File: CacheTokenParser.php

package info (click to toggle)
php-twig 3.20.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 5,940 kB
  • sloc: php: 23,320; makefile: 110; sh: 43
file content (75 lines) | stat: -rw-r--r-- 2,457 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php

/*
 * This file is part of Twig.
 *
 * (c) Fabien Potencier
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Twig\Extra\Cache\TokenParser;

use Twig\Error\SyntaxError;
use Twig\Extra\Cache\Node\CacheNode;
use Twig\Node\Expression\Filter\RawFilter;
use Twig\Node\Node;
use Twig\Node\PrintNode;
use Twig\Token;
use Twig\TokenParser\AbstractTokenParser;

class CacheTokenParser extends AbstractTokenParser
{
    public function parse(Token $token): Node
    {
        $stream = $this->parser->getStream();
        $expressionParser = $this->parser->getExpressionParser();
        $key = $expressionParser->parseExpression();

        $ttl = null;
        $tags = null;
        while ($stream->test(Token::NAME_TYPE)) {
            $k = $stream->getCurrent()->getValue();
            if (!in_array($k, ['ttl', 'tags'])) {
                throw new SyntaxError(\sprintf('Unknown "%s" configuration.', $k), $stream->getCurrent()->getLine(), $stream->getSourceContext());
            }

            $stream->next();
            $stream->expect(Token::PUNCTUATION_TYPE, '(');
            $line = $stream->getCurrent()->getLine();
            if ($stream->test(Token::PUNCTUATION_TYPE, ')')) {
                throw new SyntaxError(\sprintf('The "%s" modifier takes exactly one argument (0 given).', $k), $line, $stream->getSourceContext());
            }
            $arg = $expressionParser->parseExpression();
            if ($stream->test(Token::PUNCTUATION_TYPE, ',')) {
                throw new SyntaxError(\sprintf('The "%s" modifier takes exactly one argument (2 given).', $k), $line, $stream->getSourceContext());
            }
            $stream->expect(Token::PUNCTUATION_TYPE, ')');

            if ('ttl' === $k) {
                $ttl = $arg;
            } elseif ('tags' === $k) {
                $tags = $arg;
            }
        }

        $stream->expect(Token::BLOCK_END_TYPE);
        $body = $this->parser->subparse([$this, 'decideCacheEnd'], true);
        $stream->expect(Token::BLOCK_END_TYPE);

        $body = new CacheNode($key, $ttl, $tags, $body, $token->getLine());

        return new PrintNode(new RawFilter($body), $token->getLine());
    }

    public function decideCacheEnd(Token $token): bool
    {
        return $token->test('endcache');
    }

    public function getTag(): string
    {
        return 'cache';
    }
}