Files
Twig/extra/cache-extra/TokenParser/CacheTokenParser.php
T
Fabien Potencier 6032fd320c Merge branch '3.x' into 4.x
* 3.x:
  Fix version
  Fix CS
  Remove obsolete code
  Use generics in ExpressionParsers
  Fix precedence rules
  Add deprecation notices in CHANGELOG and docs
  Move Operators to ExpressionParsers, deprecate ExpressionParser
  Add a script to update operator precedence documentation
  Extract operators logic from ExpressionParser to their own classes
  Introduce operator classes to describe operators provided by extensions instead of arrays
  Bump version to 3.21
2025-02-14 09:08:33 +01:00

75 lines
2.3 KiB
PHP

<?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();
$key = $this->parser->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 = $this->parser->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';
}
}