vendor/twig/twig/src/TokenParser/SetTokenParser.php line 58

Open in your IDE?
  1. <?php
  2. /*
  3. * This file is part of Twig.
  4. *
  5. * (c) 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. namespace Twig\TokenParser;
  11. use Twig\Error\SyntaxError;
  12. use Twig\Node\SetNode;
  13. use Twig\Token;
  14. /**
  15. * Defines a variable.
  16. *
  17. * {% set foo = 'foo' %}
  18. * {% set foo = [1, 2] %}
  19. * {% set foo = {'foo': 'bar'} %}
  20. * {% set foo = 'foo' ~ 'bar' %}
  21. * {% set foo, bar = 'foo', 'bar' %}
  22. * {% set foo %}Some content{% endset %}
  23. */
  24. final class SetTokenParser extends AbstractTokenParser
  25. {
  26. public function parse(Token $token)
  27. {
  28. $lineno = $token->getLine();
  29. $stream = $this->parser->getStream();
  30. $names = $this->parser->getExpressionParser()->parseAssignmentExpression();
  31. $capture = false;
  32. if ($stream->nextIf(/* Token::OPERATOR_TYPE */ 8, '=')) {
  33. $values = $this->parser->getExpressionParser()->parseMultitargetExpression();
  34. $stream->expect(/* Token::BLOCK_END_TYPE */ 3);
  35. if (\count($names) !== \count($values)) {
  36. throw new SyntaxError('When using set, you must have the same number of variables and assignments.', $stream->getCurrent()->getLine(), $stream->getSourceContext());
  37. }
  38. } else {
  39. $capture = true;
  40. if (\count($names) > 1) {
  41. throw new SyntaxError('When using set with a block, you cannot have a multi-target.', $stream->getCurrent()->getLine(), $stream->getSourceContext());
  42. }
  43. $stream->expect(/* Token::BLOCK_END_TYPE */ 3);
  44. $values = $this->parser->subparse([$this, 'decideBlockEnd'], true);
  45. $stream->expect(/* Token::BLOCK_END_TYPE */ 3);
  46. }
  47. return new SetNode($capture, $names, $values, $lineno, $this->getTag());
  48. }
  49. public function decideBlockEnd(Token $token)
  50. {
  51. return $token->test('endset');
  52. }
  53. public function getTag()
  54. {
  55. return 'set';
  56. }
  57. }
  58. class_alias('Twig\TokenParser\SetTokenParser', 'Twig_TokenParser_Set');