<?php
namespace App\Service;
use App\Repository\CurrencyExchangerateRepository;
use Exception;
use Sherlockode\ConfigurationBundle\Manager\ParameterManagerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\User\UserInterface;
class CurrencyService
{
public function __construct(
private readonly CurrencyExchangerateRepository $currencyExchangerateRepository,
private readonly ParameterManagerInterface $parameterManager,
private readonly ParameterService $parameterService,
private readonly RequestStack $requestStack
){}
public function getCurrencies(): array
{
$currencies = [];
$parameters = $this->parameterManager->getAll();
foreach ($parameters as $key => $value) {
if (str_starts_with($key, 'Currency_')){
$currencies [$value] = $value;
}
}
return $currencies;
}
public function getSessionCurrency() : string{
$session = $this->requestStack->getSession();
return $session->get('userCurrency') ?? $this->parameterService->getReferenceCurrency();
}
/**
* @throws Exception
*/
public function convert($amount, $currencyFrom, $currencyTo) : ?float
{
$exchangeRate = $this->calculateExchangeRate($currencyFrom, $currencyTo);
return ceil($amount * $exchangeRate);
}
/**
* @throws Exception
*/
public function calculateExchangeRate($currencyFrom, $currencyTo) : float
{
if($currencyFrom == $currencyTo){
return 1.0;
}else
{
$currencyExchange = $this->currencyExchangerateRepository->findOneBy(
[
'currencyFrom' => $currencyFrom,
'currencyTo' => $currencyTo
]
);
if($currencyExchange!=null){
return $currencyExchange->getExchangeRate();
}else{
throw new Exception("Currency ExchangeRate Exception");
return 1;
}
}
}
public function getCurrenciesFromExchange(): array
{
$exchangeCurrencies = $this->currencyExchangerateRepository->findAll();
$currenciesToValues = array_map(function($currency) {
return $currency->getCurrencyTo();
}, $exchangeCurrencies);
$currencyArrayWithValues = [];
foreach ($currenciesToValues as $currency) {
$currencyArrayWithValues[$currency] = $currency;
}
return $currencyArrayWithValues;
}
public function getSaleCurrency(?UserInterface $user) : ?string
{
$customer = ($user?$user->getCustomer() : null);
if(is_null($user) || is_null($customer)){
// return $this->getSessionCurrency();
return $this->parameterService->getReferenceCurrency();
}
return $customer->getCurrency();
}
public function getISO4217Code(?string $currency) : ?int // 3 characters
{
return match ($currency) {
'TND' => 788,
'EUR' => 200,
'USD' => 100,
default => null,
};
}
}