2
votes

I need to know how can I get a filter from another filter, I have the next code. Maybe I have to use Twig_Enviroment, but I don't how.

The Idea is:

  • The filter A converts a number in words. This is done.
  • The filter B should use filter A to convert a currency value to words.

    class CurrencyToWordsExtension extends \Twig_Extension { public function getFilters() { return array( new \Twig_SimpleFilter('currencyToWords', array($this, 'currencyToWordsFilter')) ); }

    function currencyToWordsFilter($number)
    {
        // $toWords = $env->getFilter('toWords');
        $number = number_format((float)$number, 2);
        $pesos = floor($number);
        $centavos = ($number - $pesos) * 100;
    
        return $pesos .' con '. $centavos;
    
    }
    
    public function getName()
    {
        return 'currencyToWords';
    }
    

    }

2

2 Answers

3
votes
class SomeExtension extends \Twig_Extension {
    function getName() {
        return 'some_extension';
    }

    function getFilters() {
        return [
            new \Twig_SimpleFilter(
                'filterOne',
                function(\Twig_Environment $env, $input) {
                    $output = dosmth($input);
                    $filter2Func = $env->getFilter('otherFiltersName')->getCallable();
                    $output = call_user_func($filter2Func, $output);
                    return $output;
                },
                ['needs_environment' => true]
            )
        ];
    }
}
1
votes

There are a lot of possibilities:

  • Move out logic from filters to separate classes. Filters should be light wrappers of complicated logic.
  • Move both of filters in the same Twig Extension class (if they are simple and both are your code). Then you can call internal class method.
  • Inject dependencies into Twig Extension class constructor in services.yml

services.yml

services:
    twig.currency_extension:
        class: AppBundle\Twig\CurrencyExtension
        public: false
        arguments: [ '@twig.words_extension' ]
        tags:
            - { name: twig.extension }

CurrencyExtension.php

class CurreycExtension extends Twig_Extension
{
    /** @var WordsExtension */
    private $wordsExtension;

    public __construct(WordsExtension $wordsExtension)
    {
        $this->wordsExtension = $wordsExtension
    }

    //...
}

Also try naming filters according to twig conventions: snake_case, short.