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