picea/src/Extension/MoneyExtension.php

43 lines
1.1 KiB
PHP

<?php
namespace Picea\Extension;
use Picea\Compiler\Context;
class MoneyExtension implements Extension, FunctionExtension {
public string $token = "money";
public string $title = "";
public string $locale;
public \NumberFormatter $formatter;
public function __construct() {
$this->locale = explode('.', \Locale::getDefault())[0];
$this->formatter = new \NumberFormatter($this->locale, \NumberFormatter::CURRENCY);
}
public function exportFunctions(): array
{
return [
"money" => [ $this, 'money' ]
];
}
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token) {
return "<?php echo money($arguments) ?>";
}
public function money(float $money, ? string $currency = null) /* : string|false */
{
$this->formatter->setTextAttribute(\NumberFormatter::CURRENCY_CODE, 'CAD');
$this->formatter->setPattern( str_replace('¤#','¤ #', $this->formatter->getPattern() ) );
return $this->formatter->formatCurrency($money, $currency ?? $this->formatter->getTextAttribute(\NumberFormatter::CURRENCY_CODE));
}
}