-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJsonFileServerEntry.php
49 lines (39 loc) · 974 Bytes
/
JsonFileServerEntry.php
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
<?php
namespace DevHammed\ServerActions\Concerns;
use Closure;
use Throwable;
use Opis\Closure\SerializableClosure;
use DevHammed\ServerActions\Contracts\ServerEntry;
class JsonFileServerEntry implements ServerEntry
{
protected array $entries;
public function __construct(protected string $file)
{
try {
$this->entries = json_decode(file_get_contents($this->file), true);
} catch (Throwable) {
$this->entries = [];
}
}
public function register(string $name, Closure $callback): void
{
$this->entries[$name] = serialize(
new SerializableClosure($callback),
);
}
public function get(string $name): ?Closure
{
if ( ! array_key_exists($name, $this->entries)) {
return null;
}
$wrapper = unserialize($this->entries[$name]);
if ( ! $wrapper instanceof SerializableClosure) {
return null;
}
return $wrapper->getClosure();
}
public function __destruct()
{
file_put_contents($this->file, json_encode($this->entries));
}
}