Passed
Push — master ( 6aa1de...4498ca )
by Ankit
02:21
created

ApcuStore::getActualCacheKey()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

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 5
cts 5
cp 1
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
    /**
12
     * {@inheritDoc}
13
     */
14 7
    public function get(string $key, bool $withExpired = false)
15
    {
16 7
        $contents = apcu_fetch($this->getActualCacheKey($key));
17
18 7
        if ( ! $contents) {
19 3
            return null;
20
        }
21
22 6
        if ($withExpired) {
23 1
            return $contents ?: null;
24
        }
25
26 6
        $isExpired = Carbon::parse($contents['expires_at'])->lt(Carbon::now());
27
28 6
        return $isExpired ? null : $contents;
29
    }
30
31
    /**
32
     * {@inheritDoc}
33
     */
34 4
    public function set(string $key, $value)
35
    {
36 4
        $contents = $this->get($key) ?? [];
37
38 4
        if (\is_array($value)) {
39 4
            $contents = $value + $contents;
40
        } else {
41 1
            $contents[] = $value;
42
        }
43
44 4
        return apcu_store($this->getActualCacheKey($key), $contents, $this->getTtl());
45
    }
46
47
    /**
48
     * {@inheritDoc}
49
     */
50 2
    public function delete(string $key): bool
51
    {
52 2
        return true === apcu_delete($this->getActualCacheKey($key));
53
    }
54
55
    /**
56
     * {@inheritDoc}
57
     */
58 1
    public function keys(): array
59
    {
60 1
        $iterator = new APCUIterator('/^' . preg_quote($this->getPrefix()) . '.*$/', APC_ITER_KEY);
61 1
        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 7
    protected function getActualCacheKey(string $key): string
72
    {
73 7
        $prefix = $this->getPrefix();
74
75 7
        if (false === strpos($key, $prefix)) {
76 7
            $key = $prefix . $key;
77
        }
78
79 7
        return $key;
80
    }
81
}
82