Optional.php 2.0 KB

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