Completed
Pull Request — master (#439)
by Anton
27:34
created

Cache::initInstance()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * Bluz Framework Component
4
 *
5
 * @copyright Bluz PHP Team
6
 * @link      https://github.com/bluzphp/framework
7
 */
8
9
declare(strict_types=1);
10
11
namespace Bluz\Proxy;
12
13
use Bluz\Common\Exception\ComponentException;
14
use Cache\Hierarchy\HierarchicalPoolInterface;
15
use Cache\TagInterop\TaggableCacheItemPoolInterface as Instance;
16
use Psr\Cache\InvalidArgumentException;
17
18
/**
19
 * Proxy to Cache
20
 *
21
 * Example of usage
22
 *     use Bluz\Proxy\Cache;
23
 *
24
 *     if (!$result = Cache::get('some unique id')) {
25
 *          $result = 2*2;
26
 *          Cache::set('some unique id', $result);
27
 *     }
28
 *
29
 * @package  Bluz\Proxy
30
 * @author   Anton Shevchuk
31
 *
32
 * @method   static Instance|false getInstance()
33
 *
34
 * @method   static bool delete($key)
35
 * @see      Instance::deleteItem()
36
 *
37
 * @method   static bool clear()
38
 * @see      Instance::clear()
39
 */
40
final class Cache
41
{
42
    use ProxyTrait;
43
44
    /**
45
     * No expiry TTL value
46
     */
47
    const TTL_NO_EXPIRY = 0;
48
49
    /**
50
     * @var array
51
     */
52
    private static $pools = [];
53
54
    /**
55
     * Init cache instance
56
     *
57
     * @return Instance|false
58
     * @throws ComponentException
59
     */
60 556
    private static function initInstance()
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
61
    {
62 556
        $adapter = Config::getData('cache', 'adapter');
63 556
        return self::getAdapter($adapter);
64
    }
65
66
    /**
67
     * Get Cache Adapter
68
     *
69
     * @param  string $adapter
70
     *
71
     * @return Instance|false
72
     * @throws ComponentException
73
     */
74 556
    public static function getAdapter($adapter)
75
    {
76 556
        $config = Config::getData('cache');
77
78 556
        if ($config && $adapter && isset($config['enabled']) && $config['enabled']) {
79
            if (!isset($config['pools'][$adapter])) {
80
                throw new ComponentException("Class `Proxy\\Cache` required configuration for `$adapter` adapter");
81
            }
82
            if (!isset(static::$pools[$adapter])) {
0 ignored issues
show
Comprehensibility introduced by
Since Bluz\Proxy\Cache is declared final, using late-static binding will have no effect. You might want to replace static with self instead.

Late static binding only has effect in subclasses. A final class cannot be extended anymore so late static binding cannot occurr. Consider replacing static:: with self::.

To learn more about late static binding, please refer to the PHP core documentation.

Loading history...
83
                static::$pools[$adapter] = $config['pools'][$adapter]();
0 ignored issues
show
Comprehensibility introduced by
Since Bluz\Proxy\Cache is declared final, using late-static binding will have no effect. You might want to replace static with self instead.

Late static binding only has effect in subclasses. A final class cannot be extended anymore so late static binding cannot occurr. Consider replacing static:: with self::.

To learn more about late static binding, please refer to the PHP core documentation.

Loading history...
84
            }
85
            return static::$pools[$adapter];
0 ignored issues
show
Comprehensibility introduced by
Since Bluz\Proxy\Cache is declared final, using late-static binding will have no effect. You might want to replace static with self instead.

Late static binding only has effect in subclasses. A final class cannot be extended anymore so late static binding cannot occurr. Consider replacing static:: with self::.

To learn more about late static binding, please refer to the PHP core documentation.

Loading history...
86
        }
87 556
        return false;
88
    }
89
90
    /**
91
     * Get value of cache item
92
     *
93
     * @param  string $key
94
     *
95
     * @return mixed
96
     */
97 557
    public static function get($key)
98
    {
99 557
        if (!$cache = self::getInstance()) {
100 557
            return false;
101
        }
102
103
        $key = self::prepare($key);
104
105
        try {
106
            if ($cache->hasItem($key)) {
107
                $item = $cache->getItem($key);
108
                if ($item->isHit()) {
109
                    return $item->get();
110
                }
111
            }
112
        } catch (InvalidArgumentException $e) {
113
            // something going wrong
114
            Logger::error($e->getMessage());
115
        }
116
117
        return false;
118
    }
119
120
    /**
121
     * Set value of cache item
122
     *
123
     * @param  string   $key
124
     * @param  mixed    $data
125
     * @param  int      $ttl
126
     * @param  string[] $tags
127
     *
128
     * @return bool
129
     */
130 557
    public static function set($key, $data, $ttl = self::TTL_NO_EXPIRY, $tags = [])
131
    {
132 557
        if (!$cache = self::getInstance()) {
133 557
            return false;
134
        }
135
136
        $key = self::prepare($key);
137
        try {
138
            $item = $cache->getItem($key);
139
            $item->set($data);
140
141
            if (self::TTL_NO_EXPIRY !== $ttl) {
142
                $item->expiresAfter($ttl);
143
            }
144
145
            if (!empty($tags)) {
146
                $item->setTags($tags);
147
            }
148
149
            return $cache->save($item);
150
        } catch (InvalidArgumentException $e) {
151
            // something going wrong
152
            Logger::error($e->getMessage());
153
        }
154
155
        return false;
156
    }
157
158
    /**
159
     * Prepare key
160
     *
161
     * @param  string $key
162
     *
163
     * @return string
164
     */
165
    public static function prepare($key)
166
    {
167
        return str_replace(['-', '/', '\\', '@', ':'], '_', $key);
168
    }
169
170
    /**
171
     * Clear cache items by tag
172
     *
173
     * @see    TaggableCacheItemPoolInterface::invalidateTag()
174
     *
175
     * @param string $tag
176
     *
177
     * @return bool
178
     */
179
    public static function clearTag($tag)
180
    {
181
        if (self::getInstance() instanceof HierarchicalPoolInterface) {
182
            return self::getInstance()->invalidateTag($tag);
183
        }
184
        return false;
185
    }
186
187
    /**
188
     * Clear cache items by tags
189
     *
190
     * @see    TaggableCacheItemPoolInterface::invalidateTags()
191
     *
192
     * @param array $tags
193
     *
194
     * @return bool
195
     */
196
    public static function clearTags(array $tags)
197
    {
198
        if (self::getInstance() instanceof HierarchicalPoolInterface) {
199
            return self::getInstance()->invalidateTags($tags);
200
        }
201
        return false;
202
    }
203
}
204