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