Basic   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 11
eloc 30
c 1
b 0
f 1
dl 0
loc 61
ccs 30
cts 30
cp 1
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 7 1
A __construct() 0 3 1
A set() 0 6 2
A clear() 0 6 2
A exists() 0 6 2
A get() 0 11 3
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
    protected CompositeAdapter $cacheStorage;
26
    /** @var string[] */
27
    protected array $cachePath = [];
28
29 5
    public function __construct(CompositeAdapter $cacheStorage)
30
    {
31 5
        $this->cacheStorage = $cacheStorage;
32 5
    }
33
34 5
    public function init(array $what): void
35
    {
36 5
        $arr = new ArrayPath();
37 5
        $arr->setArray($what);
38 5
        $this->cachePath = array_merge(
39 5
            $arr->getArrayDirectory(),
40 5
            [$arr->getFileName() . ICache::EXT_CACHE]
41
        );
42 5
    }
43
44 3
    public function exists(): bool
45
    {
46
        try {
47 3
            return $this->cacheStorage->exists($this->cachePath);
48 1
        } catch (FilesException | PathsException $ex) {
49 1
            throw new CacheException($ex->getMessage(), $ex->getCode(), $ex);
50
        }
51
    }
52
53 2
    public function set(string $content): bool
54
    {
55
        try {
56 2
            return $this->cacheStorage->saveFile($this->cachePath, $content);
57 1
        } catch (FilesException | PathsException $ex) {
58 1
            throw new CacheException($ex->getMessage(), $ex->getCode(), $ex);
59
        }
60
    }
61
62 2
    public function get(): string
63
    {
64
        try {
65 2
            return $this->exists()
66 2
                ? $this->toString(
67 2
                    Stuff::arrayToPath($this->cachePath),
68 2
                    $this->cacheStorage->readFile($this->cachePath)
69
                )
70 1
                : '';
71 1
        } catch (FilesException | PathsException $ex) {
72 1
            throw new CacheException($ex->getMessage(), $ex->getCode(), $ex);
73
        }
74
    }
75
76 2
    public function clear(): void
77
    {
78
        try {
79 2
            $this->cacheStorage->deleteFile($this->cachePath);
80 1
        } catch (FilesException | PathsException $ex) {
81 1
            throw new CacheException($ex->getMessage(), $ex->getCode(), $ex);
82
        }
83 1
    }
84
}
85