Optional.php 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. /*
  3. * This file is part of Twig.
  4. *
  5. * (c) 2010 Fabien Potencier
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. class Twig_Extensions_Grammar_Optional extends Twig_Extensions_Grammar
  11. {
  12. protected $grammar;
  13. public function __construct()
  14. {
  15. $this->grammar = array();
  16. foreach (func_get_args() as $grammar) {
  17. $this->addGrammar($grammar);
  18. }
  19. }
  20. public function __toString()
  21. {
  22. $repr = array();
  23. foreach ($this->grammar as $grammar) {
  24. $repr[] = (string) $grammar;
  25. }
  26. return sprintf('[%s]', implode(' ', $repr));
  27. }
  28. public function addGrammar(Twig_Extensions_GrammarInterface $grammar)
  29. {
  30. $this->grammar[] = $grammar;
  31. }
  32. public function parse(Twig_Token $token)
  33. {
  34. // test if we have the optional element before consuming it
  35. if ($this->grammar[0] instanceof Twig_Extensions_Grammar_Constant) {
  36. if (!$this->parser->getStream()->test($this->grammar[0]->getType(), $this->grammar[0]->getName())) {
  37. return array();
  38. }
  39. } elseif ($this->grammar[0] instanceof Twig_Extensions_Grammar_Name) {
  40. if (!$this->parser->getStream()->test(Twig_Token::NAME_TYPE)) {
  41. return array();
  42. }
  43. } elseif ($this->parser->getStream()->test(Twig_Token::BLOCK_END_TYPE)) {
  44. // if this is not a Constant or a Name, it must be the last element of the tag
  45. return array();
  46. }
  47. $elements = array();
  48. foreach ($this->grammar as $grammar) {
  49. $grammar->setParser($this->parser);
  50. $element = $grammar->parse($token);
  51. if (is_array($element)) {
  52. $elements = array_merge($elements, $element);
  53. } else {
  54. $elements[$grammar->getName()] = $element;
  55. }
  56. }
  57. return $elements;
  58. }
  59. }