1: <?php
2:
3: 4: 5: 6:
7:
8: namespace Nette\Bridges\CacheLatte;
9:
10: use Latte;
11: use Nette;
12: use Nette\Caching\Cache;
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 = Latte\PhpWriter::using($node)
73: ->write('<?php Nette\Bridges\CacheLatte\CacheMacro::endCache($this->global->cacheStack, %node.array?); } ?>');
74: }
75:
76:
77:
78:
79:
80: 81: 82:
83: public static function initRuntime(Latte\Runtime\Template $template)
84: {
85: if (!empty($template->global->cacheStack)) {
86: $file = (new \ReflectionClass($template))->getFileName();
87: if (@is_file($file)) {
88: end($template->global->cacheStack)->dependencies[Cache::FILES][] = $file;
89: }
90: }
91: }
92:
93:
94: 95: 96: 97: 98: 99:
100: public static function createCache(Nette\Caching\IStorage $cacheStorage, $key, &$parents, array $args = null)
101: {
102: if ($args) {
103: if (array_key_exists('if', $args) && !$args['if']) {
104: return $parents[] = new \stdClass;
105: }
106: $key = array_merge([$key], array_intersect_key($args, range(0, count($args))));
107: }
108: if ($parents) {
109: end($parents)->dependencies[Cache::ITEMS][] = $key;
110: }
111:
112: $cache = new Cache($cacheStorage, 'Nette.Templating.Cache');
113: if ($helper = $cache->start($key)) {
114: $parents[] = $helper;
115: }
116: return $helper;
117: }
118:
119:
120: 121: 122: 123: 124:
125: public static function endCache(&$parents, array $args = null)
126: {
127: $helper = array_pop($parents);
128: if ($helper instanceof Nette\Caching\OutputHelper) {
129: if (isset($args['dependencies'])) {
130: $args += call_user_func($args['dependencies']);
131: }
132: if (isset($args['expire'])) {
133: $args['expiration'] = $args['expire'];
134: }
135: $helper->dependencies[Cache::TAGS] = isset($args['tags']) ? $args['tags'] : null;
136: $helper->dependencies[Cache::EXPIRATION] = isset($args['expiration']) ? $args['expiration'] : '+ 7 days';
137: $helper->end();
138: }
139: }
140: }
141: