Skip to content

Commit

Permalink
Default to formatting money according to default locale
Browse files Browse the repository at this point in the history
  • Loading branch information
benr77 committed Feb 27, 2023
1 parent 0489416 commit 58e3f03
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
1 change: 1 addition & 0 deletions src/Resources/config/services.xml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
</service>

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

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

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

0 comments on commit 58e3f03

Please sign in to comment.