Completed
Push — master ( c0fca1...34db81 )
by Maxim
02:36
created

Cache::key()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 1
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
    /**
11
     * @var CacheService
12
     */
13
    protected static $cacheService;
14
15
    /**
16
     * @param string|array $key
17
     *
18
     * @return mixed|null
19
     * @throws \Psr\Cache\InvalidArgumentException
20
     * @throws \RuntimeException
21
     */
22
    public static function get($key)
23
    {
24
        $item = self::getCacheService()->user()->getItem(self::key($key));
25
        if ($item->isHit()) {
26
            return $item->get();
27
        }
28
        return null;
29
    }
30
31
    /**
32
     * @param string|array $key
33
     * @param $value
34
     * @param int|null $ttl
35
     * @param array $tags
36
     *
37
     * @throws \RuntimeException
38
     * @throws \Psr\Cache\InvalidArgumentException
39
     * @throws \Symfony\Component\Cache\Exception\InvalidArgumentException
40
     */
41
    public static function set($key, $value, int $ttl = null, array $tags = [])
42
    {
43
        $cache = self::getCacheService()->user();
44
        $item = $cache->getItem(self::key($key));
45
        $item->set($value);
46
        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...
47
            $item->expiresAfter($ttl);
48
        }
49
        if ($tags && $item instanceof CacheItem) {
0 ignored issues
show
introduced by
The condition $tags && $item instanceo...mponent\Cache\CacheItem can never be true.
Loading history...
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...
50
            $item->tag($tags);
51
        }
52
        self::getCacheService()->user()->save($item);
53
    }
54
55
    /**
56
     * @param string|array $key
57
     * @param \Closure $closure
58
     * @param int|null $ttl
59
     * @param array $tags
60
     *
61
     * @return mixed
62
     * @throws \Symfony\Component\Cache\Exception\InvalidArgumentException
63
     * @throws \Psr\Cache\InvalidArgumentException
64
     * @throws \RuntimeException
65
     */
66
    public static function getOrSet($key, \Closure $closure, int $ttl = null, array $tags = [])
67
    {
68
        $item = self::getCacheService()->user()->getItem(self::key($key));
69
        if ($item->isHit()) {
70
            return $item->get();
71
        }
72
73
        $result = $closure();
74
        $item->set($result);
75
        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...
76
            $item->expiresAfter($ttl);
77
        }
78
        if ($tags && $item instanceof CacheItem) {
0 ignored issues
show
introduced by
The condition $tags && $item instanceo...mponent\Cache\CacheItem can never be true.
Loading history...
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...
79
            $item->tag($tags);
80
        }
81
        self::getCacheService()->user()->save($item);
82
        return $result;
83
    }
84
85
    /**
86
     * @param string|array $key
87
     *
88
     * @throws \RuntimeException
89
     * @throws \Psr\Cache\InvalidArgumentException
90
     */
91
    public static function invalidate($key)
92
    {
93
        self::getCacheService()->user()->deleteItem(self::key($key));
94
    }
95
96
    /**
97
     * @param array $tags
98
     *
99
     * @throws \RuntimeException
100
     * @throws \Psr\Cache\InvalidArgumentException
101
     */
102
    public static function invalidateTags(array $tags)
103
    {
104
        $cache = self::getCacheService()->user();
105
        if ($cache instanceof TagAwareAdapterInterface) {
106
            $cache->invalidateTags($tags);
107
        }
108
    }
109
110
    /**
111
     * @throws \RuntimeException
112
     */
113
    public static function clear()
114
    {
115
        self::getCacheService()->user()->clear();
116
    }
117
118
    /**
119
     * @param string|array $key
120
     * @param int|null $ttl
121
     * @param array $tags
122
     *
123
     * @return null|HtmlCache
124
     * @throws \Psr\Cache\InvalidArgumentException
125
     * @throws \RuntimeException
126
     */
127
    public static function html($key, int $ttl = null, array $tags = [])
128
    {
129
        if ($content = self::get($key)) {
130
            echo $content;
131
            return null;
132
        }
133
134
        ob_start();
135
        return new HtmlCache(self::getCacheService(), self::key($key), $ttl, $tags);
136
    }
137
138
    /**
139
     * Create PSR-6 valid key
140
     * @param string|array $key
141
     *
142
     * @return string
143
     */
144
    public static function key($key): string
145
    {
146
        if (!\is_string($key)) {
147
            $key = \json_encode($key);
148
        }
149
        return \preg_replace('/[\W]/', '_', $key);
150
    }
151
152
    /**
153
     * @param CacheService $service
154
     */
155
    public static function setCacheService(CacheService $service)
156
    {
157
        self::$cacheService = $service;
158
    }
159
160
    /**
161
     * @return CacheService
162
     * @throws \RuntimeException
163
     */
164
    protected static function getCacheService(): CacheService
165
    {
166
        if (!self::$cacheService) {
167
            throw new \RuntimeException('CacheService is not defined');
168
        }
169
        return self::$cacheService;
170
    }
171
}
172