diff --git a/src/CurrencyConverter.php b/src/CurrencyConverter.php new file mode 100644 index 00000000..1eabda11 --- /dev/null +++ b/src/CurrencyConverter.php @@ -0,0 +1,41 @@ + '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], + ]; + } +} diff --git a/src/index.php b/src/index.php index 92841bc8..6a1d6d19 100644 --- a/src/index.php +++ b/src/index.php @@ -1,18 +1,36 @@ - * @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']); +}