RedisAdapter::isAvailable()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 11
rs 9.4286
cc 2
eloc 7
nc 2
nop 0
1
<?php
2
3
namespace NilPortugues\Cache\Adapter;
4
5
use NilPortugues\Cache\Adapter\Redis\AbstractAdapter;
6
use NilPortugues\Cache\CacheAdapter;
7
use Redis;
8
use RedisException;
9
10
/**
11
 * Class RedisAdapter
12
 * @package NilPortugues\Cache\Adapter\Redis
13
 */
14
class RedisAdapter extends AbstractAdapter
15
{
16
    /**
17
     * @param array           $connections
18
     * @param CacheAdapter    $next
19
     *
20
     * @throws \Exception
21
     */
22
    public function __construct(array $connections, CacheAdapter $next = null)
23
    {
24
        $this->isRedisExtensionAvailable();
25
26
        try {
27
            $connections = \array_values($connections);
28
            $this->connected = true;
29
30
            $this->redis = new Redis();
31
            $this->redis->connect($connections[0]['host'], $connections[0]['port'], $connections[0]['timeout']);
32
            $this->redis->select($connections[0]['database']);
33
        } catch (RedisException $e) {
0 ignored issues
show
Bug introduced by
The class RedisException does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
34
            $this->connected = false;
35
        }
36
37
        $this->nextAdapter     = (InMemoryAdapter::getInstance() === $next) ? null: $next;
38
    }
39
40
41
    /**
42
     * Checks the availability of the cache service.
43
     *
44
     * @return bool
45
     */
46
    public function isAvailable()
47
    {
48
        $available = true;
49
        try {
50
            $this->redis->ping();
51
        } catch (RedisException $e) {
0 ignored issues
show
Bug introduced by
The class RedisException does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
52
            $available = false;
53
        }
54
55
        return $available;
56
    }
57
58
    /**
59
     * @throws \Exception
60
     * @codeCoverageIgnore
61
     */
62
    private function isRedisExtensionAvailable()
63
    {
64
        if (false === \class_exists('\Redis')) {
65
            throw new \Exception(
66
                \sprintf(
67
                    'Redis extension for PHP is not installed on the system, use %s class instead.',
68
                    '\NilPortugues\Cache\Adapter\PredisAdapter'
69
                )
70
            );
71
        }
72
    }
73
}
74