Basic::exists()   A
last analyzed

Complexity

Conditions 2
Paths 3

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

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