Completed
Push — master ( 3b6465...96f4b7 )
by compolom
25s queued 11s
created

Model::normalize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace ComposerJson;
4
5
use InvalidArgumentException;
6
7
abstract class Model implements ModelInterface
8
{
9
    use Helper;
10
11
    /**
12
     * Convert model to array
13
     *
14
     * @return array
15
     */
16
    public function toArray(): array
17
    {
18
        $result = [];
19
20
        $items = get_object_vars($this);
21
        foreach ($items as $key => $item) {
22
            if (is_array($item)) {
23
                foreach ($item as $subKey => $subItem) {
24
                    if ($subItem instanceof ModelInterface) {
25
                        $result[$this->normalize($key)][$subKey] = $subItem->toArray();
26
                    } else {
27
                        $result[$this->normalize($key)][$subKey] = $subItem;
28
                    }
29
                }
30
            } elseif ($item instanceof ModelInterface) {
31
                $result[$this->normalize($key)] = $item->toArray();
32
            } elseif (!empty($item)) {
33
                $result[$this->normalize($key)] = $item;
34
            }
35
        }
36
37
        return $result;
38
    }
39
40
    /**
41
     * @param string $name
42
     * @param mixed  $value
43
     *
44
     * @throws \InvalidArgumentException
45
     */
46
    public function __set(string $name, $value)
47
    {
48
        if (property_exists($this, $name)) {
49
            $this->$name = $value;
50
        } else {
51
            throw new InvalidArgumentException('Property "' . $name . '" does not in list [' . implode(',', array_keys(get_class_vars(get_class($this)))) . ']');
52
        }
53
    }
54
55
    /**
56
     * @param string $name
57
     *
58
     * @return mixed|null
59
     */
60
    public function __get(string $name)
61
    {
62
        if (isset($this->$name)) {
63
            return $this->$name;
64
        }
65
        return null;
66
    }
67
68
    /**
69
     * @param string $name
70
     *
71
     * @return bool
72
     */
73
    public function __isset(string $name): bool
74
    {
75
        return !empty($this->$name);
76
    }
77
}
78