1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace ComposerJson; |
4
|
|
|
|
5
|
|
|
use ComposerJson\Schemas\Classmap; |
6
|
|
|
use ComposerJson\Schemas\Files; |
7
|
|
|
use ComposerJson\Schemas\Psr0; |
8
|
|
|
use ComposerJson\Schemas\Psr4; |
9
|
|
|
use InvalidArgumentException; |
10
|
|
|
|
11
|
|
|
abstract class Model implements ModelInterface |
12
|
|
|
{ |
13
|
|
|
use Helper; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Convert model to array |
17
|
|
|
* |
18
|
|
|
* @return array |
19
|
|
|
*/ |
20
|
|
|
public function toArray(): array |
21
|
|
|
{ |
22
|
|
|
$result = []; |
23
|
|
|
|
24
|
|
|
$items = get_object_vars($this); |
25
|
|
|
foreach ($items as $key => $item) { |
26
|
|
|
if (is_array($item)) { |
27
|
|
|
foreach ($item as $subKey => $subItem) { |
28
|
|
|
if ($subItem instanceof ModelInterface) { |
29
|
|
|
|
30
|
|
|
switch (get_class($subItem)) { |
31
|
|
|
case Psr0::class: |
32
|
|
|
$subKey = 'psr-0'; |
33
|
|
|
break; |
34
|
|
|
case Psr4::class: |
35
|
|
|
$subKey = 'psr-4'; |
36
|
|
|
break; |
37
|
|
|
case Classmap::class: |
38
|
|
|
$subKey = 'classmap'; |
39
|
|
|
break; |
40
|
|
|
case Files::class: |
41
|
|
|
$subKey = 'files'; |
42
|
|
|
break; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
$result[$this->normalize($key)][$subKey] = $subItem->toArray(); |
46
|
|
|
} else { |
47
|
|
|
$result[$this->normalize($key)][$subKey] = $subItem; |
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
} elseif ($item instanceof ModelInterface) { |
51
|
|
|
$result[$this->normalize($key)] = $item->toArray(); |
52
|
|
|
} elseif (!empty($item)) { |
53
|
|
|
$result[$this->normalize($key)] = $item; |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
return $result; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* @param string $name |
62
|
|
|
* @param mixed $value |
63
|
|
|
* |
64
|
|
|
* @throws \InvalidArgumentException |
65
|
|
|
*/ |
66
|
|
|
public function __set(string $name, $value) |
67
|
|
|
{ |
68
|
|
|
if (property_exists($this, $name)) { |
69
|
|
|
$this->$name = $value; |
70
|
|
|
} else { |
71
|
|
|
throw new InvalidArgumentException('Property "' . $name . '" does not in list [' . implode(',', array_keys(get_class_vars(get_class($this)))) . ']'); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* @param string $name |
77
|
|
|
* |
78
|
|
|
* @return mixed|null |
79
|
|
|
*/ |
80
|
|
|
public function __get(string $name) |
81
|
|
|
{ |
82
|
|
|
if (isset($this->$name)) { |
83
|
|
|
return $this->$name; |
84
|
|
|
} |
85
|
|
|
return null; |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
/** |
89
|
|
|
* @param string $name |
90
|
|
|
* |
91
|
|
|
* @return bool |
92
|
|
|
*/ |
93
|
|
|
public function __isset(string $name): bool |
94
|
|
|
{ |
95
|
|
|
return !empty($this->$name); |
96
|
|
|
} |
97
|
|
|
} |
98
|
|
|
|