Passed
Push — master ( da4e4d...121ad9 )
by Ankit
02:53
created

ApcuStore::keys()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 5
ccs 0
cts 3
cp 0
crap 2
rs 10
1
<?php
2
3
namespace TusPhp\Cache;
4
5
use Carbon\Carbon;
6
use APCUIterator;
7
8
class ApcuStore extends AbstractCache
9
{
10
    /**
11
     * {@inheritDoc}
12
     */
13
    public function get(string $key, bool $withExpired = false)
14
    {
15
        $contents = apcu_fetch($this->getActualCacheKey($key));
16
17
        if ( ! $contents) {
18
            return null;
19
        }
20
21
        if ($withExpired) {
22
            return $contents ?: null;
23
        }
24
25
        $isExpired = Carbon::parse($contents['expires_at'])->lt(Carbon::now());
26
27
        return $isExpired ? null : $contents;
28
    }
29
30
    /**
31
     * {@inheritDoc}
32
     */
33
    public function set(string $key, $value)
34
    {
35
        $contents = $this->get($key) ?? [];
36
37
        if (\is_array($value)) {
38
            $contents = $value + $contents;
39
        } else {
40
            $contents[] = $value;
41
        }
42
43
        return apcu_store($this->getActualCacheKey($key), $contents, $this->getTtl());
44
    }
45
46
    /**
47
     * {@inheritDoc}
48
     */
49
    public function delete(string $key): bool
50
    {
51
        return true === apcu_delete($this->getActualCacheKey($key));
52
    }
53
54
    /**
55
     * {@inheritDoc}
56
     */
57
    public function keys(): array
58
    {
59
        $iterator = new APCUIterator('/^' . preg_quote($this->getPrefix()) . '.*$/', APC_ITER_KEY);
60
61
        return array_column(iterator_to_array($iterator, false), 'key');
62
    }
63
64
    /**
65
     * Get actual cache key with prefix.
66
     *
67
     * @param string $key
68
     *
69
     * @return string
70
     */
71
    protected function getActualCacheKey(string $key): string
72
    {
73
        $prefix = $this->getPrefix();
74
75
        if (false === strpos($key, $prefix)) {
76
            $key = $prefix . $key;
77
        }
78
79
        return $key;
80
    }
81
}
82