-
-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathCachingConnector.php
More file actions
93 lines (79 loc) · 2.58 KB
/
CachingConnector.php
File metadata and controls
93 lines (79 loc) · 2.58 KB
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
<?php
namespace ScriptFUSION\Porter\Connector;
use Psr\Cache\CacheItemPoolInterface;
use ScriptFUSION\Porter\Cache\CacheKeyGenerator;
use ScriptFUSION\Porter\Cache\InvalidCacheKeyException;
use ScriptFUSION\Porter\Cache\JsonCacheKeyGenerator;
use ScriptFUSION\Porter\Cache\MemoryCache;
use ScriptFUSION\Porter\Options\EncapsulatedOptions;
/**
* Wraps a connector to cache fetched data using PSR-6-compliant objects.
*/
class CachingConnector implements Connector
{
/**
* @var Connector
*/
private $connector;
/**
* @var CacheItemPoolInterface
*/
private $cache;
/**
* @var CacheKeyGenerator
*/
private $cacheKeyGenerator;
public function __construct(
Connector $connector,
CacheItemPoolInterface $cache = null,
CacheKeyGenerator $cacheKeyGenerator = null
) {
$this->connector = $connector;
$this->cache = $cache ?: new MemoryCache;
$this->cacheKeyGenerator = $cacheKeyGenerator ?: new JsonCacheKeyGenerator;
}
/**
* @param ConnectionContext $context
* @param string $source
* @param EncapsulatedOptions|null $options
*
* @return mixed
*
* @throws InvalidCacheKeyException
*/
public function fetch(ConnectionContext $context, $source, EncapsulatedOptions $options = null)
{
if ($context->mustCache()) {
$optionsCopy = $options ? $options->copy() : [];
ksort($optionsCopy);
$this->validateCacheKey($key = $this->cacheKeyGenerator->generateCacheKey($source, $optionsCopy));
if ($this->cache->hasItem($key)) {
return $this->cache->getItem($key)->get();
}
}
$data = $this->connector->fetch($context, $source, $options);
isset($key) && $this->cache->save($this->cache->getItem($key)->set($data));
return $data;
}
/**
* @param mixed $key
*
* @return void
*
* @throws InvalidCacheKeyException Cache key contains invalid data.
*/
private function validateCacheKey($key)
{
// TODO: Remove when PHP 5 support dropped and replace with string hint.
if (!is_string($key)) {
throw new InvalidCacheKeyException('Cache key must be a string.');
}
if (strpbrk($key, CacheKeyGenerator::RESERVED_CHARACTERS) !== false) {
throw new InvalidCacheKeyException(sprintf(
'Cache key "%s" contains one or more reserved characters: "%s".',
$key,
CacheKeyGenerator::RESERVED_CHARACTERS
));
}
}
}