Failed Conditions
Pull Request — master (#7885)
by Šimon
62:40
created

AbstractHydrator   A

Complexity

Total Complexity 37

Size/Duplication

Total Lines 462
Duplicated Lines 0 %

Test Coverage

Coverage 97.35%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 155
dl 0
loc 462
ccs 147
cts 151
cp 0.9735
rs 9.44
c 3
b 0
f 0
wmc 37

14 Methods

Rating   Name   Duplication   Size   Complexity  
A iterate() 0 13 1
A __construct() 0 5 1
A getIterable() 0 16 1
A getClassMetadata() 0 7 2
A onClear() 0 2 1
A hydrateAll() 0 15 1
A getDiscriminatorValues() 0 12 1
A cleanup() 0 12 1
A gatherScalarRowData() 0 27 5
A prepare() 0 2 1
A hydrateRowData() 0 3 1
B gatherRowData() 0 63 11
A hydrateRow() 0 15 2
B hydrateColumnInfo() 0 74 8
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\ORM\Internal\Hydration;
6
7
use Doctrine\DBAL\Driver\Statement;
8
use Doctrine\DBAL\FetchMode;
9
use Doctrine\DBAL\Platforms\AbstractPlatform;
10
use Doctrine\ORM\EntityManagerInterface;
11
use Doctrine\ORM\Events;
12
use Doctrine\ORM\Mapping\ClassMetadata;
13
use Doctrine\ORM\Query\ResultSetMapping;
14
use Doctrine\ORM\UnitOfWork;
15
use ReflectionClass;
16
use function array_map;
17
use function array_merge;
18
use function in_array;
19
20
/**
21
 * Base class for all hydrators. A hydrator is a class that provides some form
22
 * of transformation of an SQL result set into another structure.
23
 */
24
abstract class AbstractHydrator
25
{
26
    /**
27
     * The ResultSetMapping.
28
     *
29
     * @var ResultSetMapping
30
     */
31
    protected $rsm;
32
33
    /**
34
     * The EntityManager instance.
35
     *
36
     * @var EntityManagerInterface
37
     */
38
    protected $em;
39
40
    /**
41
     * The dbms Platform instance.
42
     *
43
     * @var AbstractPlatform
44
     */
45
    protected $platform;
46
47
    /**
48
     * The UnitOfWork of the associated EntityManager.
49
     *
50
     * @var UnitOfWork
51
     */
52
    protected $uow;
53
54
    /**
55
     * Local ClassMetadata cache to avoid going to the EntityManager all the time.
56
     *
57
     * @var ClassMetadata[]
58
     */
59
    protected $metadataCache = [];
60
61
    /**
62
     * The cache used during row-by-row hydration.
63
     *
64
     * @var mixed[][]
65
     */
66
    protected $cache = [];
67
68
    /**
69
     * The statement that provides the data to hydrate.
70
     *
71
     * @var Statement
72
     */
73
    protected $stmt;
74
75
    /**
76
     * The query hints.
77
     *
78
     * @var mixed[]
79
     */
80
    protected $hints;
81
82
    /**
83
     * Initializes a new instance of a class derived from <tt>AbstractHydrator</tt>.
84
     *
85
     * @param EntityManagerInterface $em The EntityManager to use.
86
     */
87 988
    public function __construct(EntityManagerInterface $em)
88
    {
89 988
        $this->em       = $em;
90 988
        $this->platform = $em->getConnection()->getDatabasePlatform();
91 988
        $this->uow      = $em->getUnitOfWork();
92 988
    }
93
94
    /**
95
     * Initiates a row-by-row hydration.
96
     *
97
     * @param object  $stmt
98
     * @param object  $resultSetMapping
99
     * @param mixed[] $hints
100
     *
101
     * @return IterableResult
102
     */
103 12
    public function iterate($stmt, $resultSetMapping, array $hints = [])
104
    {
105 12
        $this->stmt  = $stmt;
106 12
        $this->rsm   = $resultSetMapping;
107 12
        $this->hints = $hints;
108
109 12
        $evm = $this->em->getEventManager();
110
111 12
        $evm->addEventListener([Events::onClear], $this);
112
113 12
        $this->prepare();
114
115 12
        return new IterableResult($this);
116
    }
117
118
    /**
119
     * Initiates a row-by-row hydration.
120
     *
121
     * @param mixed[] $hints
122
     *
123
     * @return iterable<mixed>
124
     */
125
    public function getIterable(
126
        Statement $stmt,
127 976
        ResultSetMapping $resultSetMapping,
128
        array $hints = []
129 976
    ) : iterable {
130 976
        $this->stmt  = $stmt;
131 976
        $this->rsm   = $resultSetMapping;
132
        $this->hints = $hints;
133 976
134
        $evm = $this->em->getEventManager();
135 976
136
        $evm->addEventListener([Events::onClear], $this);
137 975
138
        $this->prepare();
139 965
140
        return new RowByRowResult($this);
141 965
    }
142
143
    /**
144
     * Hydrates all rows returned by the passed statement instance at once.
145
     *
146
     * @param object  $stmt
147
     * @param object  $resultSetMapping
148
     * @param mixed[] $hints
149
     *
150 11
     * @return mixed[]
151
     */
152 11
    public function hydrateAll($stmt, $resultSetMapping, array $hints = [])
153
    {
154 11
        $this->stmt  = $stmt;
155 8
        $this->rsm   = $resultSetMapping;
156
        $this->hints = $hints;
157 8
158
        $this->em->getEventManager()->addEventListener([Events::onClear], $this);
159
160 10
        $this->prepare();
161
162 10
        $result = $this->hydrateAllData();
163
164 10
        $this->cleanup();
165
166
        return $result;
167
    }
168
169
    /**
170
     * Hydrates a single row returned by the current statement instance during
171
     * row-by-row hydration with {@link iterate()}.
172
     *
173 8
     * @return mixed
174
     */
175 8
    public function hydrateRow()
176
    {
177
        $row = $this->stmt->fetch(FetchMode::ASSOCIATIVE);
178
179
        if (! $row) {
180
            $this->cleanup();
181 106
182
            return false;
183 106
        }
184
185
        $result = [];
186
187
        $this->hydrateRowData($row, $result);
188
189 973
        return $result;
190
    }
191 973
192
    /**
193 973
     * When executed in a hydrate() loop we have to clear internal state to
194 973
     * decrease memory consumption.
195 973
     *
196 973
     * @param mixed $eventArgs
197
     */
198 973
    public function onClear($eventArgs)
0 ignored issues
show
Unused Code introduced by
The parameter $eventArgs is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

198
    public function onClear(/** @scrutinizer ignore-unused */ $eventArgs)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
199 973
    {
200 973
    }
201 973
202
    /**
203
     * Executes one-time preparation tasks, once each time hydration is started
204
     * through {@link hydrateAll} or {@link iterate()}.
205
     */
206
    protected function prepare()
207
    {
208
    }
209
210
    /**
211
     * Executes one-time cleanup tasks at the end of a hydration that was initiated
212
     * through {@link hydrateAll} or {@link iterate()}.
213
     */
214
    protected function cleanup()
215
    {
216
        $this->stmt->closeCursor();
217
218
        $this->stmt          = null;
219
        $this->rsm           = null;
220
        $this->cache         = [];
221
        $this->metadataCache = [];
222
223
        $this->em
224
             ->getEventManager()
225
             ->removeEventListener([Events::onClear], $this);
226
    }
227
228
    /**
229
     * Hydrates a single row from the current statement instance.
230
     *
231
     * Template method.
232
     *
233
     * @param mixed[] $data   The row data.
234
     * @param mixed[] $result The result to fill.
235
     *
236
     * @throws HydrationException
237
     */
238
    protected function hydrateRowData(array $data, array &$result)
0 ignored issues
show
Unused Code introduced by
The parameter $result is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

238
    protected function hydrateRowData(array $data, /** @scrutinizer ignore-unused */ array &$result)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
239
    {
240
        throw new HydrationException('hydrateRowData() not implemented by this hydrator.');
241 695
    }
242
243 695
    /**
244
     * Hydrates all rows from the current statement instance at once.
245 695
     *
246 695
     * @return mixed[]
247 695
     */
248 8
    abstract protected function hydrateAllData();
249
250
    /**
251 695
     * Processes a row of the result set.
252
     *
253
     * Used for identity-based hydration (HYDRATE_OBJECT and HYDRATE_ARRAY).
254 695
     * Puts the elements of a result row into a new array, grouped by the dql alias
255 19
     * they belong to. The column names in the result set are mapped to their
256 19
     * field names during this procedure as well as any necessary conversions on
257 19
     * the values applied. Scalar values are kept in a specific key 'scalars'.
258 19
     *
259
     * @param mixed[] $data               SQL Result Row.
260 19
     * @param mixed[] $id                 Dql-Alias => ID-Hash.
261 19
     * @param mixed[] $nonemptyComponents Does this DQL-Alias has at least one non NULL value?
262 19
     *
263
     * @return mixed[] An array with all the fields (name => value) of the data row,
264 682
     *                grouped by their component alias.
265 112
     */
266 112
    protected function gatherRowData(array $data, array &$id, array &$nonemptyComponents)
267
    {
268 112
        $rowData = ['data' => []];
269 112
270
        foreach ($data as $key => $value) {
271
            $cacheKeyInfo = $this->hydrateColumnInfo($key);
272
            if ($cacheKeyInfo === null) {
273 642
                continue;
274 642
            }
275
276
            $fieldName = $cacheKeyInfo['fieldName'];
277
278 642
            switch (true) {
279 642
                case isset($cacheKeyInfo['isNewObjectParameter']):
280
                    $argIndex = $cacheKeyInfo['argIndex'];
281 24
                    $objIndex = $cacheKeyInfo['objIndex'];
282
                    $type     = $cacheKeyInfo['type'];
283
                    $value    = $type->convertToPHPValue($value, $this->platform);
284
285
                    $rowData['newObjects'][$objIndex]['class']           = $cacheKeyInfo['class'];
286
                    $rowData['newObjects'][$objIndex]['args'][$argIndex] = $value;
287 642
                    break;
288
289
                case isset($cacheKeyInfo['isScalar']):
290
                    $type  = $cacheKeyInfo['type'];
291 642
                    $value = $type->convertToPHPValue($value, $this->platform);
292 642
293
                    $rowData['scalars'][$fieldName] = $value;
294
                    break;
295 642
296 642
                //case (isset($cacheKeyInfo['isMetaColumn'])):
297 642
                default:
298
                    $dqlAlias = $cacheKeyInfo['dqlAlias'];
299 642
                    $type     = $cacheKeyInfo['type'];
300
301
                    // If there are field name collisions in the child class, then we need
302
                    // to only hydrate if we are looking at the correct discriminator value
303 695
                    if (isset($cacheKeyInfo['discriminatorColumn'], $data[$cacheKeyInfo['discriminatorColumn']])
304
                        && ! in_array((string) $data[$cacheKeyInfo['discriminatorColumn']], $cacheKeyInfo['discriminatorValues'], true)
305
                    ) {
306
                        break;
307
                    }
308
309
                    // in an inheritance hierarchy the same field could be defined several times.
310
                    // We overwrite this value so long we don't have a non-null value, that value we keep.
311
                    // Per definition it cannot be that a field is defined several times and has several values.
312
                    if (isset($rowData['data'][$dqlAlias][$fieldName])) {
313
                        break;
314
                    }
315
316
                    $rowData['data'][$dqlAlias][$fieldName] = $type
317
                        ? $type->convertToPHPValue($value, $this->platform)
318 98
                        : $value;
319
320 98
                    if ($cacheKeyInfo['isIdentifier'] && $value !== null) {
321
                        $id[$dqlAlias]                .= '|' . $value;
322 98
                        $nonemptyComponents[$dqlAlias] = true;
323 98
                    }
324 98
                    break;
325 1
            }
326
        }
327
328 98
        return $rowData;
329
    }
330
331
    /**
332 98
     * Processes a row of the result set.
333 49
     *
334 49
     * Used for HYDRATE_SCALAR. This is a variant of _gatherRowData() that
335 49
     * simply converts column names to field names and properly converts the
336 49
     * values according to their types. The resulting row has the same number
337 49
     * of elements as before.
338 49
     *
339
     * @param mixed[] $data
340
     *
341 98
     * @return mixed[] The processed row.
342
     */
343
    protected function gatherScalarRowData(&$data)
344 98
    {
345
        $rowData = [];
346
347
        foreach ($data as $key => $value) {
348
            $cacheKeyInfo = $this->hydrateColumnInfo($key);
349
            if ($cacheKeyInfo === null) {
350
                continue;
351
            }
352
353
            $fieldName = $cacheKeyInfo['fieldName'];
354 929
355
            // WARNING: BC break! We know this is the desired behavior to type convert values, but this
356 929
            // erroneous behavior exists since 2.0 and we're forced to keep compatibility.
357 424
            if (! isset($cacheKeyInfo['isScalar'])) {
358
                $dqlAlias  = $cacheKeyInfo['dqlAlias'];
359
                $type      = $cacheKeyInfo['type'];
360
                $fieldName = $dqlAlias . '_' . $fieldName;
361
                $value     = $type
362 929
                    ? $type->convertToPHPValue($value, $this->platform)
363 851
                    : $value;
364 851
            }
365 851
366 851
            $rowData[$fieldName] = $value;
367
        }
368
369 851
        return $rowData;
370 851
    }
371 851
372 851
    /**
373
     * Retrieve column information from ResultSetMapping.
374
     *
375
     * @param string $key Column name
376
     *
377 851
     * @return mixed[]|null
378 107
     */
379 107
    protected function hydrateColumnInfo($key)
380
    {
381 107
        if (isset($this->cache[$key])) {
382 107
            return $this->cache[$key];
383 107
        }
384
385
        switch (true) {
386
            // NOTE: Most of the times it's a field mapping, so keep it first!!!
387
            case isset($this->rsm->fieldMappings[$key]):
388 822
                $classMetadata = $this->getClassMetadata($this->rsm->declaringClasses[$key]);
389 741
                $fieldName     = $this->rsm->fieldMappings[$key];
390
                $ownerMap      = $this->rsm->columnOwnerMap[$key];
391 19
                $property      = $classMetadata->getProperty($fieldName);
392
393 19
                $columnInfo = [
394 19
                    'isIdentifier' => $property->isPrimaryKey(),
395
                    'fieldName'    => $fieldName,
396 19
                    'type'         => $property->getType(),
0 ignored issues
show
Bug introduced by
The method getType() does not exist on Doctrine\ORM\Mapping\Property. It seems like you code against a sub-type of Doctrine\ORM\Mapping\Property such as Doctrine\ORM\Mapping\FieldMetadata. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

396
                    'type'         => $property->/** @scrutinizer ignore-call */ getType(),
Loading history...
397 19
                    'dqlAlias'     => $this->rsm->columnOwnerMap[$key],
398 19
                ];
399 19
400 19
                // the current discriminator value must be saved in order to disambiguate fields hydration,
401
                // should there be field name collisions
402 728
                if ($classMetadata->getParent() && isset($this->rsm->discriminatorColumns[$ownerMap])) {
403 163
                    return $this->cache[$key] = array_merge(
404 163
                        $columnInfo,
405 163
                        [
406 163
                            'discriminatorColumn' => $this->rsm->discriminatorColumns[$ownerMap],
407
                            'discriminatorValue'  => $classMetadata->discriminatorValue,
408 612
                            'discriminatorValues' => $this->getDiscriminatorValues($classMetadata),
409
                        ]
410 607
                    );
411 607
                }
412
413
                return $this->cache[$key] = $columnInfo;
414 607
            case isset($this->rsm->newObjectMappings[$key]):
415
                // WARNING: A NEW object is also a scalar, so it must be declared before!
416 607
                $mapping = $this->rsm->newObjectMappings[$key];
417 607
418
                return $this->cache[$key] = [
419 607
                    'isScalar'             => true,
420 607
                    'isNewObjectParameter' => true,
421 607
                    'fieldName'            => $this->rsm->scalarMappings[$key],
422
                    'type'                 => $this->rsm->typeMappings[$key],
423
                    'argIndex'             => $mapping['argIndex'],
424
                    'objIndex'             => $mapping['objIndex'],
425
                    'class'                => new ReflectionClass($mapping['className']),
426
                ];
427 10
            case isset($this->rsm->scalarMappings[$key]):
428
                return $this->cache[$key] = [
429
                    'isScalar'  => true,
430
                    'fieldName' => $this->rsm->scalarMappings[$key],
431
                    'type'      => $this->rsm->typeMappings[$key],
432
                ];
433 107
            case isset($this->rsm->metaMappings[$key]):
434
                // Meta column (has meaning in relational schema only, i.e. foreign keys or discriminator columns).
435 107
                $fieldName = $this->rsm->metaMappings[$key];
436
                $dqlAlias  = $this->rsm->columnOwnerMap[$key];
437 50
438 107
                // Cache metadata fetch
439 107
                $this->getClassMetadata($this->rsm->aliasMap[$dqlAlias]);
440
441
                return $this->cache[$key] = [
442 107
                    'isIdentifier' => isset($this->rsm->isIdentifierColumn[$dqlAlias][$key]),
443
                    'isMetaColumn' => true,
444 107
                    'fieldName'    => $fieldName,
445
                    'type'         => $this->rsm->typeMappings[$key],
446
                    'dqlAlias'     => $dqlAlias,
447
                ];
448
        }
449
450
        // this column is a left over, maybe from a LIMIT query hack for example in Oracle or DB2
451
        // maybe from an additional column that has not been defined in a NativeQuery ResultSetMapping.
452
        return null;
453
    }
454 872
455
    /**
456 872
     * @return string[]
457 872
     */
458
    private function getDiscriminatorValues(ClassMetadata $classMetadata) : array
459
    {
460 872
        $values = array_map(
461
            function (string $subClass) : string {
462
                return (string) $this->getClassMetadata($subClass)->discriminatorValue;
463
            },
464
            $classMetadata->getSubClasses()
465
        );
466
467
        $values[] = (string) $classMetadata->discriminatorValue;
468
469
        return $values;
470
    }
471
472
    /**
473
     * Retrieve ClassMetadata associated to entity class name.
474
     *
475
     * @param string $className
476
     *
477
     * @return ClassMetadata
478
     */
479
    protected function getClassMetadata($className)
480
    {
481
        if (! isset($this->metadataCache[$className])) {
482
            $this->metadataCache[$className] = $this->em->getClassMetadata($className);
483
        }
484
485
        return $this->metadataCache[$className];
486
    }
487
}
488