Set.php 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /*
  3. * This file is part of Twig.
  4. *
  5. * (c) 2009 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. * Defines a variable.
  12. *
  13. * <pre>
  14. * {% set foo = 'foo' %}
  15. *
  16. * {% set foo = [1, 2] %}
  17. *
  18. * {% set foo = {'foo': 'bar'} %}
  19. *
  20. * {% set foo = 'foo' ~ 'bar' %}
  21. *
  22. * {% set foo, bar = 'foo', 'bar' %}
  23. *
  24. * {% set foo %}Some content{% endset %}
  25. * </pre>
  26. */
  27. class Twig_TokenParser_Set extends Twig_TokenParser
  28. {
  29. /**
  30. * Parses a token and returns a node.
  31. *
  32. * @param Twig_Token $token A Twig_Token instance
  33. *
  34. * @return Twig_NodeInterface A Twig_NodeInterface instance
  35. */
  36. public function parse(Twig_Token $token)
  37. {
  38. $lineno = $token->getLine();
  39. $stream = $this->parser->getStream();
  40. $names = $this->parser->getExpressionParser()->parseAssignmentExpression();
  41. $capture = false;
  42. if ($stream->test(Twig_Token::OPERATOR_TYPE, '=')) {
  43. $stream->next();
  44. $values = $this->parser->getExpressionParser()->parseMultitargetExpression();
  45. $stream->expect(Twig_Token::BLOCK_END_TYPE);
  46. if (count($names) !== count($values)) {
  47. throw new Twig_Error_Syntax("When using set, you must have the same number of variables and assignements.", $lineno);
  48. }
  49. } else {
  50. $capture = true;
  51. if (count($names) > 1) {
  52. throw new Twig_Error_Syntax("When using set with a block, you cannot have a multi-target.", $lineno);
  53. }
  54. $stream->expect(Twig_Token::BLOCK_END_TYPE);
  55. $values = $this->parser->subparse(array($this, 'decideBlockEnd'), true);
  56. $stream->expect(Twig_Token::BLOCK_END_TYPE);
  57. }
  58. return new Twig_Node_Set($capture, $names, $values, $lineno, $this->getTag());
  59. }
  60. public function decideBlockEnd(Twig_Token $token)
  61. {
  62. return $token->test('endset');
  63. }
  64. /**
  65. * Gets the tag name associated with this token parser.
  66. *
  67. * @return string The tag name
  68. */
  69. public function getTag()
  70. {
  71. return 'set';
  72. }
  73. }