Set.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. public function parse(Twig_Token $token)
  30. {
  31. $lineno = $token->getLine();
  32. $stream = $this->parser->getStream();
  33. $names = $this->parser->getExpressionParser()->parseAssignmentExpression();
  34. $capture = false;
  35. if ($stream->nextIf(Twig_Token::OPERATOR_TYPE, '=')) {
  36. $values = $this->parser->getExpressionParser()->parseMultitargetExpression();
  37. $stream->expect(Twig_Token::BLOCK_END_TYPE);
  38. if (count($names) !== count($values)) {
  39. throw new Twig_Error_Syntax('When using set, you must have the same number of variables and assignments.', $stream->getCurrent()->getLine(), $stream->getFilename());
  40. }
  41. } else {
  42. $capture = true;
  43. if (count($names) > 1) {
  44. throw new Twig_Error_Syntax('When using set with a block, you cannot have a multi-target.', $stream->getCurrent()->getLine(), $stream->getFilename());
  45. }
  46. $stream->expect(Twig_Token::BLOCK_END_TYPE);
  47. $values = $this->parser->subparse(array($this, 'decideBlockEnd'), true);
  48. $stream->expect(Twig_Token::BLOCK_END_TYPE);
  49. }
  50. return new Twig_Node_Set($capture, $names, $values, $lineno, $this->getTag());
  51. }
  52. public function decideBlockEnd(Twig_Token $token)
  53. {
  54. return $token->test('endset');
  55. }
  56. public function getTag()
  57. {
  58. return 'set';
  59. }
  60. }