Passed
Pull Request — master (#731)
by
unknown
02:32
created

Driver::driverConnect()   B

Complexity

Conditions 11
Paths 16

Size

Total Lines 46
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 11
eloc 19
c 2
b 0
f 0
nc 16
nop 0
dl 0
loc 46
rs 7.3166

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