Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Itamar Silva #163

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions src/CurrencyConverter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

namespace App;

/**
* Class CurrencyConverter
*
* Classe responsável por converter valores entre diferentes moedas.
*
* @package App
*/
class CurrencyConverter
{
const CURRENCY_BRL = 'BRL';
const CURRENCY_USD = 'USD';
const CURRENCY_EUR = 'EUR';

/**
* Converte o valor de uma moeda para outra com base na taxa de conversão.
*
* @param float $amount Valor a ser convertido.
* @param string $fromCurrency Moeda de origem.
* @param string $toCurrency Moeda de destino.
* @param float $rate Taxa de conversão.
*
* @return float Valor convertido.
* @throws \InvalidArgumentException Caso o valor ou a taxa sejam inválidos,
* ou as moedas sejam inválidas.
*/
public function convert(float $amount, string $fromCurrency, string $toCurrency, float $rate): float
{
if ($amount <= 0 || $rate <= 0) {
throw new \InvalidArgumentException("Invalid amount or rate.");
}

if (!in_array($fromCurrency, [self::CURRENCY_BRL, self::CURRENCY_USD, self::CURRENCY_EUR], true) ||
!in_array($toCurrency, [self::CURRENCY_BRL, self::CURRENCY_USD, self::CURRENCY_EUR], true)) {
throw new \InvalidArgumentException("Invalid currency.");
}

$convertedAmount = $amount * $rate;

return round($convertedAmount, 2);
}
}
49 changes: 49 additions & 0 deletions src/Router.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

namespace App;

/**
* Class Router
*
* Classe responsável por realizar o roteamento da URL da requisição.
*
* @package App
*/
class Router
{
/**
* Realiza o roteamento da URL da requisição.
*
* @param string $url URL da requisição.
*
* @return array Dados da requisição roteada (amount, fromCurrency, toCurrency, rate).
* @throws \InvalidArgumentException Caso a ação seja inválida, o número de parâmetros seja inválido,
* ou o valor ou taxa sejam inválidos.
*/
public function route(string $url): array
{
$urlParts = explode('/', trim($url, '/'));
$action = array_shift($urlParts);

if ($action !== 'exchange') {
throw new \InvalidArgumentException("Invalid action.");
}

if (count($urlParts) !== 4) {
throw new \InvalidArgumentException("Invalid number of parameters.");
}

list($amount, $fromCurrency, $toCurrency, $rate) = $urlParts;

if (!is_numeric($amount) || !is_numeric($rate)) {
throw new \InvalidArgumentException("Invalid amount or rate.");
}

return [
'amount' => (float) $amount,
'fromCurrency' => strtoupper($fromCurrency),
'toCurrency' => strtoupper($toCurrency),
'rate' => (float) $rate,
];
}
}
34 changes: 33 additions & 1 deletion src/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,43 @@
*
* @category Challenge
* @package Back-end
* @author Seu Nome <seu-email@seu-provedor.com>
* @author Itamar Silva <itamarsilvacc@gmail.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://github.com/apiki/back-end-challenge
*/
declare(strict_types=1);

namespace App;

require __DIR__ . '/../vendor/autoload.php';

$router = new Router();
$currencyConverter = new CurrencyConverter();

try {
// Obter os dados da requisição através do roteamento
$requestData = $router->route($_SERVER['REQUEST_URI']);

// Realizar a conversão de moedas utilizando o CurrencyConverter
$convertedAmount = $currencyConverter->convert(
$requestData['amount'],
$requestData['fromCurrency'],
$requestData['toCurrency'],
$requestData['rate']
);

// Retornar a resposta em formato JSON
$response = [
'valorConvertido' => $convertedAmount,
'simboloMoeda' =>
$requestData['toCurrency'] === CurrencyConverter::CURRENCY_USD
? '$'
: 'R$',
];

header('Content-Type: application/json');
echo json_encode($response);
} catch (\InvalidArgumentException $e) {
header("HTTP/1.1 400 Bad Request");
echo json_encode(['error' => $e->getMessage()]);
}
Loading