Passed
Pull Request — master (#212)
by Ankit
02:38
created

ApcuStore::keys()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

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 4
ccs 3
cts 3
cp 1
crap 1
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)) ?: null;
17
18 7
        if ($withExpired) {
19 1
            return $contents ?: null;
20
        }
21
22 7
        $isExpired = Carbon::parse($contents['expires_at'])->lt(Carbon::now());
23
24 7
        return $isExpired ? null : $contents;
25
    }
26
27
    /**
28
     * {@inheritDoc}
29
     */
30 4
    public function set(string $key, $value)
31
    {
32 4
        $contents = $this->get($key) ?: [];
33
34 4
        if (\is_array($value)) {
35 4
            $contents = $value + $contents;
36
        } else {
37 1
            array_push($contents, $value);
38
        }
39
40 4
        return apcu_store($this->getActualCacheKey($key), $contents, $this->getTtl());
41
    }
42
43
    /**
44
     * {@inheritDoc}
45
     */
46 2
    public function delete(string $key): bool
47
    {
48 2
        return apcu_delete($this->getActualCacheKey($key));
0 ignored issues
show
Bug Best Practice introduced by
The expression return apcu_delete($this...etActualCacheKey($key)) could return the type string[] which is incompatible with the type-hinted return boolean. Consider adding an additional type-check to rule them out.
Loading history...
49
    }
50
51
    /**
52
     * {@inheritDoc}
53
     */
54 1
    public function keys(): array
55
    {
56 1
        $iterator = new APCUIterator('/^' . preg_quote($this->getPrefix()) . '.*$/', APC_ITER_KEY);
57 1
        return array_column(iterator_to_array($iterator, false), 'key');
58
    }
59
60
    /**
61
     * Get actual cache key with prefix.
62
     *
63
     * @param string $key
64
     *
65
     * @return string
66
     */
67 7
    protected function getActualCacheKey(string $key): string
68
    {
69 7
        $prefix = $this->getPrefix();
70
71 7
        if (false === strpos($key, $prefix)) {
72 7
            $key = $prefix . $key;
73
        }
74
75 7
        return $key;
76
    }
77
}
78