From 02edbc80f39eccd7ddc645802e00a616323f1012 Mon Sep 17 00:00:00 2001 From: Ben Roberts Date: Sat, 13 May 2023 15:10:08 +0200 Subject: [PATCH] Use Translator service to get current locale instead of the RequestStack This is because in console commands the RequestStack does not contain any Requests. --- src/Resources/config/services.xml | 2 +- src/Twig/Extension/FormatMoneyExtension.php | 13 +++++-------- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/src/Resources/config/services.xml b/src/Resources/config/services.xml index 47e250f..0f5db7f 100644 --- a/src/Resources/config/services.xml +++ b/src/Resources/config/services.xml @@ -20,7 +20,7 @@ - + diff --git a/src/Twig/Extension/FormatMoneyExtension.php b/src/Twig/Extension/FormatMoneyExtension.php index 316ccea..f7b35b9 100644 --- a/src/Twig/Extension/FormatMoneyExtension.php +++ b/src/Twig/Extension/FormatMoneyExtension.php @@ -13,8 +13,7 @@ use Money\Currencies\ISOCurrencies; use Money\Formatter\IntlMoneyFormatter; use Money\Money; -use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Contracts\Translation\TranslatorInterface; use Twig\Extension\AbstractExtension; use Twig\TwigFilter; @@ -23,11 +22,11 @@ */ class FormatMoneyExtension extends AbstractExtension { - private RequestStack $requestStack; + private TranslatorInterface $translator; - public function __construct(RequestStack $requestStack) + public function __construct(TranslatorInterface $translator) { - $this->requestStack = $requestStack; + $this->translator = $translator; } public function getFilters(): array @@ -37,9 +36,7 @@ public function getFilters(): array public function moneyFilter(Money $money, string $locale = null): string { - /** @var Request $request */ - $request = $this->requestStack->getCurrentRequest(); - $defaultLocale = $request->getLocale(); + $defaultLocale = $this->translator->getLocale(); $numberFormatter = new \NumberFormatter($locale ?? $defaultLocale, \NumberFormatter::CURRENCY); $moneyFormatter = new IntlMoneyFormatter($numberFormatter, new ISOCurrencies());