Completed
Push — master ( 32d092...a9f2d5 )
by Lars
02:11
created

AdapterFileSimple::get()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 37

Duplication

Lines 7
Ratio 18.92 %

Code Coverage

Tests 16
CRAP Score 7.0671

Importance

Changes 0
Metric Value
dl 7
loc 37
ccs 16
cts 18
cp 0.8889
rs 8.3946
c 0
b 0
f 0
cc 7
nc 5
nop 1
crap 7.0671
1
<?php
2
3
declare(strict_types=1);
4
5
namespace voku\cache;
6
7
/**
8
 * AdapterFileSimple: File-adapter (simple)
9
 */
10
class AdapterFileSimple extends AdapterFileAbstract
11
{
12
    const CACHE_FILE_PREFIX = '__simple_';
13
14 23
    protected function getContext()
15
    {
16 23
        static $CONTEXT_CACHE = null;
17
18 23
        if ($CONTEXT_CACHE === null) {
19 2
            $CONTEXT_CACHE = \stream_context_create(
20
                [
21 2
                    'http' => [
22
                        'timeout' => 2,
23
                    ],
24
                ]
25
            );
26
        }
27
28 23
        return $CONTEXT_CACHE;
29
    }
30
31
    /**
32
     * {@inheritdoc}
33
     */
34 6
    public function get(string $key)
35
    {
36 6
        $path = $this->getFileName($key);
37
38 View Code Duplication
        if (
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
39 6
            \file_exists($path) === false
40
            ||
41 6
            \filesize($path) === 0
42
        ) {
43 1
            return null;
44
        }
45
46
        // init
47 6
        $string = \file_get_contents(
48 6
            $path,
49 6
            false,
50 6
            $this->getContext()
51
        );
52
53 6
        if (!$string) {
54
            return null;
55
        }
56
57 6
        $data = $this->serializer->unserialize($string);
58
59 6
        if (!$data || !$this->validateDataFromCache($data)) {
60
            return null;
61
        }
62
63 6
        if ($this->ttlHasExpired($data['ttl']) === true) {
64 2
            $this->remove($key);
65
66 2
            return null;
67
        }
68
69 5
        return $data['value'];
70
    }
71
72
    /**
73
     * {@inheritdoc}
74
     */
75 6
    public function setExpired(string $key, $value, int $ttl = 0): bool
76
    {
77 6
        return (bool) \file_put_contents(
78 6
            $this->getFileName($key),
79 6
            $this->serializer->serialize(
80
                [
81 6
                    'value' => $value,
82 6
                    'ttl'   => $ttl ? $ttl + \time() : 0,
83
                ]
84
            ),
85 6
            0,
86 6
            $this->getContext()
87
        );
88
    }
89
}
90