-
Notifications
You must be signed in to change notification settings - Fork 16
/
TYML.php
84 lines (75 loc) · 2.15 KB
/
TYML.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
namespace LireinCore\YMLParser;
/**
* Trait TYML
* @package LireinCore\YMLParser
*/
trait TYML
{
/**
* @param string $name
* @param mixed $value
* @return $this
*/
protected function addField($name, $value)
{
$setter = 'set' . str_replace(['-', '_'], '', $name);
if (method_exists($this, $setter)) {
$this->$setter($value);
}
return $this;
}
/**
* @return array
*/
protected function toArray()
{
$array = [];
foreach ($this as $key => $value) {
if (is_object($value) && method_exists($value, 'getData')) {
$array[$key] = $value->getData();
} elseif (is_array($value)) {
if (!empty($value)) {
$array[$key] = $this->getArray($value);
}
} else {
$getter = 'get' . $key;
if (method_exists($this, $getter)) {
$getValue = $this->$getter();
if ($getValue !== null) {
$array[$key] = $getValue;
}
} elseif ($value !== null) {
$array[$key] = $value;
}
}
}
return $array;
}
/**
* @param array $value
* @return array
*/
protected function getArray($value)
{
$subArray = [];
foreach ($value as $subKey => $subValue) {
if (is_object($subValue) && method_exists($subValue, 'getData')) {
$subArray[$subKey] = $subValue->getData();
} elseif (is_array($subValue)) {
$subArray[$subKey] = $this->getArray($subValue);
} else {
$getter = 'get' . $subKey;
if (method_exists($this, $getter)) {
$getValue = $this->$getter();
if ($getValue !== null) {
$subArray[$subKey] = $getValue;
}
} elseif ($subValue !== null) {
$subArray[$subKey] = $subValue;
}
}
}
return $subArray;
}
}