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