PredisAdapterFactory::getInstance()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 8
c 1
b 0
f 0
nc 3
nop 2
dl 0
loc 16
ccs 8
cts 8
cp 1
crap 4
rs 10
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