68 lines
2.0 KiB
PHP
68 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace Picea\Extension;
|
|
|
|
use Picea\Compiler\Context;
|
|
|
|
class NumberExtension implements Extension, FunctionExtension {
|
|
|
|
public string $locale;
|
|
|
|
public \NumberFormatter $formatter;
|
|
|
|
public function __construct(
|
|
public string|array $token = [ "money", "format", "format_zero" ],
|
|
public string $title = "",
|
|
) {
|
|
$this->locale = explode('.', \Locale::getDefault())[0];
|
|
}
|
|
|
|
public function exportFunctions(): array
|
|
{
|
|
return [
|
|
"money" => [ $this, 'money' ],
|
|
"format" => [ $this, 'format' ],
|
|
"format_zero" => [ $this, 'formatZero' ],
|
|
];
|
|
}
|
|
|
|
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string
|
|
{
|
|
switch($token) {
|
|
case "format":
|
|
return "<?php echo format($arguments) ?>";
|
|
|
|
case "format_zero":
|
|
return "<?php echo format_zero($arguments) ?>";
|
|
|
|
case "money":
|
|
return "<?php echo money($arguments) ?>";
|
|
|
|
}
|
|
|
|
return "";
|
|
}
|
|
|
|
public function format(int|float $num, int $decimals = 0, null|string $decimalSeparator = ".", null|string $thousandsSeparator = ",") : string
|
|
{
|
|
return number_format($num, $decimals, $decimalSeparator, $thousandsSeparator);
|
|
}
|
|
|
|
public function formatZero(int $num, int $length) : string
|
|
{
|
|
return sprintf("%0{$length}d", $num);
|
|
}
|
|
|
|
public function money(float $money, ? string $currency = null) /* : string|false */
|
|
{
|
|
$this->formatter ??= new \NumberFormatter($this->locale, \NumberFormatter::CURRENCY);
|
|
|
|
$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));
|
|
}
|
|
|
|
}
|