Passed
Push — master ( 0d9e84...07494d )
by Petr
02:10
created

Basic::init()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 5
c 1
b 0
f 1
nc 1
nop 1
dl 0
loc 7
ccs 6
cts 6
cp 1
crap 1
rs 10
1
<?php
2
3
namespace kalanis\kw_cache\Files;
4
5
6
use kalanis\kw_cache\CacheException;
7
use kalanis\kw_cache\Interfaces\ICache;
8
use kalanis\kw_files\Access\CompositeAdapter;
9
use kalanis\kw_files\FilesException;
10
use kalanis\kw_files\Traits\TToString;
11
use kalanis\kw_paths\ArrayPath;
12
use kalanis\kw_paths\PathsException;
13
use kalanis\kw_paths\Stuff;
14
15
16
/**
17
 * Class Basic
18
 * @package kalanis\kw_cache\Files
19
 * Caching content by files
20
 */
21
class Basic implements ICache
22
{
23
    use TToString;
24
25
    /** @var CompositeAdapter */
26
    protected $cacheStorage = null;
27
    /** @var string[] */
28
    protected $cachePath = [];
29
30 5
    public function __construct(CompositeAdapter $cacheStorage)
31
    {
32 5
        $this->cacheStorage = $cacheStorage;
33 5
    }
34
35 5
    public function init(array $what): void
36
    {
37 5
        $arr = new ArrayPath();
38 5
        $arr->setArray($what);
39 5
        $this->cachePath = array_merge(
40 5
            $arr->getArrayDirectory(),
41 5
            [$arr->getFileName() . ICache::EXT_CACHE]
42
        );
43 5
    }
44
45 3
    public function exists(): bool
46
    {
47
        try {
48 3
            return $this->cacheStorage->exists($this->cachePath);
49 1
        } catch (FilesException | PathsException $ex) {
50 1
            throw new CacheException($ex->getMessage(), $ex->getCode(), $ex);
51
        }
52
    }
53
54 2
    public function set(string $content): bool
55
    {
56
        try {
57 2
            return $this->cacheStorage->saveFile($this->cachePath, $content);
58 1
        } catch (FilesException | PathsException $ex) {
59 1
            throw new CacheException($ex->getMessage(), $ex->getCode(), $ex);
60
        }
61
    }
62
63 2
    public function get(): string
64
    {
65
        try {
66 2
            return $this->exists()
67 2
                ? $this->toString(
68 2
                    Stuff::arrayToPath($this->cachePath),
69 2
                    $this->cacheStorage->readFile($this->cachePath)
70
                )
71 1
                : '';
72 1
        } catch (FilesException | PathsException $ex) {
73 1
            throw new CacheException($ex->getMessage(), $ex->getCode(), $ex);
74
        }
75
    }
76
77 2
    public function clear(): void
78
    {
79
        try {
80 2
            $this->cacheStorage->deleteFile($this->cachePath);
81 1
        } catch (FilesException | PathsException $ex) {
82 1
            throw new CacheException($ex->getMessage(), $ex->getCode(), $ex);
83
        }
84 1
    }
85
}
86