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: 101:
102: public static function createCache(Nette\Caching\IStorage $cacheStorage, $key, &$parents, array $args = null)
103: {
104: if ($args) {
105: if (array_key_exists('if', $args) && !$args['if']) {
106: return $parents[] = new \stdClass;
107: }
108: $key = array_merge([$key], array_intersect_key($args, range(0, count($args))));
109: }
110: if ($parents) {
111: end($parents)->dependencies[Cache::ITEMS][] = $key;
112: }
113:
114: $cache = new Cache($cacheStorage, 'Nette.Templating.Cache');
115: if ($helper = $cache->start($key)) {
116: $parents[] = $helper;
117: }
118: return $helper;
119: }
120:
121:
122: 123: 124: 125: 126:
127: public static function endCache(&$parents, array $args = null)
128: {
129: $helper = array_pop($parents);
130: if ($helper instanceof Nette\Caching\OutputHelper) {
131: if (isset($args['dependencies'])) {
132: $args += call_user_func($args['dependencies']);
133: }
134: if (isset($args['expire'])) {
135: $args['expiration'] = $args['expire'];
136: }
137: $helper->dependencies[Cache::TAGS] = isset($args['tags']) ? $args['tags'] : null;
138: $helper->dependencies[Cache::EXPIRATION] = isset($args['expiration']) ? $args['expiration'] : '+ 7 days';
139: $helper->end();
140: }
141: }
142: }
143: