1<?php
2
3/*
4 * This file is part of Twig.
5 *
6 * (c) Fabien Potencier
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Twig\Node\Expression\Filter;
13
14use Twig\Compiler;
15use Twig\Node\Expression\ConditionalExpression;
16use Twig\Node\Expression\ConstantExpression;
17use Twig\Node\Expression\FilterExpression;
18use Twig\Node\Expression\GetAttrExpression;
19use Twig\Node\Expression\NameExpression;
20use Twig\Node\Expression\Test\DefinedTest;
21use Twig\Node\Node;
22
23/**
24 * Returns the value or the default value when it is undefined or empty.
25 *
26 *  {{ var.foo|default('foo item on var is not defined') }}
27 *
28 * @author Fabien Potencier <fabien@symfony.com>
29 */
30class DefaultFilter extends FilterExpression
31{
32    public function __construct(\Twig_NodeInterface $node, ConstantExpression $filterName, \Twig_NodeInterface $arguments, $lineno, $tag = null)
33    {
34        $default = new FilterExpression($node, new ConstantExpression('default', $node->getTemplateLine()), $arguments, $node->getTemplateLine());
35
36        if ('default' === $filterName->getAttribute('value') && ($node instanceof NameExpression || $node instanceof GetAttrExpression)) {
37            $test = new DefinedTest(clone $node, 'defined', new Node(), $node->getTemplateLine());
38            $false = \count($arguments) ? $arguments->getNode(0) : new ConstantExpression('', $node->getTemplateLine());
39
40            $node = new ConditionalExpression($test, $default, $false, $node->getTemplateLine());
41        } else {
42            $node = $default;
43        }
44
45        parent::__construct($node, $filterName, $arguments, $lineno, $tag);
46    }
47
48    public function compile(Compiler $compiler)
49    {
50        $compiler->subcompile($this->getNode('node'));
51    }
52}
53
54class_alias('Twig\Node\Expression\Filter\DefaultFilter', 'Twig_Node_Expression_Filter_Default');
55