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: if ($node->modifiers) {
52: trigger_error("Modifiers are not allowed in {{$node->name}}", E_USER_WARNING);
53: }
54: $this->used = TRUE;
55: $node->isEmpty = FALSE;
56: $node->openingCode = Latte\PhpWriter::using($node)
57: ->write('<?php if (Nette\Bridges\CacheLatte\CacheMacro::createCache($netteCacheStorage, %var, $_g->caches, %node.array?)) { ?>',
58: Nette\Utils\Random::generate()
59: );
60: }
61:
62:
63: 64: 65: 66:
67: public function nodeClosed(Latte\MacroNode $node)
68: {
69: $node->closingCode = '<?php $_l->tmp = array_pop($_g->caches); if (!$_l->tmp instanceof stdClass) $_l->tmp->end(); } ?>';
70: }
71:
72:
73:
74:
75:
76: 77: 78:
79: public static function initRuntime(Latte\Template $template, \stdClass $global)
80: {
81: if (!empty($global->caches) && $template->getEngine()->getLoader() instanceof Latte\Loaders\FileLoader) {
82: end($global->caches)->dependencies[Nette\Caching\Cache::FILES][] = $template->getName();
83: }
84: }
85:
86:
87: 88: 89: 90: 91: 92: 93: 94:
95: public static function createCache(Nette\Caching\IStorage $cacheStorage, $key, & $parents, array $args = NULL)
96: {
97: if ($args) {
98: if (array_key_exists('if', $args) && !$args['if']) {
99: return $parents[] = new \stdClass;
100: }
101: $key = array_merge(array($key), array_intersect_key($args, range(0, count($args))));
102: }
103: if ($parents) {
104: end($parents)->dependencies[Nette\Caching\Cache::ITEMS][] = $key;
105: }
106:
107: $cache = new Nette\Caching\Cache($cacheStorage, 'Nette.Templating.Cache');
108: if ($helper = $cache->start($key)) {
109: if (isset($args['dependencies'])) {
110: $args += call_user_func($args['dependencies']);
111: }
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: