Sf2 : Intl component, formatCurrency


Sf2 : Intl component, formatCurrency

我在一个trick扩展中使用intl组件来获取货币的符号。

很简单,因为这里已经很好地解释了。

但我想做的是根据货币/当地货币来制定价格。

在intl组件(NumberFormatter类)中确实有一个方法formatCurrency

<?php
namespace SE'AppBundle'Twig;
use Doctrine'ORM'EntityManager;
use Symfony'Component'HttpFoundation'RequestStack;
use Symfony'Component'Intl'Intl;
class PriceExtension extends 'Twig_Extension
{
    private $em;
    private $requestStack;
    public function __construct(EntityManager $em, RequestStack $requestStack)
    {
        $this->em = $em;
        $this->requestStack = $requestStack;
    }
    public function getFilters()
    {
        return array(
            new 'Twig_SimpleFilter('price', array($this, 'priceFilter')),
        );
    }
    public function priceFilter($price)
    {
        $request = $this->requestStack->getCurrentRequest();
        $currency_code = $request->cookies->get('currency');
        $exchange_rate = $this->em->getRepository('ApiBundle:ExchangeRates')->findOneBy(array('code' => $currency_code));
        $price = $price*$exchange_rate->getRate();
        // Get the currency symbol
        // $symbol = Intl::getCurrencyBundle()->getCurrencySymbol($currency_code); 
        // $price = $symbol.$price;
        // Undefined formatCurrency method
        $price = Intl::getCurrencyBundle()->formatCurrency($price, $currency_code);
        return $price;
    }
    public function getName()
    {
        return 'price_extension';
    }
}

我怎样才能使用formatCurrency方法?

Whole Intl Component只是在没有安装intl扩展的情况下的替换层。

所以你的代码应该看起来像:

<?php
namespace SE'AppBundle'Twig;
use Doctrine'ORM'EntityManager;
use Symfony'Component'HttpFoundation'RequestStack;
use Symfony'Component'Intl'NumberFormatter'NumberFormatter;
class PriceExtension extends 'Twig_Extension
{
    private $em;
    private $requestStack;
    public function __construct(EntityManager $em, RequestStack $requestStack)
    {
        $this->em = $em;
        $this->requestStack = $requestStack;
    }
    public function getFilters()
    {
        return array(
            new 'Twig_SimpleFilter('price', array($this, 'priceFilter')),
        );
    }
    public function priceFilter($price)
    {
        $request = $this->requestStack->getCurrentRequest();
        $currency_code = $request->cookies->get('currency');
        $exchange_rate = $this->em->getRepository('ApiBundle:ExchangeRates')->findOneBy([
            'code' => $currency_code
        ]);
        $price = $price*$exchange_rate->getRate();
        if(false === extension_loaded('intl')) {
            $formatter = new NumberFormatter('en', NumberFormatter::CURRENCY);
        } else {
            $formatter = new 'NumberFormatter(
                $request->getLocale(),
                'NumberFormatter::CURRENCY
            );
        }
        return $formatter->formatCurrency($price, $currency_code);
    }
    public function getName()
    {
        return 'price_extension';
    }
}