From 58e3f03e226aa3adc44e812b7af22d96b86f6ad5 Mon Sep 17 00:00:00 2001 From: Ben Roberts Date: Mon, 27 Feb 2023 12:17:14 +0100 Subject: [PATCH] Default to formatting money according to default locale --- src/Resources/config/services.xml | 1 + src/Twig/Extension/FormatMoneyExtension.php | 13 +++++++++++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/Resources/config/services.xml b/src/Resources/config/services.xml index b6aff2c..47e250f 100644 --- a/src/Resources/config/services.xml +++ b/src/Resources/config/services.xml @@ -20,6 +20,7 @@ + diff --git a/src/Twig/Extension/FormatMoneyExtension.php b/src/Twig/Extension/FormatMoneyExtension.php index 7b920a2..1d9a6ac 100644 --- a/src/Twig/Extension/FormatMoneyExtension.php +++ b/src/Twig/Extension/FormatMoneyExtension.php @@ -13,6 +13,7 @@ use Money\Currencies\ISOCurrencies; use Money\Formatter\IntlMoneyFormatter; use Money\Money; +use Symfony\Component\HttpFoundation\RequestStack; use Twig\Extension\AbstractExtension; use Twig\TwigFilter; @@ -21,16 +22,24 @@ */ class FormatMoneyExtension extends AbstractExtension { + private RequestStack $requestStack; + + public function __construct(RequestStack $requestStack) + { + $this->requestStack = $requestStack; + } + public function getFilters(): array { return [new TwigFilter('money', [$this, 'moneyFilter'])]; } - public function moneyFilter(Money $money): string + public function moneyFilter(Money $money, string $locale = null): string { + $defaultLocale = $this->requestStack->getCurrentRequest()->getLocale(); $currencies = new ISOCurrencies(); - $numberFormatter = new \NumberFormatter('fr_FR', \NumberFormatter::CURRENCY); + $numberFormatter = new \NumberFormatter($locale ?? $defaultLocale ?? 'fr_FR', \NumberFormatter::CURRENCY); $moneyFormatter = new IntlMoneyFormatter($numberFormatter, $currencies); return $moneyFormatter->format($money);