1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace WShafer\PSR11PhpCache\Adapter; |
6
|
|
|
|
7
|
|
|
use Cache\Adapter\Redis\RedisCachePool; |
8
|
|
|
use Psr\Container\ContainerInterface; |
9
|
|
|
use Redis; |
10
|
|
|
use WShafer\PSR11PhpCache\Exception\InvalidConfigException; |
11
|
|
|
use WShafer\PSR11PhpCache\Exception\MissingExtensionException; |
12
|
|
|
|
13
|
|
|
class RedisAdapterFactory implements FactoryInterface |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* PredisAdapterFactory constructor. |
17
|
|
|
* |
18
|
|
|
* @codeCoverageIgnore |
19
|
|
|
*/ |
20
|
|
|
public function __construct() |
21
|
|
|
{ |
22
|
|
|
if (!extension_loaded('redis')) { |
23
|
|
|
throw new MissingExtensionException( |
24
|
|
|
'Redis extension not installed' |
25
|
|
|
); |
26
|
|
|
} |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @param ContainerInterface $container |
31
|
|
|
* @param array $options |
32
|
|
|
* |
33
|
|
|
* @return RedisCachePool |
34
|
|
|
*/ |
35
|
4 |
|
public function __invoke(ContainerInterface $container, array $options): RedisCachePool |
36
|
|
|
{ |
37
|
4 |
|
$instance = $this->getInstance($container, $options); |
38
|
3 |
|
return new RedisCachePool($instance); |
39
|
|
|
} |
40
|
|
|
|
41
|
4 |
|
public function getInstance(ContainerInterface $container, array $options): Redis |
42
|
|
|
{ |
43
|
|
|
if ( |
44
|
4 |
|
empty($options['service']) |
45
|
4 |
|
&& empty($options['server']) |
46
|
|
|
) { |
47
|
1 |
|
throw new InvalidConfigException( |
48
|
1 |
|
'You must provide either a container service or a server connection' |
49
|
|
|
); |
50
|
|
|
} |
51
|
|
|
|
52
|
3 |
|
if (!empty($options['service'])) { |
53
|
1 |
|
return $this->getInstanceFromContainer($container, $options['service']); |
54
|
|
|
} |
55
|
|
|
|
56
|
2 |
|
return $this->getInstanceFromConfig($options); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* @param ContainerInterface $container |
61
|
|
|
* @param $name |
62
|
|
|
* |
63
|
|
|
* @return \Redis |
64
|
|
|
*/ |
65
|
1 |
|
public function getInstanceFromContainer(ContainerInterface $container, $name): Redis |
66
|
|
|
{ |
67
|
1 |
|
return $container->get($name); |
68
|
|
|
} |
69
|
|
|
|
70
|
2 |
|
public function getInstanceFromConfig(array $options): Redis |
71
|
|
|
{ |
72
|
2 |
|
$server = $options['server'] ?? []; |
73
|
2 |
|
$host = $server['host'] ?? null; |
74
|
2 |
|
$port = $server['port'] ?? 6379; |
75
|
2 |
|
$timeout = $server['timeout'] ?? 0.0; |
76
|
2 |
|
$persistent = $server['persistent'] ?? true; |
77
|
2 |
|
$persistentId = $server['persistentId'] ?? 'phpcache'; |
78
|
|
|
|
79
|
2 |
|
$connection = new Redis(); |
80
|
|
|
|
81
|
2 |
|
if (!$persistent) { |
82
|
1 |
|
$connection->connect($host, $port, $timeout); |
83
|
1 |
|
return $connection; |
84
|
|
|
} |
85
|
|
|
|
86
|
1 |
|
$connection->pconnect($host, $port, $timeout, $persistentId); |
87
|
1 |
|
return $connection; |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|