1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Cmp\Cache\Infrastructure\Provider; |
4
|
|
|
|
5
|
|
|
use Closure; |
6
|
|
|
use Cmp\Cache\Application\CacheFactory; |
7
|
|
|
use InvalidArgumentException; |
8
|
|
|
use Pimple\Container; |
9
|
|
|
use Pimple\ServiceProviderInterface; |
10
|
|
|
use Redis; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Class PimpleCacheProvider |
14
|
|
|
* |
15
|
|
|
* @package Cmp\Cache\Infrastructure\Provider |
16
|
|
|
*/ |
17
|
|
|
class PimpleCacheProvider implements ServiceProviderInterface |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* Registers cache services on the given container. |
21
|
|
|
* |
22
|
|
|
* @param Container $pimple A container instance |
23
|
|
|
*/ |
24
|
|
|
public function register(Container $pimple) |
25
|
|
|
{ |
26
|
|
|
$pimple['cache.backend'] = 'array'; |
27
|
|
|
$pimple['cache.debug'] = false; |
28
|
|
|
|
29
|
|
|
$pimple['cache'] = function () use ($pimple) { |
30
|
|
|
$cache = $this->getCache($pimple['cache.backend']); |
31
|
|
|
|
32
|
|
|
if ($pimple['cache.debug']) { |
33
|
|
|
$cache = CacheFactory::decorateForTesting($cache); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
return $cache; |
37
|
|
|
}; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* Gets a cache object based on the backend requested |
42
|
|
|
* |
43
|
|
|
* @param $backend |
44
|
|
|
* |
45
|
|
|
* @return Closure|\Cmp\Cache\Infrastructure\ArrayCache |
46
|
|
|
*/ |
47
|
|
|
private function getCache($backend) |
48
|
|
|
{ |
49
|
|
|
if (is_array($backend) && isset($backend['redis'])) { |
50
|
|
|
return $this->getRedis($backend['redis']); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
if ($backend == 'array') { |
54
|
|
|
return CacheFactory::arrayCache(); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
throw new InvalidArgumentException("Invalid cache backend"); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* Return a factory closure to build |
62
|
|
|
* |
63
|
|
|
* @param array|Redis $redis |
64
|
|
|
* |
65
|
|
|
* @return Closure |
66
|
|
|
*/ |
67
|
|
|
private function getRedis($redis) |
68
|
|
|
{ |
69
|
|
|
if ($redis instanceof Redis) { |
|
|
|
|
70
|
|
|
return CacheFactory::redisCache($redis); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
$host = isset($redis['host']) ? $redis['host'] : '127.0.0.1'; |
74
|
|
|
$port = isset($redis['port']) ? $redis['port'] : 6379; |
75
|
|
|
$db = isset($redis['db']) ? $redis['db'] : 0; |
76
|
|
|
$timeout = isset($redis['timeout']) ? $redis['timeout'] : 0.0; |
77
|
|
|
|
78
|
|
|
return CacheFactory::redisFromParams($host, $port, $db, $timeout); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|