Completed
Pull Request — master (#422)
by Anton
05:12
created

Cache::get()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 14.6179

Importance

Changes 0
Metric Value
cc 5
eloc 12
nc 8
nop 1
dl 0
loc 22
ccs 3
cts 11
cp 0.2727
crap 14.6179
rs 8.6737
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\Taggable\TaggablePoolInterface 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      CacheItemPoolInterface::deleteItem()
36
 *
37
 * @method   static bool clear()
38
 * @see      CacheItemPoolInterface::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
    protected static $pools = [];
53
54
    /**
55
     * Init cache instance
56
     *
57
     * @return Instance|false
58
     * @throws ComponentException
59
     */
60
    protected static function initInstance()
61
    {
62
        $adapter = Config::getData('cache', 'adapter');
63
        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
    public static function getAdapter($adapter)
75
    {
76
        $config = Config::getData('cache');
77
78
        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])) {
83
                static::$pools[$adapter] = $config['pools'][$adapter]();
84
            }
85
            return static::$pools[$adapter];
86
        }
87
        return false;
88
    }
89
90
    /**
91
     * Get value of cache item
92
     *
93
     * @param  string $key
94
     *
95
     * @return mixed
96
     */
97 715
    public static function get($key)
98
    {
99 715
        if (!$cache = self::getInstance()) {
100 715
            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 715
    public static function set($key, $data, $ttl = self::TTL_NO_EXPIRY, $tags = [])
131
    {
132 715
        if (!$cache = self::getInstance()) {
133 715
            return false;
134
        }
135
136
        $key = self::prepare($key);
137
        try {
138
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->setTags($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
     * @return string
163
     */
164
    public static function prepare($key)
165
    {
166
        return str_replace(['-', '/', '\\', '@', ':'], '_', $key);
167
    }
168
169
    /**
170
     * Clear cache items by tags
171
     *
172
     * @see    TaggablePoolInterface::clearTags()
173
     *
174
     * @return bool
175
     */
176
    public static function clearTags(array $tags)
177
    {
178
        if (self::getInstance() instanceof HierarchicalPoolInterface) {
179
            return self::getInstance()->clearTags($tags);
180
        }
181
        return false;
182
    }
183
}
184