1<?php 2 3/* 4 * This file is part of Twig. 5 * 6 * (c) Fabien Potencier 7 * 8 * For the full copyright and license information, please view the LICENSE 9 * file that was distributed with this source code. 10 */ 11 12namespace Twig\TokenParser; 13 14use Twig\Error\SyntaxError; 15use Twig\Node\SetNode; 16use Twig\Token; 17 18/** 19 * Defines a variable. 20 * 21 * {% set foo = 'foo' %} 22 * {% set foo = [1, 2] %} 23 * {% set foo = {'foo': 'bar'} %} 24 * {% set foo = 'foo' ~ 'bar' %} 25 * {% set foo, bar = 'foo', 'bar' %} 26 * {% set foo %}Some content{% endset %} 27 * 28 * @final 29 */ 30class SetTokenParser extends AbstractTokenParser 31{ 32 public function parse(Token $token) 33 { 34 $lineno = $token->getLine(); 35 $stream = $this->parser->getStream(); 36 $names = $this->parser->getExpressionParser()->parseAssignmentExpression(); 37 38 $capture = false; 39 if ($stream->nextIf(Token::OPERATOR_TYPE, '=')) { 40 $values = $this->parser->getExpressionParser()->parseMultitargetExpression(); 41 42 $stream->expect(Token::BLOCK_END_TYPE); 43 44 if (\count($names) !== \count($values)) { 45 throw new SyntaxError('When using set, you must have the same number of variables and assignments.', $stream->getCurrent()->getLine(), $stream->getSourceContext()); 46 } 47 } else { 48 $capture = true; 49 50 if (\count($names) > 1) { 51 throw new SyntaxError('When using set with a block, you cannot have a multi-target.', $stream->getCurrent()->getLine(), $stream->getSourceContext()); 52 } 53 54 $stream->expect(Token::BLOCK_END_TYPE); 55 56 $values = $this->parser->subparse([$this, 'decideBlockEnd'], true); 57 $stream->expect(Token::BLOCK_END_TYPE); 58 } 59 60 return new SetNode($capture, $names, $values, $lineno, $this->getTag()); 61 } 62 63 public function decideBlockEnd(Token $token) 64 { 65 return $token->test('endset'); 66 } 67 68 public function getTag() 69 { 70 return 'set'; 71 } 72} 73 74class_alias('Twig\TokenParser\SetTokenParser', 'Twig_TokenParser_Set'); 75