Passed
Push — master ( f22f3e...23161b )
by Stephen
02:08
created

RedisCache::ttl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
namespace Sfneal\Helpers\Redis;
4
5
use Closure;
6
use Illuminate\Support\Facades\Cache;
7
use Illuminate\Support\Facades\Redis;
8
use Sfneal\Actions\AbstractService;
9
10
class RedisCache extends AbstractService
11
{
12
    /**
13
     * Retrieve the Redis Key prefix from the config
14
     *
15
     * @return string
16
     */
17
    public static function prefix(): string
18
    {
19
        return config('redis-helpers.prefix', 'app');
20
    }
21
22
    /**
23
     * Retrieve the Redis Key TTL from the config
24
     *
25
     * @return int
26
     */
27
    public static function ttl(): int
28
    {
29
        return config('redis-helpers.ttl', '3600');
30
    }
31
32
    /**
33
     * Retrieve a formatted RedisKey with the environment prefix included.
34
     *
35
     * @param string $key
36
     * @return string
37
     */
38
    public static function key(string $key): string
39
    {
40
        return self::prefix() . ":$key";
41
    }
42
43
    /**
44
     * Retrieve an array of keys that begin with a prefix.
45
     *
46
     * @param string $prefix
47
     * @return mixed list of keys without prefix
48
     */
49
    public static function keys(string $prefix)
50
    {
51
        return array_map(
52
        // Remove prefix from each key so it is not concatenated twice
53
            function ($key) {
54
                return substr($key, strlen(self::prefix()) + 1);
55
            },
56
57
            // List of Redis key's matching pattern
58
            Redis::connection('default')->client()->keys(self::key($prefix.'*'))
59
        );
60
    }
61
62
    /**
63
     * Get items from the cache.
64
     *
65
     * @param string $key
66
     * @return mixed
67
     */
68
    public static function get(string $key)
69
    {
70
        return Cache::get(self::key($key));
71
    }
72
73
    /**
74
     * Put items in the cache with a TTL.
75
     *
76
     * Use's environment's REDIS_KEY_EXPIRATION value if $expiration is null.
77
     *
78
     * @param string $key
79
     * @param null $value
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $value is correct as it would always require null to be passed?
Loading history...
80
     * @param null $expiration
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $expiration is correct as it would always require null to be passed?
Loading history...
81
     * @return string
82
     */
83
    public static function set(string $key, $value = null, $expiration = null)
84
    {
85
        // Store the $value in the Cache
86
        Cache::put(
87
            $key,
88
            $value,
89
            (isset($expiration) ? $expiration : self::ttl())
90
        );
91
92
        // Return the $value
93
        return $value;
94
    }
95
96
    /**
97
     * Add a TTL attribute (time to live or time til expiration) to a Redis key.
98
     *
99
     * @param string $key
100
     * @param null $expiration
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $expiration is correct as it would always require null to be passed?
Loading history...
101
     * @return string|null
102
     */
103
    public static function expire(string $key, $expiration = null)
104
    {
105
        // Use environment REDIS_KEY_EXPIRATION value if not set
106
        if (! $expiration) {
0 ignored issues
show
introduced by
$expiration is of type null, thus it always evaluated to false.
Loading history...
107
            $expiration = self::ttl();
108
        }
109
110
        // Create a key value pair with a null value and a TTL if the key is missing
111
        if (self::missing($key)) {
112
            return self::set($key, null, $expiration);
113
        }
114
115
        // Create a key value pair with original value and a TTL if the key exists
116
        else {
117
            return self::set($key, self::get($key), $expiration);
118
        }
119
    }
120
121
    /**
122
     * Delete Redis key's from the Cache.
123
     *
124
     * @param $key array|string
125
     * @return mixed
126
     */
127
    public static function delete($key)
128
    {
129
        // Empty array of keys to delete
130
        $keys = [];
131
132
        // Check if an array of keys has been passed
133
        if (gettype($key) == 'array') {
134
            // Recursively merge arrays of keys found matching pattern
135
            foreach (array_values($key) as $value) {
136
                $keys = array_merge($keys, self::keys($value));
137
            }
138
        } else {
139
            // All keys matching pattern
140
            $keys = array_merge($keys, self::keys($key));
141
        }
142
143
        // Remove all keys that match param patterns
144
        $to_remove = array_values($keys);
145
        foreach ($to_remove as $value) {
146
            Cache::forget($value);
147
        }
148
149
        // Return array of deleted keys
150
        return array_values($to_remove);
151
    }
152
153
    /**
154
     * Determine if a redis key exists in the cache.
155
     *
156
     * @param string $key
157
     * @return bool
158
     */
159
    public static function exists(string $key): bool
160
    {
161
        return Cache::has(self::key($key));
162
    }
163
164
    /**
165
     * Determine if a redis key is missing from the cache.
166
     *
167
     * @param string $key
168
     * @return bool
169
     */
170
    public static function missing(string $key): bool
171
    {
172
        return Cache::missing(self::key($key));
173
    }
174
175
    /**
176
     * Create a Redis Key with a null value if it is missing.
177
     *
178
     * @param string $key
179
     * @param null $value
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $value is correct as it would always require null to be passed?
Loading history...
180
     * @param null $expiration
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $expiration is correct as it would always require null to be passed?
Loading history...
181
     * @return bool
182
     */
183
    public static function setIfMissing(string $key, $value = null, $expiration = null): bool
184
    {
185
        // Create the redis Key with an expiration
186
        if (self::missing($key)) {
187
            self::set($key, $value, $expiration);
188
189
            return true;
190
        }
191
192
        // Not created
193
        return false;
194
    }
195
196
    /**
197
     * Increment a Redis Key's value & return the new value.
198
     *
199
     * @param string $key
200
     * @param int $value
201
     * @param int|null $expiration
202
     * @return mixed
203
     */
204
    public static function increment(string $key, int $value = 1, int $expiration = null)
205
    {
206
        // Create the Key if it's missing
207
        self::setIfMissing($key, 0, $expiration);
0 ignored issues
show
Bug introduced by
It seems like $expiration can also be of type integer; however, parameter $expiration of Sfneal\Helpers\Redis\RedisCache::setIfMissing() does only seem to accept null, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

207
        self::setIfMissing($key, 0, /** @scrutinizer ignore-type */ $expiration);
Loading history...
208
209
        // Increment the value
210
        Cache::increment(self::key($key), $value);
211
212
        // Return the new value
213
        // todo: check if this is needed
214
        return self::get($key);
215
    }
216
217
    /**
218
     * Flush the entire redis cache.
219
     *
220
     * @return mixed
221
     */
222
    public static function flush()
223
    {
224
        return Redis::connection('default')->client()->flushAll();
225
    }
226
227
    /**
228
     * Flush the redis cache of all keys with environment's prefix.
229
     *
230
     * @return mixed
231
     */
232
    public static function clear()
233
    {
234
        return self::delete('');
235
    }
236
237
    /**
238
     * Pass a $callback function to be stored in the Cache for an amount of time.
239
     *
240
     * @param string $key
241
     * @param int $ttl
242
     * @param Closure $callback
243
     * @return mixed
244
     */
245
    public static function remember(string $key, int $ttl, Closure $callback)
246
    {
247
        return Cache::remember($key, $ttl, $callback);
248
    }
249
250
    /**
251
     * Pass a $callback function to be stored in the Cache forever.
252
     *
253
     * @param string $key
254
     * @param Closure $callback
255
     * @return mixed
256
     */
257
    public static function rememberForever(string $key, Closure $callback)
258
    {
259
        return Cache::rememberForever($key, $callback);
260
    }
261
}
262