Skip to content
This repository has been archived by the owner on Nov 2, 2020. It is now read-only.

Commit

Permalink
Added new filters localizednumber and localizedcurrency on Intl exten…
Browse files Browse the repository at this point in the history
…sion
  • Loading branch information
Garfield-fr authored and Michaël Perrin committed Jul 24, 2014
1 parent b713aaf commit 448a309
Showing 1 changed file with 51 additions and 1 deletion.
52 changes: 51 additions & 1 deletion lib/Twig/Extensions/Extension/Intl.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class Twig_Extensions_Extension_Intl extends Twig_Extension
{
public function __construct()
{
if (!class_exists('IntlDateFormatter')) {
if (!class_exists('IntlDateFormatter') || !class_exists('NumberFormatter')) {
throw new RuntimeException('The intl extension is needed to use intl-based filters.');
}
}
Expand All @@ -27,6 +27,8 @@ public function getFilters()
{
return array(
new Twig_SimpleFilter('localizeddate', 'twig_localized_date_filter', array('needs_environment' => true)),
new Twig_SimpleFilter('localizednumber', 'twig_localized_number_filter'),
new Twig_SimpleFilter('localizedcurrency', 'twig_localized_currency_filter'),
);
}

Expand Down Expand Up @@ -64,3 +66,51 @@ function twig_localized_date_filter(Twig_Environment $env, $date, $dateFormat =

return $formatter->format($date->getTimestamp());
}

function twig_localized_number_filter($number, $style = 'decimal', $format = 'default', $currency = null, $locale = null )
{
$formatter = getNumberFormatter(
$locale !== null ? $locale : Locale::getDefault(),
$style
);

$formatValues = array(
'default' => NumberFormatter::TYPE_DEFAULT,
'int32' => NumberFormatter::TYPE_INT32,
'int64' => NumberFormatter::TYPE_INT64,
'double' => NumberFormatter::TYPE_DOUBLE,
'currency' => NumberFormatter::TYPE_CURRENCY,
);

return $formatter->format(
$number,
$formatValues[$format]);
}

function twig_localized_currency_filter($number, $currency = null, $locale = null)
{
$formatter = getNumberFormatter(
$locale !== null ? $locale : Locale::getDefault(),
'currency'
);

return $formatter->formatCurrency($number, $currency);
}

function getNumberFormatter($locale, $style)
{
$styleValues = array(
'decimal' => NumberFormatter::DECIMAL,
'currency' => NumberFormatter::CURRENCY,
'percent' => NumberFormatter::PERCENT,
'scientific' => NumberFormatter::SCIENTIFIC,
'spellout' => NumberFormatter::SPELLOUT,
'ordinal' => NumberFormatter::ORDINAL,
'duration' => NumberFormatter::DURATION,
);

return NumberFormatter::create(
$locale !== null ? $locale : Locale::getDefault(),
$styleValues[$style]
);
}

0 comments on commit 448a309

Please sign in to comment.