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

ApcuStore   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 19
c 1
b 0
f 0
dl 0
loc 68
ccs 22
cts 22
cp 1
rs 10
wmc 12

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getActualCacheKey() 0 9 2
A keys() 0 4 1
A get() 0 11 5
A delete() 0 3 1
A set() 0 11 3
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