Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
dto.php
1<?php
2
4
5class Dto
6{
7 private array $metaFields = [];
8
12 public function __construct(array $data = [])
13 {
14 $this->initComplexProperties($data);
15 foreach ($data as $key => $value)
16 {
17 if($this->checkConstructException($key, $value))
18 {
19 continue;
20 }
21 if (property_exists($this, $key))
22 {
23 $this->$key = $value;
24 }
25 }
26 }
27
33 public function toArray(bool $filterEmptyValue = false)
34 {
35 return $this->prepareValue($this, $filterEmptyValue);
36 }
37
43 protected function prepareValue($value, bool $filterEmptyValue)
44 {
45 if (is_scalar($value))
46 {
47 return $value;
48 }
49
50 if (is_array($value) || is_object($value))
51 {
52 $result = [];
53 foreach ($value as $index => $item)
54 {
55 if ($filterEmptyValue && $item === null)
56 {
57 continue;
58 }
59 if ($this->checkPrepareToArrayException($index, $item))
60 {
61 continue;
62 }
63 $result[$index] = $this->prepareValue($item, $filterEmptyValue);
64 }
65 return $result;
66 }
67 }
68
73 private function initComplexProperties(array &$data)
74 {
75 $map = $this->getComplexPropertyMap();
76 foreach ($map as $key => $item)
77 {
78 if (!empty($item['isArray']) && !empty($data[$key]) && is_array($data[$key]))
79 {
80 $this->$key = [];
81 foreach ($data[$key] as $property)
82 {
83 $this->$key[] = $this->prepareComplexProperty(
84 $property,
85 $item['class'],
86 $item['isMandatory'] ?? false
87 );
88 }
89 }
90 elseif (empty($data[$key]))
91 {
92 $this->$key = null;
93 }
94 else
95 {
96 $this->$key = $this->prepareComplexProperty(
97 $data[$key],
98 $item['class'],
99 $item['isMandatory'] ?? false
100 );
101 }
102 unset($data[$key]);
103 }
104 }
105
109 protected function getComplexPropertyMap(): array
110 {
111 return [];
112 }
113
120 private function prepareComplexProperty(array $data, $className, $isMandatory = false)
121 {
122 if ($isMandatory)
123 {
124 return new $className($data);
125 }
126
127 return new $className($data ?? []);
128 }
129
133 public function getMetaFields(): array
134 {
135 return $this->metaFields;
136 }
137
138 protected function checkConstructException($key, $value): bool
139 {
140 if (strpos($key, '@') !== false)
141 {
142 $this->metaFields[$key] = $value;
143 return true;
144 }
145
146 return false;
147 }
148
149 protected function checkPrepareToArrayException($key, $value): bool
150 {
151 if (strpos($key, 'metaFields') !== false)
152 {
153 return true;
154 }
155 if ($key === 'etag')
156 {
157 return true;
158 }
159
160 return false;
161 }
162}
prepareValue($value, bool $filterEmptyValue)
Definition dto.php:43
toArray(bool $filterEmptyValue=false)
Definition dto.php:33
checkPrepareToArrayException($key, $value)
Definition dto.php:149