1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Isswp101\Persimmon\Repository; |
4
|
|
|
|
5
|
|
|
use Isswp101\Persimmon\Collection\ICollection; |
6
|
|
|
use Isswp101\Persimmon\Contracts\Storable; |
7
|
|
|
use Isswp101\Persimmon\Exceptions\ClassTypeErrorException; |
8
|
|
|
use Isswp101\Persimmon\Exceptions\MethodNotImplementedException; |
9
|
|
|
use Isswp101\Persimmon\QueryBuilder\IQueryBuilder; |
10
|
|
|
|
11
|
|
|
class RuntimeCacheRepository implements IRepository |
12
|
|
|
{ |
13
|
|
|
private $data = []; |
14
|
|
|
|
15
|
|
|
private function getHash(string $id, string $class): string |
16
|
|
|
{ |
17
|
|
|
return $class . '@' . $id; |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
private function getHashByModel(Storable $model): string |
21
|
|
|
{ |
22
|
|
|
return $this->getHash($model->getPrimaryKey(), get_class($model)); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
public function instantiate(string $class): Storable |
26
|
|
|
{ |
27
|
|
|
$instance = new $class; |
28
|
|
|
if (!$instance instanceof Storable) { |
29
|
|
|
throw new ClassTypeErrorException(Storable::class); |
30
|
|
|
} |
31
|
|
|
return $instance; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function find(string $id, string $class, array $columns = []): ?Storable |
35
|
|
|
{ |
36
|
|
|
$hash = $this->getHash($id, $class); |
37
|
|
|
$data = $this->data[$hash] ?? []; |
38
|
|
|
if (!$data) { |
39
|
|
|
return null; |
40
|
|
|
} |
41
|
|
|
$model = $this->instantiate($class); |
42
|
|
|
$model->setPrimaryKey($id); |
43
|
|
|
if ($columns) { |
|
|
|
|
44
|
|
|
$data = array_intersect_key($data, array_flip($columns)); |
45
|
|
|
} |
46
|
|
|
$model->fill($data); |
47
|
|
|
return $model; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
public function all(IQueryBuilder $query, string $class, callable $callback = null): ICollection |
51
|
|
|
{ |
52
|
|
|
throw new MethodNotImplementedException(__METHOD__); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
public function insert(Storable $model): void |
56
|
|
|
{ |
57
|
|
|
$hash = $this->getHashByModel($model); |
58
|
|
|
$this->data[$hash] = $model->toArray(); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
public function update(Storable $model): void |
62
|
|
|
{ |
63
|
|
|
$hash = $this->getHashByModel($model); |
64
|
|
|
$this->data[$hash] = array_merge($this->data[$hash] ?? [], $model->toArray()); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
public function delete(Storable $model): void |
68
|
|
|
{ |
69
|
|
|
$hash = $this->getHashByModel($model); |
70
|
|
|
unset($this->data[$hash]); |
71
|
|
|
} |
72
|
|
|
} |
This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.
Consider making the comparison explicit by using
empty(..)
or! empty(...)
instead.