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