Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Extending Volt: adding tests

The documentation states:

The Volt compiler allow you to extend it adding more functions, tests or filters to the existing ones.

However, only examples for functions and filters are shown. Is there an example somewhere on how to add new tests?



319
Accepted
answer

Managed to figure it out myself by looking at the Volt compiler source. The example below is implemented as a Twig extension so PhpStorm can actually autocomplete the test (given that the Symfony plugin is enabled for your project).

<?php

namespace MyApp\Volt\Test;

use Phalcon\Mvc\View\Engine\Volt\Compiler;

class RouteTest extends \Twig_Extension  {
    /** @var Compiler */
    private $compiler;

    /**
     * We require the Volt compiler to be passed through as we need
     * to compile the left part of our test expression.
     *
     * @param Compiler $compiler
     */
    public function __construct(Compiler $compiler) {
        $this->compiler = $compiler;
    }

    /**
     * @param array $expression
     * @return null|string
     */
    public function resolveExpression($expression) {
        // Only respond to "is" expressions
        if ($expression['type'] != 311) return null;
        // Only respond if the right part is PHVOLT_T_IDENTIFIER
        if ($expression['right']['type'] != 265) return null;
        // Only respond if the test is "route"
        if ($expression['right']['value'] != 'route') return null;
        // Compile the left expression
        $left = $this->compiler->expression($expression['left']);
        // Return the PHP code of our test
        return sprintf('%s == $this->router->getMatchedRoute()->getName()', $left);
    }

    /**
     * Returns the name of the extension.
     * Required to be implemented by Twig_Extension.
     *
     * @return string The extension name
     */
    public function getName()
    {
        return 'RouteTest';
    }

    /**
     * Method to let our Twig extension (and PhpStorm when using the Symfony plugin) know
     * which tests we implement.
     * @return array
     */
    public function getTests()
    {
        return [new \Twig_SimpleTest('route', [$this, 'routeTest'])];
    }

    /**
     * Dummy function used when defining our test in the getTests method.
     */
    public function routeTest() {
    }
}