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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
/vendor/

.idea/
57 changes: 57 additions & 0 deletions src/Controller/ExchangeController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);

namespace App\Controller;

use App\Validation\ExchangeRequestValidator;
use App\Service\ExchangeService;
use App\Http\JsonResponse;
use App\Utils\Url;

class ExchangeController
{
private ExchangeService $exchangeService;
private ExchangeRequestValidator $validator;
private Url $common;

public function __construct(
ExchangeService $exchangeService,
ExchangeRequestValidator $validator,
Url $common
)
{
$this->exchangeService = $exchangeService;
$this->validator = $validator;
$this->common = $common;
}

public function handle(string $requestUri): void
{
$segments = $this->common->getExtractSegments($requestUri);

$validation = $this->validator->validate($segments);

if ($validation['valid'] !== true) {
JsonResponse::send(['error' => $validation['message']], 400);
return;
}

[$amount, $from, $to, $rate] = $validation['segments'];

$result = $this->exchangeService->convert(
(float)$amount,
$from,
$to,
(float)$rate
);

if ($result === null) {
JsonResponse::send(['error' => 'Unsupported currency conversion.'], 400);
return;
}

JsonResponse::send($result, 200);
}


}
36 changes: 36 additions & 0 deletions src/Domain/Currency.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);

namespace App\Domain;

class Currency
{
public const string BRL = 'BRL';
public const string USD = 'USD';
public const string EUR = 'EUR';

private const array SYMBOLS = [
self::BRL => 'R$',
self::USD => '$',
self::EUR => '€',
];

public static function isSupported(string $currency): bool
{
return in_array($currency, self::supported(), true);
}

public static function supported(): array
{
return [
self::BRL,
self::USD,
self::EUR,
];
}

public static function getSymbol(string $currency): string
{
return self::SYMBOLS[$currency] ?? '';
}
}
15 changes: 15 additions & 0 deletions src/Http/JsonResponse.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);

namespace App\Http;

class JsonResponse
{
public static function send(array $data, int $statusCode): void
{
http_response_code($statusCode);
header('Content-Type: application/json; charset=utf-8');

echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
}
32 changes: 32 additions & 0 deletions src/Service/ExchangeService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace App\Service;

use App\Domain\Currency;

class ExchangeService
{
public function convert(float $amount, string $from, string $to, float $rate): ?array
{
if (!$this->isSupportedConversion($from, $to)) {
return null;
}

return [
'valorConvertido' => $amount * $rate,
'simboloMoeda' => Currency::getSymbol($to),
];
}

private function isSupportedConversion(string $from, string $to): bool
{
$supportedConversions = [
Currency::BRL . '-' . Currency::USD,
Currency::USD . '-' . Currency::BRL,
Currency::BRL . '-' . Currency::EUR,
Currency::EUR . '-' . Currency::BRL,
];

return in_array($from . '-' . $to, $supportedConversions, true);
}
}
69 changes: 69 additions & 0 deletions src/Utils/Url.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?php
declare(strict_types=1);

namespace App\Utils;
class Url
{
private function extractSegments(string $requestUri): array
{
$path = (string)parse_url($requestUri, PHP_URL_PATH);
$query = (string)parse_url($requestUri, PHP_URL_QUERY);

$candidates = [];

if ($path !== '') {
$candidates[] = $path;
}

if ($query !== '') {
parse_str($query, $queryParams);

foreach (['request', 'route', 'path', 'q'] as $key) {
if (!empty($queryParams[$key]) && is_string($queryParams[$key])) {
$candidates[] = $queryParams[$key];
}
}

if (str_contains($query, '/')) {
$candidates[] = $query;
}
}

foreach ($candidates as $candidate) {
$segments = $this->normalizeSegments($candidate);

if (count($segments) >= 4) {
return array_slice($segments, -4);
}

if ($segments !== []) {
return $segments;
}
}

return [];
}

private function normalizeSegments(string $value): array
{
$value = str_replace('index.php', '', $value);
$value = trim($value, " \t\n\r\0\x0B/");

if ($value === '') {
return [];
}

return array_values(array_filter(
explode('/', $value),
static function (string $segment): bool {
return trim($segment) !== '';
}
));
}

public function getExtractSegments(string $requestUri): array
{
return $this->extractSegments($requestUri);

}
}
92 changes: 92 additions & 0 deletions src/Validation/ExchangeRequestValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<?php
declare(strict_types=1);

namespace App\Validation;

use App\Domain\Currency;

class ExchangeRequestValidator
{
public function validate(array $segments): array
{
$segments = array_values(
array_filter(
array_map(
static function ($segment): string {
return trim((string) $segment);
},
$segments
),
static function (string $segment): bool {
return $segment !== '';
}
)
);

if (count($segments) !== 4) {
return [
'valid' => false,
'message' => 'Invalid route parameters.',
'debug' => $segments,
'count' => count($segments),
];
}

[$amount, $from, $to, $rate] = $segments;

if (!$this->isValidPositiveNumber($amount)) {
return [
'valid' => false,
'message' => 'Invalid amount.',
'debug' => $segments,
];
}

if (!$this->isValidCurrency($from)) {
return [
'valid' => false,
'message' => 'Invalid source currency.',
'debug' => $segments,
];
}

if (!$this->isValidCurrency($to)) {
return [
'valid' => false,
'message' => 'Invalid target currency.',
'debug' => $segments,
];
}

if (!$this->isValidPositiveNumber($rate)) {
return [
'valid' => false,
'message' => 'Invalid rate.',
'debug' => $segments,
];
}

return [
'valid' => true,
'segments' => $segments,
];
}

private function isValidPositiveNumber(string $value): bool
{
if (!is_numeric($value)) {
return false;
}

return (float) $value > 0;
}

private function isValidCurrency(string $currency): bool
{
if (!preg_match('/^[A-Z]{3}$/', $currency)) {
return false;
}

return Currency::isSupported($currency);
}
}
12 changes: 12 additions & 0 deletions src/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,15 @@

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

use App\Controller\ExchangeController;
use App\Service\ExchangeService;
use App\Validation\ExchangeRequestValidator;
use App\Utils\Url;

$controller = new ExchangeController(
new ExchangeService(),
new ExchangeRequestValidator(),
new Url()
);

$controller->handle($_SERVER['REQUEST_URI'] ?? '/');
Loading