-
Notifications
You must be signed in to change notification settings - Fork 619
/
CacheTokenParser.php
119 lines (106 loc) · 3.22 KB
/
CacheTokenParser.php
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\web\twig\tokenparsers;
use craft\web\twig\nodes\CacheNode;
use Twig\Parser;
use Twig\Token;
use Twig\TokenParser\AbstractTokenParser;
/**
* Class CacheTokenParser
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 3.0.0
*/
class CacheTokenParser extends AbstractTokenParser
{
/**
* @return string
*/
public function getTag(): string
{
return 'cache';
}
/**
* @inheritdoc
*/
public function parse(Token $token)
{
$lineno = $token->getLine();
/** @var Parser $parser */
$parser = $this->parser;
$stream = $parser->getStream();
$nodes = [];
$attributes = [
'global' => false,
'durationNum' => null,
'durationUnit' => null,
];
if ($stream->test(Token::NAME_TYPE, 'globally')) {
$attributes['global'] = true;
$stream->next();
}
if ($stream->test(Token::NAME_TYPE, 'using')) {
$stream->next();
$stream->expect(Token::NAME_TYPE, 'key');
$nodes['key'] = $parser->getExpressionParser()->parseExpression();
}
if ($stream->test(Token::NAME_TYPE, 'for')) {
$stream->next();
$attributes['durationNum'] = $stream->expect(Token::NUMBER_TYPE)->getValue();
$attributes['durationUnit'] = $stream->expect(Token::NAME_TYPE,
[
'sec',
'secs',
'second',
'seconds',
'min',
'mins',
'minute',
'minutes',
'hour',
'hours',
'day',
'days',
'fortnight',
'fortnights',
'forthnight',
'forthnights',
'month',
'months',
'year',
'years',
'week',
'weeks',
])->getValue();
} elseif ($stream->test(Token::NAME_TYPE, 'until')) {
$stream->next();
$nodes['expiration'] = $parser->getExpressionParser()->parseExpression();
}
if ($stream->test(Token::NAME_TYPE, 'if')) {
$stream->next();
$nodes['conditions'] = $parser->getExpressionParser()->parseExpression();
} elseif ($stream->test(Token::NAME_TYPE, 'unless')) {
$stream->next();
$nodes['ignoreConditions'] = $parser->getExpressionParser()->parseExpression();
}
$stream->expect(Token::BLOCK_END_TYPE);
$nodes['body'] = $parser->subparse([
$this,
'decideCacheEnd',
], true);
$stream->expect(Token::BLOCK_END_TYPE);
return new CacheNode($nodes, $attributes, $lineno, $this->getTag());
}
/**
* @param Token $token
* @return bool
*/
public function decideCacheEnd(Token $token): bool
{
return $token->test('endcache');
}
}