Skip to content

Commit

Permalink
Use Translator service to get current locale instead of the RequestStack
Browse files Browse the repository at this point in the history
This is because in console commands the RequestStack does not contain
any Requests.
  • Loading branch information
benr77 committed May 13, 2023
1 parent 6ee50d7 commit 02edbc8
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 9 deletions.
2 changes: 1 addition & 1 deletion src/Resources/config/services.xml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
</service>

<service id="headsnet_money.twig.extension.format" class="Headsnet\MoneyBundle\Twig\Extension\FormatMoneyExtension" public="false">
<argument type="service" id="request_stack"/>
<argument type="service" id="translator"/>
<tag name="twig.extension"/>
</service>

Expand Down
13 changes: 5 additions & 8 deletions src/Twig/Extension/FormatMoneyExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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
Expand All @@ -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());
Expand Down

0 comments on commit 02edbc8

Please sign in to comment.