-
Notifications
You must be signed in to change notification settings - Fork 1
/
sfViewCacheTagManager.class.php
837 lines (709 loc) · 21.2 KB
/
sfViewCacheTagManager.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
<?php
/**
* This file is part of the sfCacheTaggingPlugin package.
* (c) 2009-2013 Ilya Sabelnikov <fruit.dev@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* This is extended cache manager with additional methods to work
* with cache tags.
*
* The most important difference from sfViewCacheManager is support to use
* sepparate cache systems for data and locks (performance reasons).
*
* By default data and lock cache system is same.
*
* @package sfCacheTaggingPlugin
* @subpackage view
* @author Ilya Sabelnikov <fruit.dev@gmail.com>
*/
class sfViewCacheTagManager extends sfViewCacheManager
{
/**
* holder's namespaces
* Namespace name should be "UpperCamelCased"
* This names is used in method patterns "call%sMethod",
* where %s is Page/Action/Partial
*/
const NAMESPACE_PAGE = 'Page';
const NAMESPACE_ACTION = 'Action';
const NAMESPACE_PARTIAL = 'Partial';
/**
* Data cache and locker cache container
*
* @var sfTaggingCache
*/
protected $taggingCache = null;
/**
* sfViewCacheTagManager option holder
*
* @var array
*/
protected $options = array();
/**
* Partial tags passed to include_partial by option "sf_cache_tag"
* Stored in temp variable due to unavailability of variables
* action and module names
*
* @var mixed
*/
protected $temporaryContentTags = null;
/**
* Returns predefined namespaces
*
* @return array Array of declared content namespaces
*/
public static function getNamespaces ()
{
return array(
self::NAMESPACE_PAGE,
self::NAMESPACE_ACTION,
self::NAMESPACE_PARTIAL,
);
}
/**
* sfViewCacheTagManager options
*
* @return array
*/
public function getOptions ()
{
return $this->options;
}
/**
* Sets options to the sfTaggingCache
*
* @param array $options
*/
public function setOptions (array $options)
{
$this->options = $options;
}
/**
* @return sfContentTagHandler
*/
public function getContentTagHandler ()
{
return $this->getTaggingCache()->getContentTagHandler();
}
/**
* @return sfEventDispatcher
*/
public function getEventDispatcher ()
{
return $this->dispatcher;
}
/**
* @param sfEventDispatcher $eventDispatcher
* @return sfViewCacheTagManager
*/
protected function setEventDispatcher (sfEventDispatcher $eventDispatcher)
{
$this->dispatcher = $eventDispatcher;
return $this;
}
/**
* Initialize cache manager
*
* @param sfContext $context
* @param sfCache $taggingCache
* @param array $options
*
* @see sfViewCacheManager::initialize()
*/
public function initialize ($context, sfCache $taggingCache, $options = array())
{
if (! $taggingCache instanceof sfTaggingCache)
{
throw new InvalidArgumentException(sprintf(
'Cache "%s" is not instanceof sfTaggingCache',
get_class($taggingCache)
));
}
$this->setTaggingCache($taggingCache);
$this->cache = $this->getTaggingCache()->getCache();
$this->setEventDispatcher($context->getEventDispatcher());
$this->context = $context;
$this->controller = $context->getController();
$this->request = $context->getRequest();
$this->routing = $context->getRouting();
$this->setOptions(array_merge(
array(
'cache_key_use_vary_headers' => true,
'cache_key_use_host_name' => true,
),
$options
));
if (sfConfig::get('sf_web_debug'))
{
$this->getEventDispatcher()->connect(
'view.cache.filter_content',
array($this, 'decorateContentWithDebug')
);
}
// empty configuration
$this->cacheConfig = array();
}
/**
* Retrieves sfTaggingCache object
*
* @return sfTaggingCache
*/
public function getTaggingCache ()
{
return $this->taggingCache;
}
/**
* Sets sfTaggingCache object
*
* @param sfTaggingCache $taggingCache
* @return sfViewCacheTagManager
*/
protected function setTaggingCache (sfTaggingCache $taggingCache)
{
$this->taggingCache = $taggingCache;
return $this;
}
/**
* @return sfController
*/
protected function getController ()
{
return $this->controller;
}
/**
* Due to an optimized version (self::_get) and compatibility
*
* @param string $internalUri
* @return mixed
*/
public function get ($internalUri)
{
return serialize($this->_get($internalUri));
}
/**
* Retrieves content in the cache.
*
* Match duplicated as a parent::get()
*
* Optimized version, does not call to serialize/unserialize when cache
* is stored as opcode
*
* @param string $internalUri Internal uniform resource identifier
* @return mixed The content in the cache
*/
protected function _get ($internalUri)
{
// no cache or no cache set for this action
if (! $this->isCacheable($internalUri) || $this->ignore())
{
return null;
}
$retval = $this->getTaggingCache()->get($this->generateCacheKey($internalUri));
$this->notify(sprintf(
'Cache for "%s" %s', $internalUri, $retval !== null ? 'exists' : 'does not exist'
));
return $retval;
}
/**
* Sets data to cache with passed tags
*
* @author Martin Schnabel <mcnilz@gmail.com>
* @author Ilya Sabelnikov <fruit.dev@gmail.com>
* @param string $internalUri
* @return mixed
*/
public function set ($data, $internalUri, $tags = array())
{
if (! $this->isCacheable($internalUri))
{
return false;
}
$this->getTaggingCache()->set(
$this->generateCacheKey($internalUri),
$data,
$this->getLifeTime($internalUri),
$tags
);
$this->notify(sprintf('Save cache for "%s"', $internalUri));
return true;
}
/**
* Returns true if there is a cache.
*
* @param string $internalUri Internal uniform resource identifier
*
* @return bool true, if there is a cache otherwise false
*/
public function has ($internalUri)
{
if (! $this->isCacheable($internalUri) || $this->ignore())
{
return null;
}
return $this->getTaggingCache()->has(
$this->generateCacheKey($internalUri)
);
}
/**
* Gets an action template from the cache.
*
* @param string $uri The internal URI
*
* @return array An array composed of the cached content and
* the view attribute holder
*/
public function getActionCache ($uri)
{
if (! $this->isCacheable($uri) || $this->withLayout($uri))
{
return null;
}
// retrieve content from cache
$cache = $this->_get($uri);
if (null === $cache)
{
return null;
}
$content = $cache['content'];
$cache['response'] = unserialize($cache['response']);
$cache['response']->setEventDispatcher($this->getEventDispatcher());
$this->getContext()->getResponse()->copyProperties($cache['response']);
if (sfConfig::get('sf_web_debug'))
{
$event = new sfEvent($this, 'view.cache.filter_content', array(
'response' => $this->getContext()->getResponse(),
'uri' => $uri,
'new' => false,
));
$content = $this
->getEventDispatcher()
->filter($event, $content)
->getReturnValue();
}
return array($content, $cache['decoratorTemplate']);
}
/**
* Sets an action template in the cache.
*
* @param string $uri The internal URI
* @param string $content The content to cache
* @param string $decoratorTemplate The view attribute holder to cache
*
* @return string The cached content
*/
public function setActionCache ($uri, $content, $decoratorTemplate)
{
if (! $this->isCacheable($uri) || $this->withLayout($uri))
{
return $content;
}
$contentTags = $this
->getContentTagHandler()
->getContentTags(self::NAMESPACE_ACTION);
$actionCacheValue = array(
'content' => $content,
'decoratorTemplate' => $decoratorTemplate,
'response' => serialize($this->getContext()->getResponse())
);
$saved = $this->set($actionCacheValue, $uri, $contentTags);
if ($saved && sfConfig::get('sf_web_debug'))
{
$event = new sfEvent($this, 'view.cache.filter_content', array(
'response' => $this->getContext()->getResponse(),
'uri' => $uri,
'new' => true,
));
$content = $this
->getEventDispatcher()
->filter($event, $content)
->getReturnValue();
}
return $content;
}
/**
* @see parent::setPageCache()
* @param string $uri
* @return null
*/
public function setPageCache ($uri)
{
if (sfView::RENDER_CLIENT != $this->getController()->getRenderMode())
{
return;
}
$contentTags = $this
->getContentTagHandler()
->getContentTags(self::NAMESPACE_PAGE);
$response = $this->getContext()->getResponse();
// save content in cache
$saved = $this->set($response, $uri, $contentTags);
if ($saved && sfConfig::get('sf_web_debug'))
{
$event = new sfEvent($this, 'view.cache.filter_content', array(
'response' => $response,
'uri' => $uri,
'new' => true,
));
$content = $this
->getEventDispatcher()
->filter($event, $response->getContent())
->getReturnValue();
$response->setContent($content);
}
}
/**
* Sets partial content with associated tags
*
* @see parent::setPartialCache()
*
* @param string $module
* @param string $action
* @param string $cacheKey
* @param string $content
* @return string
*/
public function setPartialCache ($module, $action, $cacheKey, $content)
{
$uri = $this->getPartialUri($module, $action, $cacheKey);
if (! $this->isCacheable($uri))
{
return $content;
}
$tagHandler = $this->getContentTagHandler();
$namespace = sprintf('%s-%s-%s', $module, $action, self::NAMESPACE_PARTIAL);
$contentTags = $tagHandler->getContentTags($namespace);
$response = $this->getContext()->getResponse();
$saved = $this->set(
array(
'content' => $content,
'response' => serialize($response),
),
$uri,
$contentTags
);
if ($saved && sfConfig::get('sf_web_debug'))
{
$event = new sfEvent($this, 'view.cache.filter_content', array(
'response' => $response,
'uri' => $uri,
'new' => true,
));
$content = $this
->getEventDispatcher()
->filter($event, $content)
->getReturnValue();
}
$tagHandler->removeContentTags($namespace);
return $content;
}
/**
* Listens to the 'view.cache.filter_content' event to decorate a chunk of
* HTML with cache information.
*
* Added info about linked tags
*
* @param sfEvent $event A sfEvent instance
* @param string $content The HTML content
*
* @return string The decorated HTML string
*/
public function decorateContentWithDebug (sfEvent $event, $content)
{
$updatedContent = parent::decorateContentWithDebug($event, $content);
if ($content === $updatedContent)
{
return $content;
}
$cacheMetadata = new CacheMetadata($this->getCache()->get(
$this->generateCacheKey($event['uri']))
);
if (null === $cacheMetadata->getData())
{
return $content;
}
$tags = $cacheMetadata->getTags();
ksort($tags, SORT_ASC);
$tagsCount = count($tags);
$tagsContent = sprintf('[cache tags] count: %d', $tagsCount);
if (0 != $tagsCount)
{
$tagsContent .= ', tags:';
foreach ($tags as $name => $version)
{
$tagsContent .= sprintf(
' <span title="%s">%s</span>,',
htmlspecialchars($version, ENT_QUOTES, sfConfig::get('sf_charset')),
htmlspecialchars($name, ENT_QUOTES, sfConfig::get('sf_charset'))
);
}
$tagsContent = substr($tagsContent, 0, -1) . '.';
}
$textToReplace = ' <br /> ';
return str_replace($textToReplace, $tagsContent, $updatedContent);
}
/**
* Before checking cache key - saves passed tags
*
* @see parent::checkCacheKey()
* @param array $parameters An array of parameters
* @return string The cache key
*/
public function checkCacheKey (array & $parameters)
{
$tagsKey = 'sf_cache_tags';
$this->temporaryContentTags = null;
if (isset($parameters[$tagsKey]))
{
$tags = true === sfConfig::get('sf_escaping_strategy')
? sfOutputEscaper::unescape($parameters[$tagsKey])
: $parameters[$tagsKey];
unset($parameters[$tagsKey]);
if ($tags)
{
$this->temporaryContentTags = $tags;
}
}
return parent::checkCacheKey($parameters);
}
/**
* Code is much dublicated (enough same)
* with one distinction - it work already with unserialized data
*
* @see parent::getPageCache();
* @param string $uri
* @return boolean
*/
public function getPageCache ($uri)
{
$cachedResponse = $this->_get($uri);
if (null === $cachedResponse)
{
return false;
}
$cachedResponse->setEventDispatcher($this->getEventDispatcher());
if (sfView::RENDER_VAR == $this->getController()->getRenderMode())
{
$this->getController()->getActionStack()->getLastEntry()->setPresentation(
$cachedResponse->getContent()
);
$this->getContext()->getResponse()->setContent('');
}
else
{
$this->getContext()->setResponse($cachedResponse);
$response = $this->getContext()->getResponse();
if (sfConfig::get('sf_web_debug'))
{
$event = new sfEvent($this, 'view.cache.filter_content', array(
'response' => $response,
'uri' => $uri,
'new' => false,
));
$content = $this
->getEventDispatcher()
->filter($event, $response->getContent())
->getReturnValue();
$response->setContent($content);
}
}
return true;
}
/**
* Gets a partial template from the cache.
*
* @param string $module The module name
* @param string $action The action name
* @param string $cacheKey The cache key
*
* @return string The cache content
*/
public function getPartialCache ($module, $action, $cacheKey)
{
$uri = $this->getPartialUri($module, $action, $cacheKey);
if (! $this->isCacheable($uri))
{
return null;
}
if ($this->temporaryContentTags)
{
$namespace = sprintf(
'%s-%s-%s', $module, $action, self::NAMESPACE_PARTIAL
);
$this
->getContentTagHandler()
->setContentTags($this->temporaryContentTags, $namespace)
;
$this->temporaryContentTags = null;
}
// retrieve content from cache
$cache = $this->_get($uri);
if (null === $cache)
{
return null;
}
$content = $cache['content'];
$cache['response'] = unserialize($cache['response']);
$this->getContext()->getResponse()->merge($cache['response']);
if (sfConfig::get('sf_web_debug'))
{
$event = new sfEvent($this, 'view.cache.filter_content', array(
'response' => $this->getContext()->getResponse(),
'uri' => $uri,
'new' => false,
));
$content = $this
->getEventDispatcher()
->filter($event, $content)
->getReturnValue();
}
return $content;
}
/**
* Disables cache on the fly (used in "cachable" generator)
* Solved the problem when action contains form, after form is saved
* displayed flashes are cached.
*
* @param string $moduleName
* @param string $actionName
* @return array
*/
public function disableCache ($moduleName, $actionName = null)
{
if ($moduleName && $actionName)
{
if (isset($this->cacheConfig[$moduleName][$actionName]))
{
unset($this->cacheConfig[$moduleName][$actionName]);
}
return;
}
if ($moduleName)
{
if (isset($this->cacheConfig[$moduleName]))
{
unset($this->cacheConfig[$moduleName]);
}
}
return;
}
/**
* @see parent::remove() The main difference, instead of $this->cache is
* used $this->getTaggingCache()
*/
public function remove ($internalUri, $hostName = '', $vary = '', $contextualPrefix = '**')
{
$this->notify(sprintf('Remove cache for "%s"', $internalUri));
$cacheKey = $this->generateCacheKey(
$internalUri, $hostName, $vary, $contextualPrefix
);
$taggingCache = $this->getTaggingCache();
if (strpos($cacheKey, '*'))
{
return $taggingCache->removePattern($cacheKey);
}
elseif ($taggingCache->has($cacheKey))
{
return $taggingCache->remove($cacheKey);
}
}
/**
* Appends extra cache key parameters when user is authenticated
* and there are some parameters set by user
*
* {@inheritdoc}
*/
public function generateCacheKey ($internalUri, $hostName = '', $vary = '', $contextualPrefix = '')
{
$user = $this->getContext()->getUser();
$dispatcher = $this->getEventDispatcher();
// sfSecurityUser interface has "isAuthenticated" method
if (! $user instanceof sfSecurityUser)
{
$this->notify(
sprintf(
'User class "%s" does not implements the "sfSecurityUser" interface',
get_class($user)
),
sfLogger::DEBUG
);
}
elseif (! $user->isAuthenticated())
{
$this->notify('User is not authenticated', sfLogger::DEBUG);
}
else
{
$urlInfo = parse_url($internalUri);
$sysParams = array();
if (isset($urlInfo['query']))
{
parse_str($urlInfo['query'], $sysParams);
}
$cacheType = null;
if (0 === strpos($internalUri, '@sf_cache_partial'))
{
$cacheType = self::NAMESPACE_PARTIAL;
}
elseif (! isset($sysParams['action'], $sysParams['module']))
{
// w/ layout is only pages (action+layout)
if ($this->withLayout($internalUri))
{
$cacheType = self::NAMESPACE_PAGE;
}
else // w/o layout only actions
{
$cacheType = self::NAMESPACE_ACTION;
}
}
$event = new sfEvent($user, 'cache.filter_cache_keys', array(
'view_cache' => $this,
'cache_type' => $cacheType,
'call_args' => func_get_args(),
));
$userParams = $dispatcher->filter($event, array())->getReturnValue();
if (! is_array($userParams))
{
$this->notify('Custom cache key param is not an array', sfLogger::ERR);
}
elseif (0 < count($userParams))
{
// protects @sf_cache_partial action/module name substitution
if (isset($userParams['action'])) unset($userParams['action']);
if (isset($userParams['module'])) unset($userParams['module']);
$formattedUserParams = array();
foreach ($userParams as $key => $value)
{
$key = is_numeric($key) ? sprintf('param_%d', $key) : $key;
$formattedUserParams[$key] = $value;
}
// union, do not overwrite sysParams key values
$sysParams += $formattedUserParams;
if (0 < count($sysParams))
{
$internalUri = $urlInfo['path'] . '?' . http_build_query($sysParams);
}
}
}
return parent::generateCacheKey($internalUri, $hostName, $vary, $contextualPrefix);
}
/**
* Notifies application.log listener
*
* @param string $message
* @param int $priority sfLogger::*
*/
protected function notify ($message, $priority = sfLogger::INFO)
{
if (! sfConfig::get('sf_logging_enabled'))
{
return;
}
$this->getEventDispatcher()->notify(
new sfEvent($this, 'application.log', array($message, 'priority' => $priority))
);
}
}