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

declare(strict_types=1);

namespace App;

class CurrencyConverter
{
private const CURRENCY_SYMBOLS = [
'BRL' => 'R$',
'USD' => '$',
'EUR' => '€',
];

public function convert(
float $amount,
string $from,
string $to,
float $rate
): array {
$validFrom = isset(self::CURRENCY_SYMBOLS[$from]);
$validTo = isset(self::CURRENCY_SYMBOLS[$to]);

if (!$validFrom || !$validTo) {
throw new \InvalidArgumentException(
'Invalid source or destination currency'
);
}

if ($rate <= 0 || $amount < 0) {
throw new \InvalidArgumentException('Invalid rate or amount');
}

$convertedAmount = $amount * $rate;

return [
'valorConvertido' => round($convertedAmount, 2),
'simboloMoeda' => self::CURRENCY_SYMBOLS[$to],
];
}
}
44 changes: 31 additions & 13 deletions src/index.php
Original file line number Diff line number Diff line change
@@ -1,18 +1,36 @@
<?php
/**
* Back-end Challenge.
*
* PHP version 7.4
*
* Este será o arquivo chamado na execução dos testes automátizados.
*
* @category Challenge
* @package Back-end
* @author Seu Nome <seu-email@seu-provedor.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';

use App\CurrencyConverter;

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

$requestUri = $_SERVER['REQUEST_URI'];
$path = (string) parse_url($requestUri, PHP_URL_PATH);

$pattern = '/^\/exchange\/([0-9.]+)\/([A-Z]{3})\/([A-Z]{3})\/([0-9.]+)$/';
if (preg_match($pattern, $path, $matches)) {
$amount = (float) $matches[1];
$from = $matches[2];
$to = $matches[3];
$rate = (float) $matches[4];

try {
$converter = new CurrencyConverter();
$result = $converter->convert($amount, $from, $to, $rate);
echo json_encode($result);
http_response_code(200);
} catch (\InvalidArgumentException $e) {
http_response_code(400);
echo json_encode(['error' => $e->getMessage()]);
} catch (\Throwable $e) {
http_response_code(500);
echo json_encode(['error' => 'Internal Server Error']);
}
} else {
http_response_code(400);
echo json_encode(['error' => 'Invalid URL or missing parameters']);
}
Loading