/
CallbackCache.php
187 lines (165 loc) · 5.46 KB
/
CallbackCache.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
<?php
namespace Laminas\Cache\Pattern;
use Laminas\Cache\Exception;
use Laminas\Stdlib\ErrorHandler;
use function array_key_exists;
use function array_values;
use function is_callable;
use function is_object;
use function md5;
use function ob_end_flush;
use function ob_get_flush;
use function ob_implicit_flush;
use function ob_start;
use function serialize;
use function sprintf;
use function strtolower;
class CallbackCache extends AbstractStorageCapablePattern
{
/**
* Call the specified callback or get the result from cache
*
* @param callable $callback A valid callback
* @param array $args Callback arguments
* @return mixed Result
* @throws Exception\RuntimeException If invalid cached data.
* @throws \Exception
*/
public function call($callback, array $args = [])
{
$options = $this->getOptions();
$storage = $this->getStorage();
$success = null;
$key = $this->generateCallbackKey($callback, $args);
$result = $storage->getItem($key, $success);
if ($success) {
if (! array_key_exists(0, $result)) {
throw new Exception\RuntimeException("Invalid cached data for key '{$key}'");
}
echo $result[1] ?? '';
return $result[0];
}
$cacheOutput = $options->getCacheOutput();
if ($cacheOutput) {
ob_start();
ob_implicit_flush(false);
}
// TODO: do not cache on errors using [set|restore]_error_handler
try {
$ret = $callback(...$args);
} catch (\Exception $e) {
if ($cacheOutput) {
ob_end_flush();
}
throw $e;
}
if ($cacheOutput) {
$data = [$ret, ob_get_flush()];
} else {
$data = [$ret];
}
$storage->setItem($key, $data);
return $ret;
}
/**
* function call handler
*
* @param string $function Function name to call
* @param array $args Function arguments
* @return mixed
* @throws Exception\RuntimeException
* @throws \Exception
*/
public function __call($function, array $args)
{
return $this->call($function, $args);
}
/**
* Generate a unique key in base of a key representing the callback part
* and a key representing the arguments part.
*
* @param callable $callback A valid callback
* @param array $args Callback arguments
* @return string
* @throws Exception\RuntimeException
* @throws Exception\InvalidArgumentException
*/
public function generateKey($callback, array $args = [])
{
return $this->generateCallbackKey($callback, $args);
}
/**
* Generate a unique key in base of a key representing the callback part
* and a key representing the arguments part.
*
* @param callable $callback A valid callback
* @param array $args Callback arguments
* @throws Exception\RuntimeException If callback not serializable.
* @throws Exception\InvalidArgumentException If invalid callback.
* @return string
*/
protected function generateCallbackKey($callback, array $args)
{
if (! is_callable($callback, false, $callbackKey)) {
throw new Exception\InvalidArgumentException('Invalid callback');
}
// functions, methods and classnames are case-insensitive
$callbackKey = strtolower($callbackKey);
// generate a unique key of object callbacks
if (is_object($callback)) {
// Closures & __invoke
$object = $callback;
} elseif (isset($callback[0])) {
// array($object, 'method')
$object = $callback[0];
}
if (isset($object)) {
ErrorHandler::start();
try {
$serializedObject = serialize($object);
} catch (\Exception $e) {
ErrorHandler::stop();
throw new Exception\RuntimeException("Can't serialize callback: see previous exception", 0, $e);
}
$error = ErrorHandler::stop();
if (! $serializedObject) {
throw new Exception\RuntimeException(
sprintf('Cannot serialize callback%s', $error ? ': ' . $error->getMessage() : ''),
0,
$error
);
}
$callbackKey .= $serializedObject;
}
return md5($callbackKey) . $this->generateArgumentsKey($args);
}
/**
* Generate a unique key of the argument part.
*
* @param array $args
* @throws Exception\RuntimeException
* @return string
*/
protected function generateArgumentsKey(array $args)
{
if (! $args) {
return '';
}
ErrorHandler::start();
try {
$serializedArgs = serialize(array_values($args));
} catch (\Exception $e) {
ErrorHandler::stop();
throw new Exception\RuntimeException("Can't serialize arguments: see previous exception", 0, $e);
}
$error = ErrorHandler::stop();
if (! $serializedArgs) {
throw new Exception\RuntimeException(
sprintf('Cannot serialize arguments%s', $error ? ': ' . $error->getMessage() : ''),
0,
$error
);
}
return md5($serializedArgs);
}
}