]> git.immae.eu Git - github/wallabag/wallabag.git/blob - inc/Twig/Extensions/Grammar/Optional.php
da42748549e2744df16359d959649f62244744eb
[github/wallabag/wallabag.git] / inc / Twig / Extensions / Grammar / Optional.php
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 class Twig_Extensions_Grammar_Optional extends Twig_Extensions_Grammar
12 {
13 protected $grammar;
14
15 public function __construct()
16 {
17 $this->grammar = array();
18 foreach (func_get_args() as $grammar) {
19 $this->addGrammar($grammar);
20 }
21 }
22
23 public function __toString()
24 {
25 $repr = array();
26 foreach ($this->grammar as $grammar) {
27 $repr[] = (string) $grammar;
28 }
29
30 return sprintf('[%s]', implode(' ', $repr));
31 }
32
33 public function addGrammar(Twig_Extensions_GrammarInterface $grammar)
34 {
35 $this->grammar[] = $grammar;
36 }
37
38 public function parse(Twig_Token $token)
39 {
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())) {
43 return array();
44 }
45 } elseif ($this->grammar[0] instanceof Twig_Extensions_Grammar_Name) {
46 if (!$this->parser->getStream()->test(Twig_Token::NAME_TYPE)) {
47 return array();
48 }
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
51
52 return array();
53 }
54
55 $elements = array();
56 foreach ($this->grammar as $grammar) {
57 $grammar->setParser($this->parser);
58
59 $element = $grammar->parse($token);
60 if (is_array($element)) {
61 $elements = array_merge($elements, $element);
62 } else {
63 $elements[$grammar->getName()] = $element;
64 }
65 }
66
67 return $elements;
68 }
69 }