-
Notifications
You must be signed in to change notification settings - Fork 24
/
CacheListener.php
121 lines (103 loc) · 2.79 KB
/
CacheListener.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
<?php
/**
* @author Bram Gerritsen bgerritsen@gmail.com
* @copyright (c) Bram Gerritsen 2013
* @license http://opensource.org/licenses/mit-license.php
*/
namespace StrokerCache\Listener;
use StrokerCache\Options\ModuleOptions;
use StrokerCache\Service\CacheService;
use Zend\EventManager\AbstractListenerAggregate;
use Zend\EventManager\EventManagerInterface;
use Zend\Http\PhpEnvironment\Request as HttpRequest;
use Zend\Mvc\MvcEvent;
class CacheListener extends AbstractListenerAggregate
{
/**
* @var array
*/
protected $listeners = array();
/**
* @var CacheService
*/
protected $cacheService;
/**
* @var ModuleOptions
*/
protected $options;
/**
* @var bool
*/
protected $loadedFromCache = false;
/**
* Default constructor
*
* @param CacheService $cacheService
* @param ModuleOptions $options
*/
public function __construct(CacheService $cacheService, ModuleOptions $options)
{
$this->cacheService = $cacheService;
$this->options = $options;
}
/**
* {@inheritDoc}
*/
public function attach(EventManagerInterface $events)
{
$this->listeners[] = $events->attach('route', array($this, 'onRoute'), 100);
$this->listeners[] = $events->attach('finish', array($this, 'onFinish'), -100);
}
/**
* Load the page contents from the cache and set the response.
*
* @param MvcEvent $e
* @return \Zend\Stdlib\ResponseInterface|void
*/
public function onRoute(MvcEvent $e)
{
if (!$e->getRequest() instanceof HttpRequest) {
return;
}
$data = $this->getCacheService()->load($e);
if ($data !== null) {
$this->loadedFromCache = true;
if ($this->getOptions()->getCacheResponse() === true) {
$response = unserialize($data);
} else {
$response = $e->getResponse();
$response->setContent($data);
}
$response->getHeaders()->addHeaderLine('X-Stroker-Cache', 'Hit');
return $response;
}
$e->getResponse()->getHeaders()->addHeaderLine('X-Stroker-Cache', 'Miss');
}
/**
* Save page contents to the cache
*
* @param MvcEvent $e
* @return void
*/
public function onFinish(MvcEvent $e)
{
if (!$e->getRequest() instanceof HttpRequest || $this->loadedFromCache) {
return;
}
$this->getCacheService()->save($e);
}
/**
* @return CacheService
*/
public function getCacheService()
{
return $this->cacheService;
}
/**
* @return ModuleOptions
*/
public function getOptions()
{
return $this->options;
}
}