Completed
Push — master ( 9ffd04...0bd2ec )
by Vladimir
04:28 queued 01:48
created

FilesystemAdapter::get()   A

Complexity

Conditions 3
Paths 5

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 9
nc 5
nop 2
dl 0
loc 15
ccs 7
cts 7
cp 1
crap 3
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace FondBot\Cache\Adapters;
6
7
use JsonSerializable;
8
use FondBot\Cache\Adapter;
9
use League\Flysystem\Filesystem;
10
use League\Flysystem\FileNotFoundException;
11
12
class FilesystemAdapter extends Adapter
13
{
14
    private $filesystem;
15
16 3
    public function __construct(Filesystem $filesystem)
17
    {
18 3
        $this->filesystem = $filesystem;
19 3
    }
20
21
    /**
22
     * Retrieve an item from the cache by key.
23
     *
24
     * @param string $key
25
     * @param mixed  $default
26
     *
27
     * @return mixed
28
     */
29 1
    public function get(string $key, $default = null)
30
    {
31
        try {
32 1
            $contents = $this->filesystem->read($this->key($key));
33 1
            $json = json_decode($contents, true);
34
35 1
            if (json_last_error() === JSON_ERROR_NONE) {
36
                return $json;
37
            }
38
39 1
            return $contents;
40 1
        } catch (FileNotFoundException $exception) {
41 1
            return $default;
42
        }
43
    }
44
45
    /**
46
     * Store an item in the cache.
47
     *
48
     * @param string $key
49
     * @param mixed  $value
50
     */
51 1
    public function store(string $key, $value): void
52
    {
53 1
        if ($value instanceof JsonSerializable) {
0 ignored issues
show
Bug introduced by
The class JsonSerializable does not exist. Is this class maybe located in a folder that is not analyzed, or in a newer version of your dependencies than listed in your composer.lock/composer.json?
Loading history...
54 1
            $value = json_encode($value->jsonSerialize());
55
        } else {
56 1
            $value = json_encode($value);
57
        }
58
59 1
        $this->filesystem->put($this->key($key), $value);
60 1
    }
61
62
    /**
63
     * Remove an item from the cache.
64
     *
65
     * @param string $key
66
     */
67 1
    public function forget(string $key): void
68
    {
69
        try {
70 1
            $this->filesystem->delete($this->key($key));
71
        } catch (FileNotFoundException $exception) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
72
        }
73 1
    }
74
75 3
    private function key(string $key): string
76
    {
77 3
        return md5($key);
78
    }
79
}
80