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

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