Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
dto.php
1<?php
2
4
5abstract class Dto
6{
10 public function __construct(array $data = [])
11 {
12 $this->initComplexProperties($data);
13 foreach ($data as $key => $value)
14 {
15 if($this->checkConstructException($key, $value))
16 {
17 continue;
18 }
19 if (property_exists($this, $key))
20 {
21 $this->$key = $value;
22 }
23 }
24 }
25
31 protected function checkConstructException($key, $value): bool
32 {
33 return false;
34 }
35
40 public function toArray(bool $filterEmptyValue = false)
41 {
42 return $this->prepareValue($this, $filterEmptyValue);
43 }
44
50 protected function prepareValue($value, bool $filterEmptyValue)
51 {
52 if (is_scalar($value))
53 {
54 return $value;
55 }
56
57 if (is_array($value) || is_object($value))
58 {
59 $result = [];
60 foreach ($value as $index => $item)
61 {
62 if ($filterEmptyValue && $item === null)
63 {
64 continue;
65 }
66 if ($this->checkPrepareToArrayException($index, $item))
67 {
68 continue;
69 }
70 $result[$index] = $this->prepareValue($item, $filterEmptyValue);
71 }
72 return $result;
73 }
74 }
75
81 protected function checkPrepareToArrayException($key, $value): bool
82 {
83 return false;
84 }
85
90 private function initComplexProperties(array &$data)
91 {
92 $map = $this->getComplexPropertyMap();
93 foreach ($map as $key => $item)
94 {
95 if (!empty($item['isArray']) && !empty($data[$key]) && is_array($data[$key]))
96 {
97 $this->$key = [];
98 foreach ($data[$key] as $property)
99 {
100 $this->$key[] = $this->prepareComplexProperty(
101 $property,
102 $item['class'],
103 $item['isMandatory'] ?? false
104 );
105 }
106 }
107 elseif (empty($data[$key]))
108 {
109 $this->$key = null;
110 }
111 else
112 {
113 $this->$key = $this->prepareComplexProperty(
114 $data[$key],
115 $item['class'],
116 $item['isMandatory'] ?? false
117 );
118 }
119 unset($data[$key]);
120 }
121 }
122
126 protected function getComplexPropertyMap(): array
127 {
128 return [];
129 }
130
137 private function prepareComplexProperty(array $data, $className, $isMandatory = false)
138 {
139 if ($isMandatory)
140 {
141 return new $className($data);
142 }
143 else
144 {
145 return new $className($data ?? []);
146 }
147 }
148}
prepareValue($value, bool $filterEmptyValue)
Definition dto.php:50
checkConstructException($key, $value)
Definition dto.php:31
toArray(bool $filterEmptyValue=false)
Definition dto.php:40
checkPrepareToArrayException($key, $value)
Definition dto.php:81
__construct(array $data=[])
Definition dto.php:10