Cache::clear()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 0
1
<?php
2
3
namespace WebComplete\core\utils\cache;
4
5
use Symfony\Component\Cache\Adapter\TagAwareAdapterInterface;
6
use Symfony\Component\Cache\CacheItem;
7
8
class Cache
9
{
10
    const TTL_1MIN  = 60;
11
    const TTL_5MIN  = 300;
12
    const TTL_10MIN = 600;
13
    const TTL_HOUR  = 3600;
14
    const TTL_DAY   = 86400;
15
    const TTL_WEEK  = 604800;
16
    const TTL_MONTH = 2592000;
17
18
    /**
19
     * @var CacheService
20
     */
21
    protected static $cacheService;
22
23
    /**
24
     * @param string|array $key
25
     *
26
     * @return mixed|null
27
     * @throws \Psr\Cache\InvalidArgumentException
28
     * @throws \RuntimeException
29
     */
30
    public static function get($key)
31
    {
32
        $item = self::getCacheService()->user()->getItem(self::key($key));
33
        if ($item->isHit()) {
34
            return $item->get();
35
        }
36
        return null;
37
    }
38
39
    /**
40
     * @param string|array $key
41
     * @param $value
42
     * @param int|null $ttl
43
     * @param array $tags
44
     *
45
     * @throws \RuntimeException
46
     * @throws \Psr\Cache\InvalidArgumentException
47
     * @throws \Symfony\Component\Cache\Exception\InvalidArgumentException
48
     */
49
    public static function set($key, $value, int $ttl = null, array $tags = [])
50
    {
51
        $cache = self::getCacheService()->user();
52
        $item = $cache->getItem(self::key($key));
53
        $item->set($value);
54
        if ($ttl) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $ttl of type null|integer is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
55
            $item->expiresAfter($ttl);
56
        }
57
        if ($tags && $item instanceof CacheItem) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $tags of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
58
            $item->tag($tags);
59
        }
60
        self::getCacheService()->user()->save($item);
61
    }
62
63
    /**
64
     * @param string|array $key
65
     * @param \Closure $closure
66
     * @param int|null $ttl
67
     * @param array $tags
68
     *
69
     * @return mixed
70
     * @throws \Symfony\Component\Cache\Exception\InvalidArgumentException
71
     * @throws \Psr\Cache\InvalidArgumentException
72
     * @throws \RuntimeException
73
     */
74
    public static function getOrSet($key, \Closure $closure, int $ttl = null, array $tags = [])
75
    {
76
        $item = self::getCacheService()->user()->getItem(self::key($key));
77
        if ($item->isHit()) {
78
            return $item->get();
79
        }
80
81
        $result = $closure();
82
        $item->set($result);
83
        if ($ttl) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $ttl of type null|integer is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
84
            $item->expiresAfter($ttl);
85
        }
86
        if ($tags && $item instanceof CacheItem) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $tags of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
87
            $item->tag($tags);
88
        }
89
        self::getCacheService()->user()->save($item);
90
        return $result;
91
    }
92
93
    /**
94
     * @param string|array $key
95
     *
96
     * @throws \RuntimeException
97
     * @throws \Psr\Cache\InvalidArgumentException
98
     */
99
    public static function invalidate($key)
100
    {
101
        self::getCacheService()->user()->deleteItem(self::key($key));
102
    }
103
104
    /**
105
     * @param array $tags
106
     *
107
     * @throws \RuntimeException
108
     * @throws \Psr\Cache\InvalidArgumentException
109
     */
110
    public static function invalidateTags(array $tags)
111
    {
112
        $cache = self::getCacheService()->user();
113
        if ($cache instanceof TagAwareAdapterInterface) {
114
            $cache->invalidateTags($tags);
115
        }
116
    }
117
118
    /**
119
     * @throws \RuntimeException
120
     */
121
    public static function clear()
122
    {
123
        self::getCacheService()->user()->clear();
124
    }
125
126
    /**
127
     * @param string|array $key
128
     * @param int|null $ttl
129
     * @param array $tags
130
     *
131
     * @return null|HtmlCache
132
     * @throws \Psr\Cache\InvalidArgumentException
133
     * @throws \RuntimeException
134
     */
135
    public static function html($key, int $ttl = null, array $tags = [])
136
    {
137
        if ($content = self::get($key)) {
138
            echo $content;
139
            return null;
140
        }
141
142
        ob_start();
143
        return new HtmlCache(self::getCacheService(), self::key($key), $ttl, $tags);
144
    }
145
146
    /**
147
     * Create PSR-6 valid key
148
     * @param string|array $key
149
     *
150
     * @return string
151
     */
152
    public static function key($key): string
153
    {
154
        if (!\is_string($key)) {
155
            $key = \json_encode($key);
156
        }
157
        return \preg_replace('/[\W]/', '_', $key);
158
    }
159
160
    /**
161
     * @param CacheService $service
162
     */
163
    public static function setCacheService(CacheService $service)
164
    {
165
        self::$cacheService = $service;
166
    }
167
168
    /**
169
     * @return CacheService
170
     * @throws \RuntimeException
171
     */
172
    protected static function getCacheService(): CacheService
173
    {
174
        if (!self::$cacheService) {
175
            throw new \RuntimeException('CacheService is not defined');
176
        }
177
        return self::$cacheService;
178
    }
179
}
180