ApcuStore::get()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5

Importance

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