Completed
Pull Request — master (#382)
by Anton
05:33
created

Cache::set()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 9.488

Importance

Changes 0
Metric Value
cc 4
eloc 10
nc 5
nop 4
dl 0
loc 19
ccs 3
cts 10
cp 0.3
crap 9.488
rs 9.2
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
/**
10
 * @namespace
11
 */
12
namespace Bluz\Proxy;
13
14
use Bluz\Common\Exception\ComponentException;
15
use Bluz\Common\Singleton;
16
use Cache\Adapter\Common\CacheItem as Item;
17
use Psr\Cache\CacheItemPoolInterface as Instance;
18
19
/**
20
 * Proxy to Cache
21
 *
22
 * Example of usage
23
 *     use Bluz\Proxy\Cache;
24
 *
25
 *     if (!Cache::hasItem('some unique id')) {
26
 *          $result = 2*2;
27
 *          $item = Cache::getItem('some unique id');
28
 *          $item->set($result);
29
 *          Cache::save($item);
30
 *     }
31
 *
32
 * @package  Bluz\Proxy
33
 * @author   Anton Shevchuk
34
 *
35
 * @method   static Instance getInstance()
36
 *
37
 * @method   static Item getItem($key)
38
 * @see      Instance::getItem()
39
 *
40
 * @method   static array|\Traversable getItems(array $keys = array())
41
 * @see      Instance::getItems()
42
 *
43
 * @method   static bool hasItem($key)
44
 * @see      Instance::hasItem()
45
 *
46
 * @method   static bool deleteItem($key)
47
 * @see      Instance::deleteItem()
48
 *
49
 * @method   static bool deleteItems(array $keys)
50
 * @see      Instance::deleteItems()
51
 *
52
 * @method   static bool save(Item $item)
53
 * @see      Instance::save()
54
 *
55
 * @method   static bool clear()
56
 * @see      Instance::clear()
57
 *
58
 * @method   static bool clearTags(array $tags)
59
 * @see      TaggablePoolInterface::clearTags()
60
 */
61
class Cache
62
{
63
    use Singleton;
64
65
    const TTL_NO_EXPIRY = 0;
66
67
    /**
68
     * @var array
69
     */
70
    protected static $pools = [];
71
72
    /**
73
     * Handle dynamic, static calls to the object.
74
     *
75
     * @param  string $method
76
     * @param  array $args
77
     * @return mixed
78
     * @throws ComponentException
79
     */
80
    public static function __callStatic($method, $args)
81
    {
82
        if (false === static::getInstance()) {
83
            throw new ComponentException(
84
                "Class `Proxy\\Cache` is disabled, please use safe-methods.\n".
85
                "For more information read documentation at https://github.com/bluzphp/framework/wiki/Cache"
86
            );
87
        }
88
89
        return static::getInstance()->$method(...$args);
90
    }
91
92
93
    /**
94
     * Init cache instance
95
     *
96
     * @return Instance|false
97
     * @throws ComponentException
98
     */
99
    protected static function initInstance()
100
    {
101
        $adapter = Config::getData('cache', 'adapter');
102
        return self::getAdapter($adapter);
103
    }
104
105
    /**
106
     * Get Cache Adapter
107
     *
108
     * @param string $adapter
109
     * @return Instance|false
110
     * @throws ComponentException
111
     */
112
    public static function getAdapter($adapter)
113
    {
114
        $config = Config::getData('cache');
115
116
        if ($config && $adapter && isset($config['enabled']) && $config['enabled']) {
117
            if (!isset($config['pools'][$adapter])) {
118
                throw new ComponentException("Class `Proxy\\Cache` required configuration for `$adapter` adapter");
119
            } else {
120
                if (!isset(static::$pools[$adapter])) {
121
                    static::$pools[$adapter] = $config['pools'][$adapter]();
122
                }
123
                return static::$pools[$adapter];
124
            }
125
        }
126
        return false;
127
    }
128
129
    /**
130
     * Get value of cache item
131
     *
132
     * @param string $key
133
     * @return mixed
134
     */
135 626
    public static function get($key)
136
    {
137 626
        if (!self::getInstance()) {
138 626
            return false;
139
        }
140
141
        if (self::hasItem($key)) {
142
            $item = self::getItem($key);
143
            if ($item->isHit()) {
144
                return $item->get();
145
            }
146
        }
147
        return false;
148
    }
149
150
    /**
151
     * Set value of cache item
152
     *
153
     * @param string $key
154
     * @param mixed $data
155
     * @param int $ttl
156
     * @param array $tags
157
     * @return bool
158
     */
159 626
    public static function set($key, $data, $ttl = self::TTL_NO_EXPIRY, $tags = [])
160
    {
161 626
        if (!self::getInstance()) {
162 626
            return false;
163
        }
164
165
        $item = self::getItem($key);
166
        $item->set($data);
167
168
        if (self::TTL_NO_EXPIRY !== $ttl) {
169
            $item->expiresAfter($ttl);
170
        }
171
172
        if (!empty($tags)) {
173
            $item->setTags($tags);
174
        }
175
176
        return self::save($item);
177
    }
178
179
    /**
180
     * Delete cache item
181
     *
182
     * @param string $key
183
     * @return bool
184
     */
185
    public static function delete($key)
186
    {
187
        if (!self::getInstance()) {
188
            return false;
189
        }
190
191
        return self::deleteItem($key);
192
    }
193
194
    /**
195
     * Prepare key
196
     *
197
     * @return string
198
     */
199 626
    public static function prepare($key)
200
    {
201 626
        return str_replace(['-', '/'], '_', $key);
202
    }
203
}
204