Completed
Pull Request — master (#629)
by Georges
04:13
created

Driver::driverConnect()   C

Complexity

Conditions 12
Paths 24

Size

Total Lines 48

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
nc 24
nop 0
dl 0
loc 48
rs 6.9666
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()->getOptPrefix()){
85
            $this->instance->setOption(RedisClient::OPT_PREFIX, $this->getConfig()->getOptPrefix());
86
        }
87
88
        if (!$this->getConfig()->getPath()) {
89
            if ($this->getConfig()->getPassword() && !$this->instance->auth($this->getConfig()->getPassword())) {
90
                return false;
91
            }
92
        }
93
94
        if ($this->getConfig()->getDatabase() !== null) {
95
            $this->instance->select($this->getConfig()->getDatabase());
96
        }
97
        return true;
98
    }
99
100
    /**
101
     * @param \Psr\Cache\CacheItemInterface $item
102
     * @return null|array
103
     */
104
    protected function driverRead(CacheItemInterface $item)
105
    {
106
        $val = $this->instance->get($item->getKey());
107
        if ($val == false) {
108
            return null;
109
        }
110
111
        return $this->decode($val);
112
    }
113
114
    /**
115
     * @param \Psr\Cache\CacheItemInterface $item
116
     * @return mixed
117
     * @throws PhpfastcacheInvalidArgumentException
118
     */
119
    protected function driverWrite(CacheItemInterface $item): bool
120
    {
121
        /**
122
         * Check for Cross-Driver type confusion
123
         */
124
        if ($item instanceof Item) {
125
            $ttl = $item->getExpirationDate()->getTimestamp() - \time();
126
127
            /**
128
             * @see https://redis.io/commands/setex
129
             * @see https://redis.io/commands/expire
130
             */
131
            if ($ttl <= 0) {
132
                return $this->instance->expire($item->getKey(), 0);
133
            }
134
135
            return $this->instance->setex($item->getKey(), $ttl, $this->encode($this->driverPreWrap($item)));
136
        }
137
138
        throw new PhpfastcacheInvalidArgumentException('Cross-Driver type confusion detected');
139
    }
140
141
    /**
142
     * @param \Psr\Cache\CacheItemInterface $item
143
     * @return bool
144
     * @throws PhpfastcacheInvalidArgumentException
145
     */
146
    protected function driverDelete(CacheItemInterface $item): bool
147
    {
148
        /**
149
         * Check for Cross-Driver type confusion
150
         */
151
        if ($item instanceof Item) {
152
            return (bool)$this->instance->del($item->getKey());
153
        }
154
155
        throw new PhpfastcacheInvalidArgumentException('Cross-Driver type confusion detected');
156
    }
157
158
    /**
159
     * @return bool
160
     */
161
    protected function driverClear(): bool
162
    {
163
        return $this->instance->flushDB();
164
    }
165
166
    /********************
167
     *
168
     * PSR-6 Extended Methods
169
     *
170
     *******************/
171
172
    /**
173
     * @return DriverStatistic
174
     */
175
    public function getStats(): DriverStatistic
176
    {
177
        // used_memory
178
        $info = $this->instance->info();
179
        $date = (new \DateTime())->setTimestamp(\time() - $info['uptime_in_seconds']);
180
181
        return (new DriverStatistic())
182
            ->setData(\implode(', ', \array_keys($this->itemInstances)))
183
            ->setRawData($info)
184
            ->setSize((int)$info['used_memory'])
185
            ->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.",
186
                $info['redis_version'], $date->format(\DATE_RFC2822)));
187
    }
188
}