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
|
|
|
|