Completed
Push — master ( 4e7427...4a94bb )
by Georges
12s
created

Driver::driverConnect()   B

Complexity

Conditions 11
Paths 14

Size

Total Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
nc 14
nop 0
dl 0
loc 44
rs 7.3166
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 *
4
 * This file is part of phpFastCache.
5
 *
6
 * @license MIT License (MIT)
7
 *
8
 * For full copyright and license information, please see the docs/CREDITS.txt file.
9
 *
10
 * @author Khoa Bui (khoaofgod)  <[email protected]> https://www.phpfastcache.com
11
 * @author Georges.L (Geolim4)  <[email protected]>
12
 *
13
 */
14
declare(strict_types=1);
15
16
namespace Phpfastcache\Drivers\Redis;
17
18
use Phpfastcache\Core\Pool\{
19
    DriverBaseTrait, ExtendedCacheItemPoolInterface
20
};
21
use Phpfastcache\Entities\DriverStatistic;
22
use Phpfastcache\Exceptions\{
23
    PhpfastcacheInvalidArgumentException, PhpfastcacheLogicException
24
};
25
use Psr\Cache\CacheItemInterface;
26
use Redis as RedisClient;
27
28
/**
29
 * Class Driver
30
 * @package phpFastCache\Drivers
31
 * @property Config $config Config object
32
 * @method Config getConfig() Return the config object
33
 */
34
class Driver implements ExtendedCacheItemPoolInterface
35
{
36
    use DriverBaseTrait;
37
38
    /**
39
     * @return bool
40
     */
41
    public function driverCheck(): bool
42
    {
43
        return \extension_loaded('Redis');
44
    }
45
46
    /**
47
     * @return bool
48
     * @throws PhpfastcacheLogicException
49
     */
50
    protected function driverConnect(): bool
51
    {
52
        if ($this->instance instanceof RedisClient) {
53
            throw new PhpfastcacheLogicException('Already connected to Redis server');
54
        }
55
56
        /**
57
         * In case of an user-provided
58
         * Redis client just return here
59
         */
60
        if ($this->getConfig()->getRedisClient() instanceof RedisClient) {
0 ignored issues
show
introduced by
$this->getConfig()->getRedisClient() is always a sub-type of Redis.
Loading history...
61
            /**
62
             * Unlike Predis, we can't test if we're are connected
63
             * or not, so let's just assume that we are
64
             */
65
            $this->instance = $this->getConfig()->getRedisClient();
66
            return true;
67
        }
68
69
        $this->instance = $this->instance ?: new RedisClient();
70
71
        /**
72
         * If path is provided we consider it as an UNIX Socket
73
         */
74
        if ($this->getConfig()->getPath()) {
75
            $isConnected = $this->instance->connect($this->getConfig()->getPath());
76
        } else {
77
            $isConnected = $this->instance->connect($this->getConfig()->getHost(), $this->getConfig()->getPort(), $this->getConfig()->getTimeout());
78
        }
79
80
        if (!$isConnected && $this->getConfig()->getPath()) {
81
            return false;
82
        }
83
84
        if (!$this->getConfig()->getPath()) {
85
            if ($this->getConfig()->getPassword() && !$this->instance->auth($this->getConfig()->getPassword())) {
86
                return false;
87
            }
88
        }
89
90
        if ($this->getConfig()->getDatabase() !== null) {
91
            $this->instance->select($this->getConfig()->getDatabase());
92
        }
93
        return true;
94
    }
95
96
    /**
97
     * @param \Psr\Cache\CacheItemInterface $item
98
     * @return null|array
99
     */
100
    protected function driverRead(CacheItemInterface $item)
101
    {
102
        $val = $this->instance->get($item->getKey());
103
        if ($val == false) {
104
            return null;
105
        }
106
107
        return $this->decode($val);
108
    }
109
110
    /**
111
     * @param \Psr\Cache\CacheItemInterface $item
112
     * @return mixed
113
     * @throws PhpfastcacheInvalidArgumentException
114
     */
115
    protected function driverWrite(CacheItemInterface $item): bool
116
    {
117
        /**
118
         * Check for Cross-Driver type confusion
119
         */
120
        if ($item instanceof Item) {
121
            $ttl = $item->getExpirationDate()->getTimestamp() - \time();
122
123
            /**
124
             * @see https://redis.io/commands/setex
125
             * @see https://redis.io/commands/expire
126
             */
127
            if ($ttl <= 0) {
128
                return $this->instance->expire($item->getKey(), 0);
129
            }
130
131
            return $this->instance->setex($item->getKey(), $ttl, $this->encode($this->driverPreWrap($item)));
132
        }
133
134
        throw new PhpfastcacheInvalidArgumentException('Cross-Driver type confusion detected');
135
    }
136
137
    /**
138
     * @param \Psr\Cache\CacheItemInterface $item
139
     * @return bool
140
     * @throws PhpfastcacheInvalidArgumentException
141
     */
142
    protected function driverDelete(CacheItemInterface $item): bool
143
    {
144
        /**
145
         * Check for Cross-Driver type confusion
146
         */
147
        if ($item instanceof Item) {
148
            return (bool)$this->instance->del($item->getKey());
149
        }
150
151
        throw new PhpfastcacheInvalidArgumentException('Cross-Driver type confusion detected');
152
    }
153
154
    /**
155
     * @return bool
156
     */
157
    protected function driverClear(): bool
158
    {
159
        return $this->instance->flushDB();
160
    }
161
162
    /********************
163
     *
164
     * PSR-6 Extended Methods
165
     *
166
     *******************/
167
168
    /**
169
     * @return DriverStatistic
170
     */
171
    public function getStats(): DriverStatistic
172
    {
173
        // used_memory
174
        $info = $this->instance->info();
175
        $date = (new \DateTime())->setTimestamp(\time() - $info['uptime_in_seconds']);
176
177
        return (new DriverStatistic())
178
            ->setData(\implode(', ', \array_keys($this->itemInstances)))
179
            ->setRawData($info)
180
            ->setSize((int)$info['used_memory'])
181
            ->setInfo(\sprintf("The Redis daemon v%s is up since %s.\n For more information see RawData. \n Driver size includes the memory allocation size.",
182
                $info['redis_version'], $date->format(\DATE_RFC2822)));
183
    }
184
}