TwigTokenParserCache.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. /**
  3. * @package Grav\Common\Twig
  4. *
  5. * @copyright Copyright (C) 2015 - 2020 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Common\Twig\TokenParser;
  9. use Grav\Common\Grav;
  10. use Grav\Common\Twig\Node\TwigNodeCache;
  11. use Twig\Token;
  12. use Twig\TokenParser\AbstractTokenParser;
  13. /**
  14. * Adds ability to cache Twig between tags.
  15. *
  16. * {% cache 600 %}
  17. * {{ some_complex_work() }}
  18. * {% endcache %}
  19. *
  20. * Where the `600` is an optional lifetime in seconds
  21. */
  22. class TwigTokenParserCache extends AbstractTokenParser
  23. {
  24. /**
  25. * {@inheritDoc}
  26. */
  27. public function parse(Token $token)
  28. {
  29. $lineno = $token->getLine();
  30. $stream = $this->parser->getStream();
  31. $key = $this->parser->getVarName() . $lineno;
  32. $lifetime = Grav::instance()['cache']->getLifetime();
  33. // Check for optional lifetime override
  34. if (!$stream->test(Token::BLOCK_END_TYPE)) {
  35. $lifetime_expr = $this->parser->getExpressionParser()->parseExpression();
  36. $lifetime = $lifetime_expr->getAttribute('value');
  37. }
  38. $stream->expect(Token::BLOCK_END_TYPE);
  39. $body = $this->parser->subparse(array($this, 'decideCacheEnd'), true);
  40. $stream->expect(Token::BLOCK_END_TYPE);
  41. return new TwigNodeCache($key, $lifetime, $body, $lineno, $this->getTag());
  42. }
  43. /**
  44. * Decide if current token marks end of cache block.
  45. *
  46. * @param Token $token
  47. * @return bool
  48. */
  49. public function decideCacheEnd(Token $token)
  50. {
  51. return $token->test('endcache');
  52. }
  53. /**
  54. * {@inheritDoc}
  55. */
  56. public function getTag()
  57. {
  58. return 'cache';
  59. }
  60. }