GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

Redis   B
last analyzed

Complexity

Total Complexity 39

Size/Duplication

Total Lines 176
Duplicated Lines 3.41 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
dl 6
loc 176
ccs 0
cts 63
cp 0
rs 8.2857
c 0
b 0
f 0
wmc 39
lcom 1
cbo 2

7 Methods

Rating   Name   Duplication   Size   Complexity  
A clear() 0 4 1
C __construct() 6 29 11
C get() 0 25 12
C set() 0 28 11
A delete() 0 4 1
A isSupported() 0 4 1
A __destruct() 0 6 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * Kotori.php
4
 *
5
 * A Tiny Model-View-Controller PHP Framework
6
 *
7
 * This content is released under the Apache 2 License
8
 *
9
 * Copyright (c) 2015-2017 Kotori Technology. All rights reserved.
10
 *
11
 * Licensed under the Apache License, Version 2.0 (the "License");
12
 * you may not use this file except in compliance with the License.
13
 * You may obtain a copy of the License at
14
 *
15
 *     http://www.apache.org/licenses/LICENSE-2.0
16
 *
17
 * Unless required by applicable law or agreed to in writing, software
18
 * distributed under the License is distributed on an "AS IS" BASIS,
19
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
 * See the License for the specific language governing permissions and
21
 * limitations under the License.
22
 */
23
24
/**
25
 * Redis Caching Class
26
 *
27
 * @package     Kotori
28
 * @subpackage  Cache
29
 * @author      Kokororin
30
 * @link        https://kotori.love
31
 */
32
namespace Kotori\Core\Cache;
33
34
use Kotori\Core\Container;
35
use Kotori\Exception\CacheException;
36
use RedisException;
37
38
class Redis
39
{
40
    /**
41
     * Default config
42
     *
43
     * @var array
44
     */
45
    protected $redisConf = [
46
        'host' => '127.0.0.1',
47
        'password' => null,
48
        'port' => 6379,
49
        'timeout' => 0,
50
        'database' => 0,
51
    ];
52
53
    /**
54
     * Redis connection
55
     *
56
     * @var Redis
57
     */
58
    protected $redis;
59
60
    /**
61
     * Class constructor
62
     *
63
     * Setup Redis
64
     *
65
     * Loads Redis config file if present. Will halt execution
66
     * if a Redis connection can't be established.
67
     *
68
     * @param   array $config
69
     *
70
     * @throws \Kotori\Exception\CacheException
71
     */
72
    public function __construct($config = [])
73
    {
74
        if (!$this->isSupported()) {
75
            throw new CacheException('Failed to create Redis object; extension not loaded?');
76
        }
77
78
        if (empty($config)) {
79
            $config = Container::get('config')->get('cache');
80
            $config = array_merge($this->redisConf, $config);
81
        }
82
83
        $this->redis = new \Redis();
0 ignored issues
show
Documentation Bug introduced by
It seems like new \Redis() of type object<Redis> is incompatible with the declared type object<Kotori\Core\Cache\Redis> of property $redis.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
84
85
        try {
86
            if (!$this->redis->connect($config['host'], ($config['host'][0] === '/' ? 0 : $config['port']), $config['timeout'])) {
87
                throw new CacheException('Redis connection failed. Check your configuration.');
88
            }
89
90 View Code Duplication
            if (isset($config['password']) && !$this->redis->auth($config['password'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
91
                throw new CacheException('Redis authentication failed.');
92
            }
93
94 View Code Duplication
            if (isset($config['database']) && $config['database'] > 0 && !$this->redis->select($config['database'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
95
                throw new CacheException('Redis select database failed.');
96
            }
97
        } catch (RedisException $e) {
98
            throw new CacheException('Redis connection refused (' . $e->getMessage() . ')');
99
        }
100
    }
101
102
    /**
103
     * Get cache
104
     *
105
     * @param   string  $key
106
     * @return  mixed
107
     */
108
    public function get($key)
109
    {
110
        $value = $this->redis->hMGet($key, ['type', 'value']);
0 ignored issues
show
Bug introduced by
The method hMGet() does not seem to exist on object<Kotori\Core\Cache\Redis>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
111
112
        if (!isset($value['type'], $value['value']) || $value['value'] === false) {
113
            return false;
114
        }
115
116
        switch ($value['type']) {
117
            case 'array':
118
            case 'object':
119
                return unserialize($value['value']);
120
            case 'boolean':
121
            case 'integer':
122
            case 'double': // Yes, 'double' is returned and NOT 'float'
123
            case 'string':
124
            case 'NULL':
125
                return settype($value['value'], $value['type'])
126
                ? $value['value']
127
                : false;
128
            case 'resource':
129
            default:
130
                return false;
131
        }
132
    }
133
134
    /**
135
     * Save cache
136
     *
137
     * @param   string    $key
138
     * @param   mixed     $value
139
     * @param   int       $ttl
140
     * @return  boolean
141
     */
142
    public function set($key, $value, $ttl = 60)
143
    {
144
        $dataType = gettype($value);
145
146
        switch ($dataType) {
147
            case 'array':
148
            case 'object':
149
                $value = serialize($value);
150
                break;
151
            case 'boolean':
152
            case 'integer':
153
            case 'double': // Yes, 'double' is returned and NOT 'float'
154
            case 'string':
155
            case 'NULL':
156
                break;
157
            case 'resource':
158
            default:
159
                return false;
160
        }
161
162
        if (!$this->redis->hMSet($key, ['type' => $dataType, 'value' => $value])) {
0 ignored issues
show
Bug introduced by
The method hMSet() does not seem to exist on object<Kotori\Core\Cache\Redis>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
163
            return false;
164
        } elseif ($ttl) {
165
            $this->redis->expireAt($key, time() + $ttl);
0 ignored issues
show
Bug introduced by
The method expireAt() does not seem to exist on object<Kotori\Core\Cache\Redis>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
166
        }
167
168
        return true;
169
    }
170
171
    /**
172
     * Delete from cache
173
     *
174
     * @param   string  $key
175
     * @return  boolean
176
     */
177
    public function delete($key)
178
    {
179
        return ($this->redis->delete($key) === 1);
180
    }
181
182
    /**
183
     * Clean cache
184
     *
185
     * @return  boolean
186
     */
187
    public function clear()
188
    {
189
        return $this->redis->flushDB();
0 ignored issues
show
Bug introduced by
The method flushDB() does not seem to exist on object<Kotori\Core\Cache\Redis>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
190
    }
191
192
    /**
193
     * Check if Redis driver is supported
194
     *
195
     * @return  boolean
196
     */
197
    public function isSupported()
198
    {
199
        return extension_loaded('redis');
200
    }
201
202
    /**
203
     * Class destructor
204
     *
205
     * Closes the connection to Redis if present.
206
     */
207
    public function __destruct()
208
    {
209
        if ($this->redis) {
210
            $this->redis->close();
0 ignored issues
show
Bug introduced by
The method close() does not seem to exist on object<Kotori\Core\Cache\Redis>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
211
        }
212
    }
213
}
214