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.
Completed
Push — master ( 6a8fe9...bdbe09 )
by やかみ
02:52
created

Redis::clear()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 4
ccs 0
cts 2
cp 0
crap 2
rs 10
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
     * @return  void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
70
     *
71
     * @throws \Kotori\Exception\CacheException
72
     */
73
    public function __construct($config = [])
74
    {
75
        if (!$this->isSupported()) {
76
            throw new CacheException('Failed to create Redis object; extension not loaded?');
77
        }
78
79
        if (empty($config)) {
80
            $config = Container::get('config')->get('cache');
81
            $config = array_merge($this->redisConf, $config);
82
        }
83
84
        $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...
85
86
        try
87
        {
88
            if (!$this->redis->connect($config['host'], ($config['host'][0] === '/' ? 0 : $config['port']), $config['timeout'])) {
89
                throw new CacheException('Redis connection failed. Check your configuration.');
90
            }
91
92
            if (isset($config['password']) && !$this->redis->auth($config['password'])) {
93
                throw new CacheException('Redis authentication failed.');
94
            }
95
96
            if (isset($config['database']) && $config['database'] > 0 && !$this->redis->select($config['database'])) {
97
                throw new CacheException('Redis select database failed.');
98
            }
99
        } catch (RedisException $e) {
100
            throw new CacheException('Redis connection refused (' . $e->getMessage() . ')');
101
        }
102
    }
103
104
    /**
105
     * Get cache
106
     *
107
     * @param   string  $key
108
     * @return  mixed
109
     */
110
    public function get($key)
111
    {
112
        $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...
113
114
        if (!isset($value['type'], $value['value']) or $value['value'] === false) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
115
            return false;
116
        }
117
118
        switch ($value['type']) {
119
            case 'array':
120
            case 'object':
121
                return unserialize($value['value']);
122
            case 'boolean':
123
            case 'integer':
124
            case 'double': // Yes, 'double' is returned and NOT 'float'
125
            case 'string':
126
            case 'NULL':
127
                return settype($value['value'], $value['type'])
128
                ? $value['value']
129
                : false;
130
            case 'resource':
131
            default:
132
                return false;
133
        }
134
    }
135
136
    /**
137
     * Save cache
138
     *
139
     * @param   string    $key
140
     * @param   mixed     $value
141
     * @param   int       $ttl
142
     * @return  boolean
143
     */
144
    public function set($key, $value, $ttl = 60)
145
    {
146
        $dataType = gettype($value);
147
148
        switch ($dataType) {
149
            case 'array':
150
            case 'object':
151
                $value = serialize($value);
152
                break;
153
            case 'boolean':
154
            case 'integer':
155
            case 'double': // Yes, 'double' is returned and NOT 'float'
156
            case 'string':
157
            case 'NULL':
158
                break;
159
            case 'resource':
160
            default:
161
                return false;
162
        }
163
164
        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...
165
            return false;
166
        } elseif ($ttl) {
167
            $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...
168
        }
169
170
        return true;
171
    }
172
173
    /**
174
     * Delete from cache
175
     *
176
     * @param   string  $key
177
     * @return  boolean
178
     */
179
    public function delete($key)
180
    {
181
        return ($this->redis->delete($key) === 1);
182
    }
183
184
    /**
185
     * Clean cache
186
     *
187
     * @return  boolean
188
     */
189
    public function clear()
190
    {
191
        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...
192
    }
193
194
    /**
195
     * Check if Redis driver is supported
196
     *
197
     * @return  boolean
198
     */
199
    public function isSupported()
200
    {
201
        return extension_loaded('redis');
202
    }
203
204
    /**
205
     * Class destructor
206
     *
207
     * Closes the connection to Redis if present.
208
     *
209
     * @return  void
210
     */
211
    public function __destruct()
212
    {
213
        if ($this->redis) {
214
            $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...
215
        }
216
    }
217
}
218