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