Debian Codegraph @

vendor/ipl/orm/src/Hydrator.php

raw
1 <?php
2
3 namespace ipl\Orm;
4
5 use ipl\Orm\Exception\InvalidRelationException;
6 use InvalidArgumentException;
7
8 /**
9 * Hydrates raw database rows into concrete model instances.
10 */
11 class Hydrator
12 {
13 /** @var array Additional hydration rules for the model's relations */
14 protected array $hydrators = [];
15
16 /** @var array<string, array<string, bool>> Map of columns to referencing paths */
17 protected array $columnToTargetMap = [];
18
19 /** @var Query The query the hydration rules are for */
20 protected Query $query;
21
22 /**
23 * Create a new Hydrator
24 *
25 * @param Query $query
26 */
27 public function __construct(Query $query)
28 {
29 $this->query = $query;
30 }
31
32 /**
33 * Add a hydration rule
34 *
35 * @param string $path Model path
36 *
37 * @return $this
38 *
39 * @throws InvalidArgumentException If a hydrator for the given path already exists
40 */
41 public function add(string $path): static
42 {
43 if (isset($this->hydrators[$path])) {
44 throw new InvalidArgumentException("Hydrator for path '$path' already exists");
45 }
46
47 $resolver = $this->query->getResolver();
48 $target = $this->query->getModel();
49 $relation = null;
50
51 if ($path === $target->getTableAlias()) {
52 $selectableColumns = $resolver->getSelectableColumns($target);
53 $columnToPropertyMap = array_combine($selectableColumns, $selectableColumns);
54 } else {
55 $relation = $resolver->resolveRelation($path);
56 $target = $relation->getTarget();
57 $selectableColumns = $resolver->getSelectableColumns($target);
58 $columnToPropertyMap = array_combine(
59 array_keys($resolver->qualifyColumnsAndAliases($selectableColumns, $target)),
60 $selectableColumns
61 );
62 }
63
64 $relationLoader = function (Model $subject, string $relationName) {
65 return $this->query->derive($relationName, $subject);
66 };
67
68 $defaults = $this->query->getResolver()->getDefaults($target);
69 foreach ($resolver->getRelations($target) as $targetRelation) {
70 $targetRelationName = $targetRelation->getName();
71 if (! $defaults->has($targetRelationName)) {
72 $defaults->add($targetRelationName, $relationLoader);
73 }
74 }
75
76 $this->updateColumnToTargetMap($path, $columnToPropertyMap);
77 $this->hydrators[$path] = [$target, $relation, $columnToPropertyMap, $defaults];
78
79 return $this;
80 }
81
82 /**
83 * Update which columns the given path is referencing
84 *
85 * @param string $path
86 * @param array<string, string> $columnToPropertyMap
87 *
88 * @return void
89 */
90 protected function updateColumnToTargetMap(string $path, array $columnToPropertyMap): void
91 {
92 foreach ($columnToPropertyMap as $qualifiedColumnPath => $_) {
93 if (isset($this->columnToTargetMap[$qualifiedColumnPath])) {
94 $this->columnToTargetMap[$qualifiedColumnPath][$path] = true;
95 } else {
96 $this->columnToTargetMap[$qualifiedColumnPath] = [$path => true];
97 }
98 }
99 }
100
101 /**
102 * Hydrate the given raw database rows into the specified model
103 *
104 * @param array $data
105 * @param Model $model
106 *
107 * @return Model
108 */
109 public function hydrate(array $data, Model $model): Model
110 {
111 $defaultsToApply = [];
112 $columnToTargetMap = $this->columnToTargetMap;
113 foreach ($this->hydrators as $path => $vars) {
114 [$target, $relation, $columnToPropertyMap, $defaults] = $vars;
115
116 $subject = $model;
117 if ($relation !== null) {
118 /** @var Relation $relation */
119
120 $steps = explode('.', $path);
121 $baseTable = array_shift($steps);
122 $relationName = array_pop($steps);
123
124 $parent = $model;
125 foreach ($steps as $i => $step) {
126 if (! isset($parent->$step)) {
127 $intermediateRelation = $this->query->getResolver()->resolveRelation(
128 $baseTable . '.' . implode('.', array_slice($steps, 0, $i + 1)),
129 $model
130 );
131 $parentClass = $intermediateRelation->getTargetClass();
132 $parent = $parent->$step = new $parentClass();
133 } else {
134 $parent = $parent->$step;
135 }
136 }
137
138 if (isset($parent->$relationName)) {
139 $subject = $parent->$relationName;
140 } else {
141 $subjectClass = $relation->getTargetClass();
142 $subject = new $subjectClass();
143 $parent->$relationName = $subject;
144 }
145 }
146
147 $subject->setProperties($this->extractAndMap($data, $columnToPropertyMap, $path, $columnToTargetMap));
148 $this->query->getResolver()->getBehaviors($target)->retrieve($subject);
149 $defaultsToApply[] = [$subject, $defaults];
150 }
151
152 // If there are any columns left, propagate them to the targeted relation if possible, to the base otherwise
153 foreach ($data as $column => $value) {
154 if (($aliasPrefix = $this->query->getResolver()->getAliasPrefix())) {
155 $column = substr($column, strlen($aliasPrefix));
156 }
157
158 $columnName = $column;
159 $steps = explode('_', $column);
160 $baseTable = array_shift($steps);
161 while (! empty($steps) && $baseTable !== $model->getTableAlias()) {
162 $baseTable .= '_' . array_shift($steps);
163 }
164
165 $subject = $model;
166 $target = $this->query->getModel();
167 $stepsTaken = [];
168 for ($i = 0; $i < count($steps); $i++) {
169 $step = $steps[$i];
170 $stepsTaken[] = $step;
171 $relationPath = "$baseTable." . implode('.', $stepsTaken);
172
173 try {
174 $relation = $this->query->getResolver()->resolveRelation($relationPath);
175 } catch (InvalidRelationException $_) {
176 if (isset($steps[$i + 1])) {
177 $steps[$i + 1] = $step . '_' . $steps[$i + 1];
178 array_pop($stepsTaken);
179 continue;
180 } else {
181 array_pop($stepsTaken);
182 $columnName = implode('_', array_slice($steps, $i));
183 break;
184 }
185 }
186
187 if (! $subject->hasProperty($step)) {
188 $stepClass = $relation->getTargetClass();
189 $subject->$step = new $stepClass();
190 }
191
192 $subject = $subject->$step;
193 $target = $relation->getTarget();
194 }
195
196 $subject->$columnName = $this->query
197 ->getResolver()
198 ->getBehaviors($target)
199 ->retrieveProperty($value, $columnName);
200 }
201
202 // Apply defaults last, otherwise we may evaluate them during hydration
203 foreach ($defaultsToApply as [$subject, $defaults]) {
204 foreach ($defaults as $name => $default) {
205 if (! $subject->hasProperty($name)) {
206 $subject->$name = $default;
207 }
208 }
209 }
210
211 return $model;
212 }
213
214 /**
215 * Extract and map the given data based on the specified column to property resolution map
216 *
217 * @param array $data
218 * @param array $columnToPropertyMap
219 * @param string $path
220 * @param array<string, array<string, bool>> $columnToTargetMap
221 *
222 * @return array
223 */
224 protected function extractAndMap(
225 array &$data,
226 array $columnToPropertyMap,
227 string $path,
228 array &$columnToTargetMap
229 ): array {
230 $extracted = [];
231 foreach (array_intersect_key($columnToPropertyMap, $data) as $column => $property) {
232 $extracted[$property] = $data[$column];
233
234 if (isset($columnToTargetMap[$column][$path])) {
235 unset($columnToTargetMap[$column][$path]);
236 if (empty($columnToTargetMap[$column])) {
237 // Only unset a column once it's really not required anymore
238 unset($data[$column], $columnToTargetMap[$column]);
239 }
240 }
241 }
242
243 return $extracted;
244 }
245 }