1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace AlgoWeb\PODataLaravel\Serialisers; |
6
|
|
|
|
7
|
|
|
use Illuminate\Database\Eloquent\Model; |
8
|
|
|
use POData\Common\InvalidOperationException; |
9
|
|
|
|
10
|
|
|
class ModelSerialiser |
11
|
|
|
{ |
12
|
|
|
// take a supplied Eloquent model with metadata trait and serialise it in bulk. |
13
|
|
|
// Upstream POData implementation has an N+1 lookup problem that interacts badly with how |
14
|
|
|
// Eloquent handles property accesses |
15
|
|
|
|
16
|
|
|
/** @var array[] */ |
17
|
|
|
private static $mutatorCache = []; |
18
|
|
|
/** @var array[] */ |
19
|
|
|
private static $metadataCache = []; |
20
|
|
|
|
21
|
|
|
public function __construct() |
22
|
|
|
{ |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Serialise needed bits of supplied model, taking fast path where possible. |
27
|
|
|
* |
28
|
|
|
* @param Model $model |
29
|
|
|
* |
30
|
|
|
* @return mixed |
31
|
|
|
*/ |
32
|
|
|
public function bulkSerialise(Model $model) |
33
|
|
|
{ |
34
|
|
|
$class = get_class($model); |
35
|
|
|
// dig up metadata |
36
|
|
|
if (!isset(self::$metadataCache[$class])) { |
37
|
|
|
self::$metadataCache[$class] = $model->fetchMetadata(); |
38
|
|
|
} |
39
|
|
|
$meta = self::$metadataCache[$class]; |
40
|
|
|
/** @var string[] $keys */ |
41
|
|
|
$keys = array_keys($meta); |
42
|
|
|
// dig up getter list - we only care about the mutators that end up in metadata |
43
|
|
|
if (!isset(self::$mutatorCache[$class])) { |
44
|
|
|
$getterz = []; |
45
|
|
|
/** @var \DateTime[] $datez */ |
46
|
|
|
$datez = $model->getDates(); |
47
|
|
|
/** @var string[] $castz */ |
48
|
|
|
$castz = $model->retrieveCasts(); |
49
|
|
|
foreach ($keys as $key) { |
50
|
|
|
if ($model->hasGetMutator($key) || in_array($key, $datez) || array_key_exists($key, $castz)) { |
51
|
|
|
$getterz[] = $key; |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
self::$mutatorCache[$class] = $getterz; |
55
|
|
|
} |
56
|
|
|
$getterz = self::$mutatorCache[$class]; |
57
|
|
|
$modelAttrib = $model->getAttributes(); |
58
|
|
|
$result = array_intersect_key($modelAttrib, $meta); |
59
|
|
|
foreach ($keys as $key) { |
60
|
|
|
if (!isset($result[$key])) { |
61
|
|
|
$result[$key] = null; |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
foreach ($getterz as $getter) { |
65
|
|
|
$result[$getter] = $model->{$getter}; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
return $result; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|