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\Lexer;
15use Twig\Node\Expression\Variable\AssignContextVariable;
16use Twig\Node\Nodes;
17use Twig\Parser;
18use Twig\Token;
19
20/**
21 * Base class for all token parsers.
22 *
23 * @author Fabien Potencier <fabien@symfony.com>
24 */
25abstract class AbstractTokenParser implements TokenParserInterface
26{
27    /**
28     * @var Parser
29     */
30    protected $parser;
31
32    public function setParser(Parser $parser): void
33    {
34        $this->parser = $parser;
35    }
36
37    /**
38     * Parses an assignment expression like "a, b".
39     */
40    protected function parseAssignmentExpression(): Nodes
41    {
42        $stream = $this->parser->getStream();
43        $targets = [];
44        while (true) {
45            $token = $stream->getCurrent();
46            if ($stream->test(Token::OPERATOR_TYPE) && preg_match(Lexer::REGEX_NAME, $token->getValue())) {
47                // in this context, string operators are variable names
48                $stream->next();
49            } else {
50                $stream->expect(Token::NAME_TYPE, null, 'Only variables can be assigned to');
51            }
52            $targets[] = new AssignContextVariable($token->getValue(), $token->getLine());
53
54            if (!$stream->nextIf(Token::PUNCTUATION_TYPE, ',')) {
55                break;
56            }
57        }
58
59        return new Nodes($targets);
60    }
61}
62