Skip to content
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
51 changes: 51 additions & 0 deletions src/CurrencyConverter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

namespace App;

/**
* Classe responsável por realizar a conversão de moedas.
*/
class CurrencyConverter
{
/**
* Realiza a conversão de moeda.
*
* @param float $amount O valor a ser convertido.
* @param string $from A moeda de origem (ex: 'BRL', 'USD', 'EUR' - já validado em maiúsculas no index.php).
* @param string $to A moeda de destino (ex: 'BRL', 'USD', 'EUR' - já validado em maiúsculas no index.php).
* @param float $rate A taxa de câmbio entre as moedas.
* @return float O valor convertido, arredondado conforme necessário para os testes.
* @throws \InvalidArgumentException Se as moedas forem inválidas ou a taxa for negativa/zero.
*/
public function convert(float $amount, string $from, string $to, float $rate): float
{
if ($from === $to) {
return $amount;
}

$convertedAmount = 0;

switch ($from) {
case 'BRL':
if ($to === 'USD') {
$convertedAmount = $amount / $rate;
$convertedAmount = $amount * $rate;
} elseif ($to === 'EUR') {
$convertedAmount = $amount * $rate;
}
break;
case 'USD':
if ($to === 'BRL') {
$convertedAmount = $amount * $rate;
}
break;
case 'EUR':
if ($to === 'BRL') {
$convertedAmount = $amount * $rate;
}
break;
}

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

return [
'currency_symbols' => [
'BRL' => 'R$',
'USD' => '$',
'EUR' => '€',
],
];
81 changes: 80 additions & 1 deletion src/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,90 @@
*
* @category Challenge
* @package Back-end
* @author Seu Nome <seu-email@seu-provedor.com>
* @author Marcelo Tomaz <celo.willyan@gmail.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://github.com/apiki/back-end-challenge
*/
declare(strict_types=1);

require __DIR__ . '/../vendor/autoload.php';
$config = require __DIR__ . '/config.php';

use App\CurrencyConverter;

header('Content-Type: application/json');

$requestUri = $_SERVER['REQUEST_URI'];
$path = parse_url($requestUri, PHP_URL_PATH);
$segments = explode('/', trim($path, '/'));

$amount_str = null;
$from = null;
$to = null;
$rate_str = null;

$is_exchange_route = false;
if (isset($segments[0]) && $segments[0] === 'exchange') {
if (count($segments) === 5) {
$amount_str = $segments[1];
$from = $segments[2];
$to = $segments[3];
$rate_str = $segments[4];
$is_exchange_route = true;
}
} elseif (count($segments) === 4) {
$amount_str = $segments[0];
$from = $segments[1];
$to = $segments[2];
$rate_str = $segments[3];
$is_exchange_route = true;
}

$response = [];
try {
if (!$is_exchange_route || $amount_str === null || $from === null || $to === null || $rate_str === null) {
throw new \InvalidArgumentException('Parâmetros da requisição inválidos ou ausentes.');
}

if (!is_numeric($amount_str) || (float)$amount_str < 0) {
throw new \InvalidArgumentException('O valor a ser convertido (amount) deve ser um número positivo ou zero.');
}
$amount = (float) $amount_str;

$valid_currencies_case_sensitive = ['BRL', 'USD', 'EUR'];
if (!in_array($from, $valid_currencies_case_sensitive)) {
throw new \InvalidArgumentException('Moeda de origem (from) inválida. Use BRL, USD ou EUR em maiúsculas.');
}
if (!in_array($to, $valid_currencies_case_sensitive)) {
throw new \InvalidArgumentException('Moeda de destino (to) inválida. Use BRL, USD ou EUR em maiúsculas.');
}

if (!is_numeric($rate_str) || (float)$rate_str <= 0) {
throw new \InvalidArgumentException('A taxa de câmbio (rate) deve ser um valor positivo.');
}
$rate = (float) $rate_str;

$converter = new CurrencyConverter();
$convertedValue = $converter->convert($amount, $from, $to, $rate);

$symbol = $config['currency_symbols'][$to] ?? '';

$response = [
'valorConvertido' => $convertedValue,
'simboloMoeda' => $symbol,
];

http_response_code(200);
} catch (\InvalidArgumentException $e) {
http_response_code(400);
$response = [
'error' => $e->getMessage(),
];
} catch (\Throwable $e) {
http_response_code(500);
$response = [
'error' => 'Ocorreu um erro interno: ' . $e->getMessage(),
];
}

echo json_encode($response);
Loading