1<?php
2
3/*
4 * This file is part of Twig.
5 *
6 * (c) 2010 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
12/**
13 * @deprecated since version 1.5
14 */
15class Twig_Extensions_Grammar_Optional extends Twig_Extensions_Grammar
16{
17    protected $grammar;
18
19    public function __construct()
20    {
21        $this->grammar = array();
22        foreach (func_get_args() as $grammar) {
23            $this->addGrammar($grammar);
24        }
25    }
26
27    public function __toString()
28    {
29        $repr = array();
30        foreach ($this->grammar as $grammar) {
31            $repr[] = (string) $grammar;
32        }
33
34        return sprintf('[%s]', implode(' ', $repr));
35    }
36
37    public function addGrammar(Twig_Extensions_GrammarInterface $grammar)
38    {
39        $this->grammar[] = $grammar;
40    }
41
42    public function parse(Twig_Token $token)
43    {
44        // test if we have the optional element before consuming it
45        if ($this->grammar[0] instanceof Twig_Extensions_Grammar_Constant) {
46            if (!$this->parser->getStream()->test($this->grammar[0]->getType(), $this->grammar[0]->getName())) {
47                return array();
48            }
49        } elseif ($this->grammar[0] instanceof Twig_Extensions_Grammar_Name) {
50            if (!$this->parser->getStream()->test(Twig_Token::NAME_TYPE)) {
51                return array();
52            }
53        } elseif ($this->parser->getStream()->test(Twig_Token::BLOCK_END_TYPE)) {
54            // if this is not a Constant or a Name, it must be the last element of the tag
55
56            return array();
57        }
58
59        $elements = array();
60        foreach ($this->grammar as $grammar) {
61            $grammar->setParser($this->parser);
62
63            $element = $grammar->parse($token);
64            if (is_array($element)) {
65                $elements = array_merge($elements, $element);
66            } else {
67                $elements[$grammar->getName()] = $element;
68            }
69        }
70
71        return $elements;
72    }
73}
74