1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace WShafer\PSR11PhpCache\Adapter; |
6
|
|
|
|
7
|
|
|
use Cache\Adapter\Predis\PredisCachePool; |
8
|
|
|
use Predis\Client; |
9
|
|
|
use Psr\Container\ContainerInterface; |
10
|
|
|
use WShafer\PSR11PhpCache\Exception\InvalidConfigException; |
11
|
|
|
use WShafer\PSR11PhpCache\Exception\MissingLibraryException; |
12
|
|
|
|
13
|
|
|
class PredisAdapterFactory implements FactoryInterface |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* PredisAdapterFactory constructor. |
17
|
|
|
* |
18
|
|
|
* @codeCoverageIgnore |
19
|
|
|
*/ |
20
|
|
|
public function __construct() |
21
|
|
|
{ |
22
|
|
|
if (!class_exists(Client::class)) { |
23
|
|
|
throw new MissingLibraryException( |
24
|
|
|
'Predis library not installed' |
25
|
|
|
); |
26
|
|
|
} |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @param ContainerInterface $container |
31
|
|
|
* @param array $options |
32
|
|
|
* |
33
|
|
|
* @return PredisCachePool |
34
|
|
|
*/ |
35
|
4 |
|
public function __invoke(ContainerInterface $container, array $options): PredisCachePool |
36
|
|
|
{ |
37
|
4 |
|
$instance = $this->getInstance($container, $options); |
38
|
3 |
|
return new PredisCachePool($instance); |
39
|
|
|
} |
40
|
|
|
|
41
|
4 |
|
protected function getInstance(ContainerInterface $container, array $options) |
42
|
|
|
{ |
43
|
|
|
if ( |
44
|
4 |
|
empty($options['service']) |
45
|
4 |
|
&& empty($options['servers']) |
46
|
|
|
) { |
47
|
1 |
|
throw new InvalidConfigException( |
48
|
1 |
|
'You must provide either a container service or at least one server to use' |
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 Client |
64
|
|
|
*/ |
65
|
1 |
|
protected function getInstanceFromContainer(ContainerInterface $container, $name): Client |
66
|
|
|
{ |
67
|
1 |
|
return $container->get($name); |
68
|
|
|
} |
69
|
|
|
|
70
|
2 |
|
protected function getInstanceFromConfig(array $options): Client |
71
|
|
|
{ |
72
|
2 |
|
$servers = $options['servers'] ?? []; |
73
|
2 |
|
$connectionOptions = $options['connectionOptions'] ?? []; |
74
|
|
|
|
75
|
2 |
|
if (count($servers) === 1) { |
76
|
1 |
|
return new Client($servers[0], $connectionOptions); |
77
|
|
|
} |
78
|
|
|
|
79
|
1 |
|
return new Client($servers, $connectionOptions); |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|