-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCache.php
More file actions
89 lines (75 loc) · 2.18 KB
/
Cache.php
File metadata and controls
89 lines (75 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php
namespace Gt\FileCache;
use DateTimeImmutable;
use DateTimeInterface;
use Gt\TypeSafeGetter\CallbackTypeSafeGetter;
use TypeError;
class Cache implements CallbackTypeSafeGetter {
private FileAccess $fileAccess;
public function __construct(
string $path = "cache",
private readonly int $secondsValid = 60 * 60, // 1 hour of validity by default
?FileAccess $fileAccess = null,
) {
if(is_null($fileAccess)) {
$fileAccess = new FileAccess($path);
}
$this->fileAccess = $fileAccess;
}
public function get(
string $name,
callable $callback,
):mixed {
try {
$this->fileAccess->checkValidity($name, $this->secondsValid);
return $this->fileAccess->getData($name);
}
catch(FileNotFoundException|CacheInvalidException) {
$value = $callback();
$this->fileAccess->setData($name, $value);
return $value;
}
}
public function getString(string $name, callable $callback):string {
return (string)$this->get($name, $callback);
}
public function getInt(string $name, callable $callback):int {
return (int)$this->get($name, $callback);
}
public function getFloat(string $name, callable $callback):float {
return (float)$this->get($name, $callback);
}
public function getBool(string $name, callable $callback):bool {
return (bool)$this->get($name, $callback);
}
public function getDateTime(string $name, callable $callback):DateTimeInterface {
$value = $this->get($name, $callback);
if($value instanceof DateTimeInterface) {
return $value;
}
elseif(is_int($value)) {
$dateTime = new DateTimeImmutable();
return $dateTime->setTimestamp($value);
}
return new DateTimeImmutable($value);
}
public function getArray(string $name, callable $callback):array {
$value = $this->get($name, $callback);
if(!is_array($value)) {
throw new TypeError("Value with key '$name' is not an array");
}
return $value;
}
/**
* @template T
* @param class-string<T> $className
* @return T
*/
public function getInstance(string $name, string $className, callable $callback):object {
$value = $this->get($name, $callback);
if(get_class($value) !== $className) {
throw new TypeError("Value is not of type $className");
}
return $value;
}
}