Completed
Push — master ( 260504...c2ab20 )
by Alex
18s queued 11s
created

ModelSerialiser::reset()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
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