src/Twig/BloCurrencyExtension.php line 78

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Twig;
  4. use App\Entity\Blo\Product;
  5. use App\Service\Blo\CurrencyConverter;
  6. use Symfony\Component\HttpFoundation\RequestStack;
  7. use Twig\Extension\AbstractExtension;
  8. use Twig\Extension\GlobalsInterface;
  9. use Twig\TwigFilter;
  10. use Twig\TwigFunction;
  11. class BloCurrencyExtension extends AbstractExtension implements GlobalsInterface
  12. {
  13.     public function __construct(
  14.         private readonly RequestStack $requestStack,
  15.         private readonly CurrencyConverter $converter,
  16.     ) {
  17.     }
  18.     public function getFilters(): array
  19.     {
  20.         return [
  21.             new TwigFilter('blo_price', [$this'formatPrice']),
  22.         ];
  23.     }
  24.     public function getFunctions(): array
  25.     {
  26.         return [
  27.             new TwigFunction('blo_currency_label', [$this'getCurrencyLabel']),
  28.         ];
  29.     }
  30.     /**
  31.      * Convertit un montant depuis sa devise d'origine vers la devise sélectionnée
  32.      * par l'utilisateur, puis le formate avec le libellé d'affichage (ex. F CFA).
  33.      *
  34.      * Usage Twig : {{ product.price|blo_price(product.currency) }}
  35.      *              {{ order.totalGrand|blo_price }}    (suppose XOF par défaut)
  36.      */
  37.     public function formatPrice(float|string|null $amountstring $fromCurrency 'XOF'): string
  38.     {
  39.         if ($amount === null || $amount === '') {
  40.             return '';
  41.         }
  42.         $targetCurrency $this->getCurrentCurrency();
  43.         $converted $this->converter->convert($amount$fromCurrency$targetCurrency);
  44.         $decimals $this->converter->getDecimals($targetCurrency);
  45.         return number_format($converted$decimals','' ') . ' ' $this->getCurrencyLabel($targetCurrency);
  46.     }
  47.     public function getCurrencyLabel(string $code): string
  48.     {
  49.         return Product::CURRENCY_DISPLAY[$code] ?? $code;
  50.     }
  51.     public function getGlobals(): array
  52.     {
  53.         return [
  54.             'blo_current_currency' => $this->getCurrentCurrency(),
  55.             'blo_currencies' => Product::CURRENCIES,
  56.             'blo_currency_display' => Product::CURRENCY_DISPLAY,
  57.         ];
  58.     }
  59.     private function getCurrentCurrency(): string
  60.     {
  61.         $request $this->requestStack->getCurrentRequest();
  62.         if ($request === null || !$request->hasSession()) {
  63.             return 'XOF';
  64.         }
  65.         $currency $request->getSession()->get('_currency''XOF');
  66.         if (!is_string($currency) || !array_key_exists($currencyProduct::CURRENCIES)) {
  67.             return 'XOF';
  68.         }
  69.         return $currency;
  70.     }
  71. }