blob: b674bea4ab08968461cb038f0e8c01c26256fd46 [file] [log] [blame]
Matthias Andreas Benkard12a57352021-12-28 18:02:04 +01001<?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\AutoEscapeNode;
16use Twig\Node\Expression\ConstantExpression;
17use Twig\Node\Node;
18use Twig\Token;
19
20/**
21 * Marks a section of a template to be escaped or not.
22 *
23 * @internal
24 */
25final class AutoEscapeTokenParser extends AbstractTokenParser
26{
27 public function parse(Token $token): Node
28 {
29 $lineno = $token->getLine();
30 $stream = $this->parser->getStream();
31
32 if ($stream->test(/* Token::BLOCK_END_TYPE */ 3)) {
33 $value = 'html';
34 } else {
35 $expr = $this->parser->getExpressionParser()->parseExpression();
36 if (!$expr instanceof ConstantExpression) {
37 throw new SyntaxError('An escaping strategy must be a string or false.', $stream->getCurrent()->getLine(), $stream->getSourceContext());
38 }
39 $value = $expr->getAttribute('value');
40 }
41
42 $stream->expect(/* Token::BLOCK_END_TYPE */ 3);
43 $body = $this->parser->subparse([$this, 'decideBlockEnd'], true);
44 $stream->expect(/* Token::BLOCK_END_TYPE */ 3);
45
46 return new AutoEscapeNode($value, $body, $lineno, $this->getTag());
47 }
48
49 public function decideBlockEnd(Token $token): bool
50 {
51 return $token->test('endautoescape');
52 }
53
54 public function getTag(): string
55 {
56 return 'autoescape';
57 }
58}