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