1: <?php
2:
3: 4: 5: 6:
7:
8: namespace Nette\Bridges\CacheLatte;
9:
10: use Nette;
11: use Nette\Caching\Cache;
12: use Latte;
13:
14:
15: 16: 17:
18: class CacheMacro implements Latte\IMacro
19: {
20: use Nette\SmartObject;
21:
22:
23: private $used;
24:
25:
26: 27: 28: 29:
30: public function initialize()
31: {
32: $this->used = FALSE;
33: }
34:
35:
36: 37: 38: 39:
40: public function finalize()
41: {
42: if ($this->used) {
43: return ['Nette\Bridges\CacheLatte\CacheMacro::initRuntime($this);'];
44: }
45: }
46:
47:
48: 49: 50: 51:
52: public function nodeOpened(Latte\MacroNode $node)
53: {
54: if ($node->modifiers) {
55: throw new Latte\CompileException('Modifiers are not allowed in ' . $node->getNotation());
56: }
57: $this->used = TRUE;
58: $node->empty = FALSE;
59: $node->openingCode = Latte\PhpWriter::using($node)
60: ->write('<?php if (Nette\Bridges\CacheLatte\CacheMacro::createCache($this->global->cacheStorage, %var, $this->global->cacheStack, %node.array?)) { ?>',
61: Nette\Utils\Random::generate()
62: );
63: }
64:
65:
66: 67: 68: 69:
70: public function nodeClosed(Latte\MacroNode $node)
71: {
72: $node->closingCode = '<?php $_tmp = array_pop($this->global->cacheStack); if (!$_tmp instanceof stdClass) $_tmp->end(); } ?>';
73: }
74:
75:
76:
77:
78:
79: 80: 81:
82: public static function initRuntime(Latte\Runtime\Template $template)
83: {
84: if (!empty($template->global->cacheStack)) {
85: $file = (new \ReflectionClass($template))->getFileName();
86: if (@is_file($file)) {
87: end($template->global->cacheStack)->dependencies[Cache::FILES][] = $file;
88: }
89: }
90: }
91:
92:
93: 94: 95: 96: 97: 98: 99: 100:
101: public static function createCache(Nette\Caching\IStorage $cacheStorage, $key, & $parents, array $args = NULL)
102: {
103: if ($args) {
104: if (array_key_exists('if', $args) && !$args['if']) {
105: return $parents[] = new \stdClass;
106: }
107: $key = array_merge([$key], array_intersect_key($args, range(0, count($args))));
108: }
109: if ($parents) {
110: end($parents)->dependencies[Cache::ITEMS][] = $key;
111: }
112:
113: $cache = new Cache($cacheStorage, 'Nette.Templating.Cache');
114: if ($helper = $cache->start($key)) {
115: if (isset($args['dependencies'])) {
116: $args += call_user_func($args['dependencies']);
117: }
118: if (isset($args['expire'])) {
119: $args['expiration'] = $args['expire'];
120: }
121: $helper->dependencies = [
122: $cache::TAGS => isset($args['tags']) ? $args['tags'] : NULL,
123: $cache::EXPIRATION => isset($args['expiration']) ? $args['expiration'] : '+ 7 days',
124: ];
125: $parents[] = $helper;
126: }
127: return $helper;
128: }
129:
130: }
131: