Cache::getAdapter()   B
last analyzed

Complexity

Conditions 7
Paths 4

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 15.4039

Importance

Changes 0
Metric Value
cc 7
eloc 8
nc 4
nop 1
dl 0
loc 14
ccs 4
cts 9
cp 0.4444
crap 15.4039
rs 8.8333
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Bluz Framework Component
5
 *
6
 * @copyright Bluz PHP Team
7
 * @link      https://github.com/bluzphp/framework
8
 */
9
10
declare(strict_types=1);
11
12
namespace Bluz\Proxy;
13
14
use Bluz\Common\Exception\ComponentException;
15
use Symfony\Component\Cache\Adapter\TagAwareAdapterInterface;
0 ignored issues
show
Bug introduced by
The type Symfony\Component\Cache\...agAwareAdapterInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
16
use Symfony\Component\Cache\Adapter\AdapterInterface as Instance;
0 ignored issues
show
Bug introduced by
The type Symfony\Component\Cache\Adapter\AdapterInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
17
use Psr\Cache\InvalidArgumentException;
0 ignored issues
show
Bug introduced by
The type Psr\Cache\InvalidArgumentException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
18
19
/**
20
 * Proxy to Cache
21
 *
22
 * Example of usage
23
 *     use Bluz\Proxy\Cache;
24
 *
25
 *     if (!$result = Cache::get('some unique id')) {
26
 *          $result = 2*2;
27
 *          Cache::set('some unique id', $result);
28
 *     }
29
 *
30
 * @package  Bluz\Proxy
31
 * @author   Anton Shevchuk
32
 *
33
 * @method   static Instance|false getInstance()
34
 *
35
 * @method   static bool delete($key)
36
 * @see      Instance::deleteItem()
37
 *
38
 * @method   static bool clear()
39
 * @see      Instance::clear()
40
 */
41
final class Cache
42
{
43
    use ProxyTrait;
44
45
    /**
46
     * No expiry TTL value
47
     */
48
    public const TTL_NO_EXPIRY = 0;
49
50
    /**
51
     * @var array
52
     */
53
    private static $pools = [];
54
55
    /**
56
     * Init cache instance
57
     *
58
     * @return Instance|false
59
     * @throws ComponentException
60
     */
61 587
    private static function initInstance()
0 ignored issues
show
Unused Code introduced by
The method initInstance() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
62
    {
63 587
        $adapter = Config::get('cache', 'adapter');
64 587
        return self::getAdapter($adapter);
65
    }
66
67
    /**
68
     * Get Cache Adapter
69
     *
70
     * @param string $adapter
71
     *
72
     * @return Instance|false
73
     * @throws ComponentException
74
     */
75 587
    public static function getAdapter(string $adapter)
76
    {
77 587
        $config = Config::get('cache');
78
79 587
        if ($config && $adapter && isset($config['enabled']) && $config['enabled']) {
80
            if (!isset($config['pools'][$adapter])) {
81
                throw new ComponentException("Class `Proxy\\Cache` required configuration for `$adapter` adapter");
82
            }
83
            if (!isset(Cache::$pools[$adapter])) {
84
                Cache::$pools[$adapter] = $config['pools'][$adapter]();
85
            }
86
            return Cache::$pools[$adapter];
87
        }
88 587
        return false;
89
    }
90
91
    /**
92
     * Get value of cache item
93
     *
94
     * @param string $key
95
     *
96
     * @return mixed
97
     */
98 587
    public static function get(string $key)
99
    {
100 587
        if (!$cache = self::getInstance()) {
101 587
            return false;
102
        }
103
104
        $key = self::prepare($key);
105
106
        try {
107
            if ($cache->hasItem($key)) {
108
                $item = $cache->getItem($key);
109
                if ($item->isHit()) {
110
                    return $item->get();
111
                }
112
            }
113
        } catch (InvalidArgumentException $e) {
114
            // something going wrong
115
            Logger::error($e->getMessage());
116
        }
117
118
        return false;
119
    }
120
121
    /**
122
     * Set value of cache item
123
     *
124
     * @param  string   $key
125
     * @param  mixed    $data
126
     * @param  int      $ttl
127
     * @param  string[] $tags
128
     *
129
     * @return bool
130
     */
131 587
    public static function set(string $key, $data, int $ttl = self::TTL_NO_EXPIRY, array $tags = [])
132
    {
133 587
        if (!$cache = self::getInstance()) {
134 587
            return false;
135
        }
136
137
        $key = self::prepare($key);
138
        try {
139
            $item = $cache->getItem($key);
140
            $item->set($data);
141
142
            if (self::TTL_NO_EXPIRY !== $ttl) {
143
                $item->expiresAfter($ttl);
144
            }
145
146
            if (!empty($tags)) {
147
                $item->tag($tags);
148
            }
149
150
            return $cache->save($item);
151
        } catch (InvalidArgumentException $e) {
152
            // something going wrong
153
            Logger::error($e->getMessage());
154
        }
155
156
        return false;
157
    }
158
159
    /**
160
     * Prepare key
161
     *
162
     * @param  string $key
163
     *
164
     * @return string
165
     */
166
    public static function prepare(string $key): string
167
    {
168
        return str_replace(['-', '/', '\\', '@', ':'], '_', $key);
169
    }
170
171
    /**
172
     * Clear cache items by tag
173
     *
174
     * @param  string $tag
175
     *
176
     * @return bool
177
     */
178
    public static function clearTag(string $tag): bool
179
    {
180
        if (self::getInstance() instanceof TagAwareAdapterInterface) {
181
            return self::getInstance()->invalidateTags([$tag]);
182
        }
183
        return false;
184
    }
185
186
    /**
187
     * Clear cache items by tags
188
     *
189
     * @param array $tags
190
     *
191
     * @return bool
192
     */
193
    public static function clearTags(array $tags): bool
194
    {
195
        if (self::getInstance() instanceof TagAwareAdapterInterface) {
196
            return self::getInstance()->invalidateTags($tags);
197
        }
198
        return false;
199
    }
200
}
201