TraitEntity::toArray()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
c 1
b 0
f 0
dl 0
loc 11
rs 10
cc 2
nc 2
nop 0
1
<?php
2
namespace Itau\API;
3
4
trait TraitEntity
5
{
6
7
    public function jsonSerialize(): mixed
8
    {
9
        $entity = clone $this;
10
11
        if (method_exists($entity, 'beforeSerialize')) {
12
            $entity->beforeSerialize();
13
        }
14
15
        return $entity->toArray();
16
    }
17
        
18
    /**
19
     *
20
     * @return array
21
     */
22
    public function toArray()
23
    {
24
        $vars = get_object_vars($this);
25
26
        if ($this->hiddenNullValues()) {
27
            return array_filter($vars, function ($value) {
28
                return null !== $value;
29
            });
30
        }
31
32
        return $vars;
33
    }
34
35
    /**
36
     *
37
     * @return false|string
38
     */
39
    public function toJSON($hiddenNull = true)
40
    {
41
        if ($hiddenNull) {
42
            return json_encode($this);
43
        }
44
45
        return json_encode(get_object_vars($this));
46
    }
47
48
    public function populateByArray(array $body, array $blockFields = [])
49
    {
50
        foreach ($body as $prop => $value) {
51
            if (property_exists($this, $prop) && null !== $value && !in_array($prop, $blockFields)) {
52
                $this->{$prop} = $value;
53
            }
54
        }
55
        
56
        return $this;
57
    }
58
59
    private function hiddenNullValues(): bool
60
    {
61
        return true;
62
    }
63
}