<?php
namespace App\Twig;
use App\Entity\Gos\Country;
use App\Entity\Gos\CountrySettings;
use App\Utils\Region\CountryService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
class CurrencyExtension extends AbstractExtension
{
private EntityManagerInterface $em;
private ?Request $request;
private ?UserInterface $user;
private CountryService $countryService;
public function __construct(
EntityManagerInterface $em,
RequestStack $requestStack,
CountryService $countryService,
Security $security
) {
$this->em = $em;
$this->request = $requestStack->getCurrentRequest();
$this->user = $security->getUser();
$this->countryService = $countryService;
}
public function getFilters(): array
{
return array(
new TwigFilter('addCurrency', array($this, 'addCurrency'))
);
}
public function addCurrency(string $price, Country $countryParam = null): string
{
if (!isset($countryParam))
$country = $this->countryService->getCountry($this->request, $this->user);
else
$country = $countryParam;
$currency = "$";
$locale = 'pl';
try {
$locale = $this->request->getSession()->get('userLocale', 'pl');
}catch (\Exception $e){}
if (in_array(isset($countryParam) ? strtolower($countryParam->getAlpha2()) : $locale, ['pl', 'en', 'de', 'ru']))
{
$currency = $this->getCurrencyBasedOnLocale(isset($countryParam) ? strtolower($countryParam->getAlpha2()) : $locale);
}
elseif ($country)
{
$countrySettings = $this->em->getRepository(CountrySettings::class)->findOneByCountry($country);
if ($countrySettings)
{
if ($countrySettings->getSignAfterPrice())
return $price . ' ' . $countrySettings->getSignAfterPrice();
else
return $countrySettings->getSignBeforePrice() . $price;
}
}
return $price . ' ' . $currency;
}
private function getCurrencyBasedOnLocale(string $country): string
{
switch ($country)
{
case 'pl':
return 'zł';
case 'ru':
return '₽';
case 'en':
return '£';
case 'de':
default:
return '€';
}
}
}