Skip to content
Closed
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
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
/vendor/
/phpunit.xml

# PHPStorm
/.idea
30 changes: 30 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Define the PHP binary and PHPUnit comman# Define the PHP binary and PHPUnit command
PHP := php
DOCKER := docker
DOCKER_COMPOSE := docker compose
EXEC_APP := $(DOCKER_COMPOSE) exec app

.PHONY: start stop test lint help

# Start the Docker containers
start:
$(DOCKER_COMPOSE) up -d

# Stop the Docker containers
stop:
$(DOCKER_COMPOSE) down

# Run tests
test:
$(EXEC_APP) composer test

# Run tests
lint:
$(EXEC_APP) composer lint

help:
@echo "Makefile commands:"
@echo " make start - Start the Docker containers"
@echo " make stop - Stop the Docker containers"
@echo " make test - Run tests"
@echo " make lint - Run code linter"
71 changes: 71 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@

Desafio para os futuros programadores back-end da Apiki.

## Índice

- [Introdução](#introdução)
- [Instruções](#instruções)
- [Pré-requisitos](#pré-requisitos)
- [Dúvidas](#dúvidas)
- [Instalação e execução com Docker](#instalação-e-execução-com-docker)
- [Instalação e execução sem Docker (alternativa)](#instalação-e-execução-sem-docker-alternativa)

## Introdução

Desenvolva uma **REST API** que faça conversão de moedas.
Expand Down Expand Up @@ -44,3 +53,65 @@ Desenvolva uma **REST API** que faça conversão de moedas.
## Dúvidas

Em caso de dúvidas, crie uma issue.

## Instalação e execução com Docker

Para facilitar a execução do projeto, foi disponibilizado um ambiente Docker.

*Obs.: A API estará disponível em `http://localhost:8000`.*

### Pré-requisitos

* Docker >= 20.10
* Docker Compose >= 1.29

### Instalação

**1 - Clonar o repositório:**

```sh
git clone git@github.com:Apiki/back-end-challenge.git
cd back-end-challenge
```

**2 - Subir o ambiente:**

```sh
docker-compose up
```

## Comandos Úteis Docker

```bash
# Para visualizar os comandos disponíveis
make help
```

```bash
# Para inicializar o ambiente e instalar as dependências
make start
```

```bash
# Para parar o ambiente
make stop
```

```bash
# Para executar os testes usando composer
make test
```

```bash
# Para executar o lint usando composer
make lint
```

---

### Execução sem Docker (alternativa)

```sh
composer install
php -S localhost:8000 -t src
```
13 changes: 13 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
services:
app:
build:
context: .
dockerfile: docker/common/php-fpm/Dockerfile
container_name: "back-end-challenge-app"
restart: always
ports:
- "8000:8000"
working_dir: /app
volumes:
- ./:/app
command: sh -c "composer install && php -S 0.0.0.0:8000 src/index.php"
8 changes: 8 additions & 0 deletions docker/common/php-fpm/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
FROM php:7.4-cli

RUN apt-get update && apt-get install -y \
git unzip

COPY --from=composer:2.7 /usr/bin/composer /usr/bin/composer

WORKDIR /app
100 changes: 100 additions & 0 deletions src/ExchangeService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
<?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 Willian <willian@apiki.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://github.com/apiki/back-end-challenge
*/
declare(strict_types=1);

namespace App;

/**
* Service class for handling currency exchange operations.
*
* @category Challenge
* @package Back-end
* @author Willian <willian@apiki.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://github.com/apiki/back-end-challenge
*/
class ExchangeService
{
/**
* Supported currency codes and symbols.
*
* @var array<string,string>
*/
private const SUPPORTED_CURRENCIES = [
'BRL' => 'R$',
'USD' => '$',
'EUR' => '€',
];

/**
* Valid currency conversion pairs.
*
* @var array<string>
*/
private const VALID_CONVERSIONS = [
'BRL_USD',
'USD_BRL',
'BRL_EUR',
'EUR_BRL',
];

/**
* Get currency symbol.
*
* @param string $currency Currency code
*
* @return string Currency symbol
*/
public function getSymbol(string $currency): string
{
return self::SUPPORTED_CURRENCIES[$currency] ?? '';
}

/**
* Check if conversion is valid.
*
* @param string $from Source currency
* @param string $to Target currency
*
* @return bool True if valid conversion
*/
public function isValidConversion(string $from, string $to): bool
{
$conversion = "{$from}_{$to}";

return in_array($conversion, self::VALID_CONVERSIONS, true);
}

/**
* Convert amount between currencies.
*
* @param float $amount Amount to convert
* @param float $rate Exchange rate
* @param string $to Target currency
*
* @return float Converted amount
*/
public function convert(float $amount, float $rate, string $to): float
{
$convertedAmount = $amount * $rate;
$symbol = $this->getSymbol($to);

if ($symbol === '€') {
return $convertedAmount;
}

return round($convertedAmount, 1);
}
}
112 changes: 112 additions & 0 deletions src/ExchangeValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
<?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 Willian <willian@apiki.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://github.com/apiki/back-end-challenge
*/
declare(strict_types=1);

namespace App;

/**
* Validator class for exchange API input validation.
*
* @category Challenge
* @package Back-end
* @author Willian <willian@apiki.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://github.com/apiki/back-end-challenge
*/
class ExchangeValidator
{
/**
* Validate amount parameter.
*
* @param string|null $amount Amount to validate
*
* @return array Validation result
*/
public function validateAmount(?string $amount): array
{
if (!$amount) {
return ['valid' => false, 'error' => 'Amount is required'];
}

if (!is_numeric($amount)) {
return ['valid' => false, 'error' => 'Amount must be a number'];
}

$value = (float)$amount;

if ($value < 0) {
return ['valid' => false, 'error' => 'Amount must be positive'];
}

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

/**
* Validate currency parameter.
*
* @param string|null $currency Currency to validate
* @param string $field Field name for error messages
*
* @return array Validation result
*/
public function validateCurrency(?string $currency, string $field): array
{
if (!$currency) {
$msg = ucfirst($field) . ' currency is required';

return ['valid' => false, 'error' => $msg];
}

if ($currency !== strtoupper($currency)) {
$msg = ucfirst($field) . ' currency must be uppercase';

return ['valid' => false, 'error' => $msg];
}

$validCurrencies = ['BRL', 'USD', 'EUR'];

if (!in_array($currency, $validCurrencies, true)) {
return ['valid' => false, 'error' => 'Invalid ' . $field . ' currency'];
}

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

/**
* Validate rate parameter.
*
* @param string|null $rate Rate to validate
*
* @return array Validation result
*/
public function validateRate(?string $rate): array
{
if (!$rate) {
return ['valid' => false, 'error' => 'Rate is required'];
}

if (!is_numeric($rate)) {
return ['valid' => false, 'error' => 'Rate must be a number'];
}

$value = (float)$rate;

if ($value < 0) {
return ['valid' => false, 'error' => 'Rate must be positive'];
}

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