Skip to content

Instantly share code, notes, and snippets.

@geerteltink
Created June 12, 2019 14:35
Show Gist options
  • Save geerteltink/7e54e28338772de765d9d478a6f52318 to your computer and use it in GitHub Desktop.
Save geerteltink/7e54e28338772de765d9d478a6f52318 to your computer and use it in GitHub Desktop.
Twig PHP Money Extension
<?php
declare(strict_types=1);
namespace App\Infrastructure\View;
use Locale;
use Money\Currencies\ISOCurrencies;
use Money\Formatter\DecimalMoneyFormatter;
use Money\Formatter\IntlMoneyFormatter;
use Money\Money;
use NumberFormatter;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
class TwigMoneyExtension extends AbstractExtension
{
/** @var string */
private $locale;
/** @var ISOCurrencies */
private $currencies;
public function __construct(?string $locale = null)
{
if ($locale === null) {
$locale = Locale::getDefault();
}
$this->locale = $locale;
}
/**
* @return TwigFilter[]
*/
public function getFilters() : array
{
return [
new TwigFilter('money_format', [$this, 'formatMoney']),
new TwigFilter('money_decimal', [$this, 'formatDecimal']),
new TwigFilter('money_amount', [$this, 'formatAmount']),
new TwigFilter('money_currency', [$this, 'formatCurrency']),
];
}
public function formatMoney(?Money $money = null) : string
{
if ($money === null) {
return '';
}
$numberFormatter = new NumberFormatter($this->locale, NumberFormatter::CURRENCY);
$moneyFormatter = new IntlMoneyFormatter($numberFormatter, $this->getCurrencies());
return $moneyFormatter->format($money);
}
public function formatDecimal(?Money $money = null) : string
{
if ($money === null) {
return '';
}
$moneyFormatter = new DecimalMoneyFormatter($this->getCurrencies());
return $moneyFormatter->format($money);
}
public function formatAmount(?Money $money = null) : string
{
if ($money === null) {
return '';
}
$numberFormatter = new NumberFormatter($this->locale, NumberFormatter::DECIMAL);
$moneyFormatter = new IntlMoneyFormatter($numberFormatter, $this->getCurrencies());
return $moneyFormatter->format($money);
}
public function formatCurrency(?Money $money = null) : string
{
if ($money === null) {
return '';
}
return $money->getCurrency()->getCode();
}
private function getCurrencies() : ISOCurrencies
{
if (! $this->currencies) {
$this->currencies = new ISOCurrencies();
}
return $this->currencies;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment