4 * This file is part of Twig.
6 * (c) 2010 Fabien Potencier
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
11 class Twig_Extensions_Grammar_Optional
extends Twig_Extensions_Grammar
15 public function __construct()
17 $this->grammar
= array();
18 foreach (func_get_args() as $grammar) {
19 $this->addGrammar($grammar);
23 public function __toString()
26 foreach ($this->grammar
as $grammar) {
27 $repr[] = (string) $grammar;
30 return sprintf('[%s]', implode(' ', $repr));
33 public function addGrammar(Twig_Extensions_GrammarInterface
$grammar)
35 $this->grammar
[] = $grammar;
38 public function parse(Twig_Token
$token)
40 // test if we have the optional element before consuming it
41 if ($this->grammar
[0] instanceof Twig_Extensions_Grammar_Constant
) {
42 if (!$this->parser
->getStream()->test($this->grammar
[0]->getType(), $this->grammar
[0]->getName())) {
45 } elseif ($this->grammar
[0] instanceof Twig_Extensions_Grammar_Name
) {
46 if (!$this->parser
->getStream()->test(Twig_Token
::NAME_TYPE
)) {
49 } elseif ($this->parser
->getStream()->test(Twig_Token
::BLOCK_END_TYPE
)) {
50 // if this is not a Constant or a Name, it must be the last element of the tag
56 foreach ($this->grammar
as $grammar) {
57 $grammar->setParser($this->parser
);
59 $element = $grammar->parse($token);
60 if (is_array($element)) {
61 $elements = array_merge($elements, $element);
63 $elements[$grammar->getName()] = $element;