TwigNodeCache.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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\Node;
  9. use Twig\Compiler;
  10. use Twig\Node\Expression\AbstractExpression;
  11. use Twig\Node\Node;
  12. class TwigNodeCache extends Node
  13. {
  14. /**
  15. * @param string $key unique name for key
  16. * @param int $lifetime in seconds
  17. * @param Node $body
  18. * @param integer $lineno
  19. * @param string $tag
  20. */
  21. public function __construct(string $key, int $lifetime, Node $body, $lineno, $tag = null)
  22. {
  23. parent::__construct(array('body' => $body), array( 'key' => $key, 'lifetime' => $lifetime), $lineno, $tag);
  24. }
  25. /**
  26. * {@inheritDoc}
  27. */
  28. public function compile(Compiler $compiler)
  29. {
  30. $boo = $this->getAttribute('key');
  31. $compiler
  32. ->addDebugInfo($this)
  33. ->write("\$cache = \\Grav\\Common\\Grav::instance()['cache'];\n")
  34. ->write("\$key = \"twigcache-\" . \"" . $this->getAttribute('key') . "\";\n")
  35. ->write("\$lifetime = " . $this->getAttribute('lifetime') . ";\n")
  36. ->write("\$cache_body = \$cache->fetch(\$key);\n")
  37. ->write("if (\$cache_body === false) {\n")
  38. ->indent()
  39. ->write("ob_start();\n")
  40. ->indent()
  41. ->subcompile($this->getNode('body'))
  42. ->outdent()
  43. ->write("\n")
  44. ->write("\$cache_body = ob_get_clean();\n")
  45. ->write("\$cache->save(\$key, \$cache_body, \$lifetime);\n")
  46. ->outdent()
  47. ->write("}\n")
  48. ->write("echo \$cache_body;\n")
  49. ;
  50. }
  51. }