Passed
Push — master ( 8ab621...bd425a )
by Stephen
02:23
created

RedisCache::keys()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 1
eloc 6
c 4
b 0
f 0
nc 1
nop 1
dl 0
loc 12
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 TTL from the config.
14
     *
15
     * @return int
16
     */
17
    public static function ttl(): int
18
    {
19
        return config('redis-helpers.ttl', 3600);
20
    }
21
22
    /**
23
     * Retrieve an array of keys that begin with a prefix.
24
     *
25
     * @param string $prefix
26
     * @return mixed list of keys without prefix
27
     */
28
    public static function keys(string $prefix = '')
29
    {
30
        return array_map(
31
            // Remove prefix from each key so it is not concatenated twice
32
            function ($key) {
33
                return substr($key, strlen(config('cache.prefix')) + 1);
34
            },
35
36
            // List of Redis key's matching pattern
37
            Redis::connection()
38
                ->client()
39
                ->keys(config('cache.prefix') . ":{$prefix}*")
40
        );
41
    }
42
43
    /**
44
     * Get items from the cache.
45
     *
46
     * @param string $key
47
     * @return mixed
48
     */
49
    public static function get(string $key)
50
    {
51
        return Cache::get($key);
52
    }
53
54
    /**
55
     * Put items in the cache with a TTL.
56
     *
57
     * Use's environment's REDIS_KEY_EXPIRATION value if $expiration is null.
58
     *
59
     * @param string $key
60
     * @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...
61
     * @param int|null $expiration
62
     * @return bool
63
     */
64
    public static function set(string $key, $value = null, int $expiration = null): bool
65
    {
66
        // Store the $value in the Cache
67
        // todo: optimize expiration call
68
        return Cache::put(
69
            $key,
70
            $value,
71
            (isset($expiration) ? $expiration : self::ttl())
72
        );
73
    }
74
75
    /**
76
     * Put an array of key value pairs into the cache with a TTL.
77
     *
78
     * @param array $array
79
     * @param int|null $expiration
80
     * @return array
81
     */
82
    public static function setMany(array $array, int $expiration = null): array
83
    {
84
        foreach ($array as $key => $value) {
85
            self::set($key, $value, $expiration);
86
        }
87
88
        return array_values($array);
89
    }
90
91
    /**
92
     * Add a TTL attribute (time to live or time til expiration) to a Redis key.
93
     *
94
     * @param string $key
95
     * @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...
96
     * @return bool
97
     */
98
    public static function expire(string $key, $expiration = null): bool
99
    {
100
        // Use environment REDIS_KEY_EXPIRATION value if not set
101
        if (! $expiration) {
0 ignored issues
show
introduced by
$expiration is of type null, thus it always evaluated to false.
Loading history...
102
            $expiration = self::ttl();
103
        }
104
105
        // Create a key value pair with a null value and a TTL if the key is missing
106
        if (self::missing($key)) {
107
            return self::set($key, null, $expiration);
108
        }
109
110
        // Create a key value pair with original value and a TTL if the key exists
111
        else {
112
            return self::set($key, self::get($key), $expiration);
113
        }
114
    }
115
116
    /**
117
     * Delete Redis key's from the Cache.
118
     *
119
     * @param $keys array|string
120
     * @return array
121
     */
122
    public static function delete($keys): array
123
    {
124
        // Returns an array of deleted keys with success values
125
        return collect((array) $keys)
126
            ->flatMap(function (string $key) {
127
                return self::keys($key);
128
            })
129
            ->mapWithKeys(function (string $key) {
130
                return [$key => Cache::forget($key)];
131
            })
132
            ->toArray();
133
    }
134
135
    /**
136
     * Determine if a redis key exists in the cache.
137
     *
138
     * @param string $key
139
     * @return bool
140
     */
141
    public static function exists(string $key): bool
142
    {
143
        return Cache::has($key);
144
    }
145
146
    /**
147
     * Determine if a redis key is missing from the cache.
148
     *
149
     * @param string $key
150
     * @return bool
151
     */
152
    public static function missing(string $key): bool
153
    {
154
        return Cache::missing($key);
155
    }
156
157
    /**
158
     * Create a Redis Key with a null value if it is missing.
159
     *
160
     * @param string $key
161
     * @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...
162
     * @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...
163
     * @return bool
164
     */
165
    public static function setIfMissing(string $key, $value = null, $expiration = null): bool
166
    {
167
        // Create the redis Key with an expiration
168
        if (self::missing($key)) {
169
            self::set($key, $value, $expiration);
170
171
            return true;
172
        }
173
174
        // Not created
175
        return false;
176
    }
177
178
    /**
179
     * Increment a Redis Key's value & return the new value.
180
     *
181
     * @param string $key
182
     * @param int $value
183
     * @param int|null $expiration
184
     * @return mixed
185
     */
186
    public static function increment(string $key, int $value = 1, int $expiration = null)
187
    {
188
        // Create the Key if it's missing
189
        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

189
        self::setIfMissing($key, 0, /** @scrutinizer ignore-type */ $expiration);
Loading history...
190
191
        // Increment the value & return the new value
192
        return Cache::increment($key, $value);
193
    }
194
195
    /**
196
     * Flush the entire redis cache.
197
     *
198
     * @return mixed
199
     */
200
    public static function flush()
201
    {
202
        return Cache::flush();
203
    }
204
205
    /**
206
     * Flush the redis cache of all keys with environment's prefix.
207
     *
208
     * @return array
209
     */
210
    public static function clear(): array
211
    {
212
        return self::delete('');
213
    }
214
215
    /**
216
     * Pass a $callback function to be stored in the Cache for an amount of time.
217
     *
218
     * @param string $key
219
     * @param int $ttl
220
     * @param Closure $callback
221
     * @return mixed
222
     */
223
    public static function remember(string $key, int $ttl, Closure $callback)
224
    {
225
        return Cache::remember($key, $ttl, $callback);
226
    }
227
228
    /**
229
     * Pass a $callback function to be stored in the Cache forever.
230
     *
231
     * @param string $key
232
     * @param Closure $callback
233
     * @return mixed
234
     */
235
    public static function rememberForever(string $key, Closure $callback)
236
    {
237
        return Cache::rememberForever($key, $callback);
238
    }
239
}
240