Matthias Andreas Benkard | 12a5735 | 2021-12-28 18:02:04 +0100 | [diff] [blame^] | 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 | |
| 12 | namespace Twig\TokenParser; |
| 13 | |
| 14 | use Twig\Error\SyntaxError; |
| 15 | use Twig\Node\Expression\ConstantExpression; |
| 16 | use Twig\Node\Node; |
| 17 | use Twig\Token; |
| 18 | |
| 19 | /** |
| 20 | * Imports blocks defined in another template into the current template. |
| 21 | * |
| 22 | * {% extends "base.html" %} |
| 23 | * |
| 24 | * {% use "blocks.html" %} |
| 25 | * |
| 26 | * {% block title %}{% endblock %} |
| 27 | * {% block content %}{% endblock %} |
| 28 | * |
| 29 | * @see https://twig.symfony.com/doc/templates.html#horizontal-reuse for details. |
| 30 | * |
| 31 | * @internal |
| 32 | */ |
| 33 | final class UseTokenParser extends AbstractTokenParser |
| 34 | { |
| 35 | public function parse(Token $token): Node |
| 36 | { |
| 37 | $template = $this->parser->getExpressionParser()->parseExpression(); |
| 38 | $stream = $this->parser->getStream(); |
| 39 | |
| 40 | if (!$template instanceof ConstantExpression) { |
| 41 | throw new SyntaxError('The template references in a "use" statement must be a string.', $stream->getCurrent()->getLine(), $stream->getSourceContext()); |
| 42 | } |
| 43 | |
| 44 | $targets = []; |
| 45 | if ($stream->nextIf('with')) { |
| 46 | do { |
| 47 | $name = $stream->expect(/* Token::NAME_TYPE */ 5)->getValue(); |
| 48 | |
| 49 | $alias = $name; |
| 50 | if ($stream->nextIf('as')) { |
| 51 | $alias = $stream->expect(/* Token::NAME_TYPE */ 5)->getValue(); |
| 52 | } |
| 53 | |
| 54 | $targets[$name] = new ConstantExpression($alias, -1); |
| 55 | |
| 56 | if (!$stream->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ',')) { |
| 57 | break; |
| 58 | } |
| 59 | } while (true); |
| 60 | } |
| 61 | |
| 62 | $stream->expect(/* Token::BLOCK_END_TYPE */ 3); |
| 63 | |
| 64 | $this->parser->addTrait(new Node(['template' => $template, 'targets' => new Node($targets)])); |
| 65 | |
| 66 | return new Node(); |
| 67 | } |
| 68 | |
| 69 | public function getTag(): string |
| 70 | { |
| 71 | return 'use'; |
| 72 | } |
| 73 | } |