Passed
Pull Request — master (#212)
by
unknown
03:32 queued 48s
created

ApcuStore::getActualCacheKey()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 9
ccs 0
cts 5
cp 0
crap 6
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
    /**
12
     * {@inheritDoc}
13
     */
14
    public function get(string $key, bool $withExpired = false)
15
    {
16
        $contents = apcu_fetch($this->getActualCacheKey($key));
17
18
        if ( ! $contents) {
19
            return null;
20
        }
21
22
        if ($withExpired) {
23
            return $contents ?: null;
24
        }
25
26
        $isExpired = Carbon::parse($contents['expires_at'])->lt(Carbon::now());
27
28
        return $isExpired ? null : $contents;
29
    }
30
31
    /**
32
     * {@inheritDoc}
33
     */
34
    public function set(string $key, $value)
35
    {
36
        $contents = $this->get($key) ?? [];
37
38
        if (\is_array($value)) {
39
            $contents = $value + $contents;
40
        } else {
41
            $contents[] = $value;
42
        }
43
44
        return apcu_store($this->getActualCacheKey($key), $contents, $this->getTtl());
45
    }
46
47
    /**
48
     * {@inheritDoc}
49
     */
50
    public function delete(string $key): bool
51
    {
52
        return true === apcu_delete($this->getActualCacheKey($key));
53
    }
54
55
    /**
56
     * {@inheritDoc}
57
     */
58
    public function keys(): array
59
    {
60
        $iterator = new APCUIterator('/^' . preg_quote($this->getPrefix()) . '.*$/', APC_ITER_KEY);
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