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

Added Number extension #27

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions lib/Twig/Extensions/Extension/Number.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?php

/**
* This file is part of Twig.
*
* (c) 2009 Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Tim Nagel <tim@nagel.com.au>
* @package Twig
* @subpackage Twig-extensions
*/
class Twig_Extensions_Extension_Number extends Twig_Extension
{
/**
* Returns a list of filters.
*
* @return array
*/
public function getFilters()
{
return array(
'currency' => new Twig_Filter_Function('twig_format_currency'),
);
}

/**
* Name of this extension
*
* @return string
*/
public function getName()
{
return 'Number';
}
}

if (class_exists('NumberFormatter')) {
function twig_format_currency($value, $currency, $locale = null)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This part should be removed in favor of #55 IMO

{
static $formatter;

if (null === $locale) {
$locale = Locale::getDefault();
}

if (null === $formatter) {
$formatter = new NumberFormatter($locale, NumberFormatter::CURRENCY);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you should not use a static formatter as it will fail when using the method several times with different locales.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually you can use a static but compare the locale of the object with the given one (that is how I do it).
Most users will not change the locale during runtime so keeping this 'cache' with a locale check is better imo.

(null === $formatter || $locale !== $formatter->getLocale())

}

return $formatter->formatCurrency($value, $currency);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about making the locale configurable with a third parameter (and using the default when it is not given) ?

}
} else {
function twig_format_currency($value, $currency = null, $locale = null)
{
if (null !== $currency) {
throw new \LogicException("You must have Intl enabled to specify a currency. Pass null if you\'re trying to set the locale.");
}

if (null !== $locale) {
setlocale(LC_MONETARY, $locale);
}

return money_format("%i", $value);
}
}