Passed
Push — master ( ca75ff...2f940f )
by
unknown
18:41
created

Typo3DbQueryParser::parseOperand()   B

Complexity

Conditions 8
Paths 9

Size

Total Lines 27
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 22
nc 9
nop 2
dl 0
loc 27
rs 8.4444
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the TYPO3 CMS project.
5
 *
6
 * It is free software; you can redistribute it and/or modify it under
7
 * the terms of the GNU General Public License, either version 2
8
 * of the License, or any later version.
9
 *
10
 * For the full copyright and license information, please read the
11
 * LICENSE.txt file that was distributed with this source code.
12
 *
13
 * The TYPO3 project - inspiring people to share!
14
 */
15
16
namespace TYPO3\CMS\Extbase\Persistence\Generic\Storage;
17
18
use Psr\Http\Message\ServerRequestInterface;
19
use TYPO3\CMS\Backend\Utility\BackendUtility;
20
use TYPO3\CMS\Core\Context\Context;
21
use TYPO3\CMS\Core\Database\Connection;
22
use TYPO3\CMS\Core\Database\ConnectionPool;
23
use TYPO3\CMS\Core\Database\Query\Expression\CompositeExpression;
24
use TYPO3\CMS\Core\Database\Query\Expression\ExpressionBuilder;
25
use TYPO3\CMS\Core\Database\Query\QueryBuilder;
26
use TYPO3\CMS\Core\Domain\Repository\PageRepository;
27
use TYPO3\CMS\Core\Http\ApplicationType;
28
use TYPO3\CMS\Core\Utility\GeneralUtility;
29
use TYPO3\CMS\Extbase\DomainObject\AbstractDomainObject;
30
use TYPO3\CMS\Extbase\Persistence\Generic\Exception;
31
use TYPO3\CMS\Extbase\Persistence\Generic\Exception\InconsistentQuerySettingsException;
32
use TYPO3\CMS\Extbase\Persistence\Generic\Exception\InvalidRelationConfigurationException;
33
use TYPO3\CMS\Extbase\Persistence\Generic\Exception\MissingColumnMapException;
34
use TYPO3\CMS\Extbase\Persistence\Generic\Exception\RepositoryException;
35
use TYPO3\CMS\Extbase\Persistence\Generic\Exception\UnsupportedOrderException;
36
use TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap;
37
use TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper;
38
use TYPO3\CMS\Extbase\Persistence\Generic\Qom;
39
use TYPO3\CMS\Extbase\Persistence\Generic\Qom\AndInterface;
40
use TYPO3\CMS\Extbase\Persistence\Generic\Qom\ComparisonInterface;
41
use TYPO3\CMS\Extbase\Persistence\Generic\Qom\ConstraintInterface;
42
use TYPO3\CMS\Extbase\Persistence\Generic\Qom\DynamicOperandInterface;
43
use TYPO3\CMS\Extbase\Persistence\Generic\Qom\EquiJoinCondition;
44
use TYPO3\CMS\Extbase\Persistence\Generic\Qom\JoinInterface;
45
use TYPO3\CMS\Extbase\Persistence\Generic\Qom\LowerCaseInterface;
46
use TYPO3\CMS\Extbase\Persistence\Generic\Qom\NotInterface;
47
use TYPO3\CMS\Extbase\Persistence\Generic\Qom\OrInterface;
48
use TYPO3\CMS\Extbase\Persistence\Generic\Qom\PropertyValueInterface;
49
use TYPO3\CMS\Extbase\Persistence\Generic\Qom\SelectorInterface;
50
use TYPO3\CMS\Extbase\Persistence\Generic\Qom\SourceInterface;
51
use TYPO3\CMS\Extbase\Persistence\Generic\Qom\UpperCaseInterface;
52
use TYPO3\CMS\Extbase\Persistence\Generic\QuerySettingsInterface;
53
use TYPO3\CMS\Extbase\Persistence\Generic\Storage\Exception\BadConstraintException;
54
use TYPO3\CMS\Extbase\Persistence\QueryInterface;
55
56
/**
57
 * QueryParser, converting the qom to string representation
58
 * @internal only to be used within Extbase, not part of TYPO3 Core API.
59
 */
60
class Typo3DbQueryParser
61
{
62
    protected DataMapper $dataMapper;
63
64
    /**
65
     * The TYPO3 page repository. Used for language and workspace overlay
66
     *
67
     * @var PageRepository
68
     */
69
    protected $pageRepository;
70
71
    /**
72
     * Instance of the Doctrine query builder
73
     *
74
     * @var QueryBuilder
75
     */
76
    protected $queryBuilder;
77
78
    /**
79
     * Maps domain model properties to their corresponding table aliases that are used in the query, e.g.:
80
     *
81
     * 'property1' => 'tableName',
82
     * 'property1.property2' => 'tableName1',
83
     *
84
     * @var array
85
     */
86
    protected $tablePropertyMap = [];
87
88
    /**
89
     * Maps tablenames to their aliases to be used in where clauses etc.
90
     * Mainly used for joins on the same table etc.
91
     *
92
     * @var array<string, string>
93
     */
94
    protected $tableAliasMap = [];
95
96
    /**
97
     * Stores all tables used in for SQL joins
98
     *
99
     * @var array
100
     */
101
    protected $unionTableAliasCache = [];
102
103
    /**
104
     * @var string
105
     */
106
    protected $tableName = '';
107
108
    /**
109
     * @var bool
110
     */
111
    protected $suggestDistinctQuery = false;
112
113
    public function __construct(DataMapper $dataMapper)
114
    {
115
        $this->dataMapper = $dataMapper;
116
    }
117
118
    /**
119
     * Whether using a distinct query is suggested.
120
     * This information is defined during parsing of the current query
121
     * for RELATION_HAS_MANY & RELATION_HAS_AND_BELONGS_TO_MANY relations.
122
     *
123
     * @return bool
124
     */
125
    public function isDistinctQuerySuggested(): bool
126
    {
127
        return $this->suggestDistinctQuery;
128
    }
129
130
    /**
131
     * Returns a ready to be executed QueryBuilder object, based on the query
132
     *
133
     * @param QueryInterface $query
134
     * @return QueryBuilder
135
     */
136
    public function convertQueryToDoctrineQueryBuilder(QueryInterface $query)
137
    {
138
        // Reset all properties
139
        $this->tablePropertyMap = [];
140
        $this->tableAliasMap = [];
141
        $this->unionTableAliasCache = [];
142
        $this->tableName = '';
143
144
        if ($query->getStatement() && $query->getStatement()->getStatement() instanceof QueryBuilder) {
145
            $this->queryBuilder = clone $query->getStatement()->getStatement();
146
            return $this->queryBuilder;
147
        }
148
        // Find the right table name
149
        $source = $query->getSource();
150
        $this->initializeQueryBuilder($source);
151
152
        $constraint = $query->getConstraint();
153
        if ($constraint instanceof ConstraintInterface) {
154
            $wherePredicates = $this->parseConstraint($constraint, $source);
155
            if (!empty($wherePredicates)) {
156
                $this->queryBuilder->andWhere($wherePredicates);
157
            }
158
        }
159
160
        $this->parseOrderings($query->getOrderings(), $source);
161
        $this->addTypo3Constraints($query);
162
163
        return $this->queryBuilder;
164
    }
165
166
    /**
167
     * Creates the queryBuilder object whether it is a regular select or a JOIN
168
     *
169
     * @param Qom\SourceInterface $source The source
170
     */
171
    protected function initializeQueryBuilder(SourceInterface $source)
172
    {
173
        if ($source instanceof SelectorInterface) {
174
            $className = $source->getNodeTypeName();
175
            $tableName = $this->dataMapper->getDataMap($className)->getTableName();
176
            $this->tableName = $tableName;
177
178
            $this->queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
179
                ->getQueryBuilderForTable($tableName);
180
181
            $this->queryBuilder
182
                ->getRestrictions()
183
                ->removeAll();
184
185
            $tableAlias = $this->getUniqueAlias($tableName);
186
187
            $this->queryBuilder
188
                ->select($tableAlias . '.*')
189
                ->from($tableName, $tableAlias);
190
191
            $this->addRecordTypeConstraint($className);
192
        } elseif ($source instanceof JoinInterface) {
193
            $leftSource = $source->getLeft();
194
            $leftTableName = $leftSource->getSelectorName();
195
196
            $this->queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
197
                ->getQueryBuilderForTable($leftTableName);
198
            $leftTableAlias = $this->getUniqueAlias($leftTableName);
199
            $this->queryBuilder
200
                ->select($leftTableAlias . '.*')
201
                ->from($leftTableName, $leftTableAlias);
202
            $this->parseJoin($source, $leftTableAlias);
203
        }
204
    }
205
206
    /**
207
     * Transforms a constraint into SQL and parameter arrays
208
     *
209
     * @param Qom\ConstraintInterface $constraint The constraint
210
     * @param Qom\SourceInterface $source The source
211
     * @return CompositeExpression|string
212
     * @throws \RuntimeException
213
     */
214
    protected function parseConstraint(ConstraintInterface $constraint, SourceInterface $source)
215
    {
216
        if ($constraint instanceof AndInterface) {
217
            return $this->queryBuilder->expr()->andX(
218
                $this->parseConstraint($constraint->getConstraint1(), $source),
219
                $this->parseConstraint($constraint->getConstraint2(), $source)
220
            );
221
        }
222
        if ($constraint instanceof OrInterface) {
223
            return $this->queryBuilder->expr()->orX(
224
                $this->parseConstraint($constraint->getConstraint1(), $source),
225
                $this->parseConstraint($constraint->getConstraint2(), $source)
226
            );
227
        }
228
        if ($constraint instanceof NotInterface) {
229
            return ' NOT(' . $this->parseConstraint($constraint->getConstraint(), $source) . ')';
230
        }
231
        if ($constraint instanceof ComparisonInterface) {
232
            return $this->parseComparison($constraint, $source);
233
        }
234
        throw new \RuntimeException('not implemented', 1476199898);
235
    }
236
237
    /**
238
     * Transforms orderings into SQL.
239
     *
240
     * @param array $orderings An array of orderings (Qom\Ordering)
241
     * @param Qom\SourceInterface $source The source
242
     * @throws UnsupportedOrderException
243
     */
244
    protected function parseOrderings(array $orderings, SourceInterface $source)
245
    {
246
        foreach ($orderings as $propertyName => $order) {
247
            if ($order !== QueryInterface::ORDER_ASCENDING && $order !== QueryInterface::ORDER_DESCENDING) {
248
                throw new UnsupportedOrderException('Unsupported order encountered.', 1242816074);
249
            }
250
            $className = null;
251
            $tableName = '';
252
            if ($source instanceof SelectorInterface) {
253
                $className = $source->getNodeTypeName();
254
                $tableName = $this->dataMapper->convertClassNameToTableName($className);
255
                $fullPropertyPath = '';
256
                while (strpos($propertyName, '.') !== false) {
257
                    $this->addUnionStatement($className, $tableName, $propertyName, $fullPropertyPath);
258
                }
259
            } elseif ($source instanceof JoinInterface) {
260
                $tableName = $source->getLeft()->getSelectorName();
261
            }
262
            $columnName = $this->dataMapper->convertPropertyNameToColumnName($propertyName, $className);
263
            if ($tableName !== '') {
264
                $this->queryBuilder->addOrderBy($tableName . '.' . $columnName, $order);
265
            } else {
266
                $this->queryBuilder->addOrderBy($columnName, $order);
267
            }
268
        }
269
    }
270
271
    /**
272
     * add TYPO3 Constraints for all tables to the queryBuilder
273
     *
274
     * @param QueryInterface $query
275
     */
276
    protected function addTypo3Constraints(QueryInterface $query)
277
    {
278
        $index = 0;
279
        foreach ($this->tableAliasMap as $tableAlias => $tableName) {
280
            if ($index === 0) {
281
                // We only add the pid and language check for the first table (aggregate root).
282
                // We know the first table is always the main table for the current query run.
283
                $additionalWhereClauses = $this->getAdditionalWhereClause($query->getQuerySettings(), $tableName, $tableAlias);
284
            } else {
285
                $additionalWhereClauses = [];
286
            }
287
            $index++;
288
            $statement = $this->getVisibilityConstraintStatement($query->getQuerySettings(), $tableName, $tableAlias);
289
            if ($statement !== '') {
290
                $additionalWhereClauses[] = $statement;
291
            }
292
            if (!empty($additionalWhereClauses)) {
293
                if (in_array($tableAlias, $this->unionTableAliasCache, true)) {
294
                    $this->queryBuilder->andWhere(
295
                        $this->queryBuilder->expr()->orX(
296
                            $this->queryBuilder->expr()->andX(...$additionalWhereClauses),
297
                            $this->queryBuilder->expr()->isNull($tableAlias . '.uid')
298
                        )
299
                    );
300
                } else {
301
                    $this->queryBuilder->andWhere(...$additionalWhereClauses);
302
                }
303
            }
304
        }
305
    }
306
307
    /**
308
     * Parse a Comparison into SQL and parameter arrays.
309
     *
310
     * @param Qom\ComparisonInterface $comparison The comparison to parse
311
     * @param Qom\SourceInterface $source The source
312
     * @return string
313
     * @throws \RuntimeException
314
     * @throws RepositoryException
315
     * @throws BadConstraintException
316
     */
317
    protected function parseComparison(ComparisonInterface $comparison, SourceInterface $source)
318
    {
319
        if ($comparison->getOperator() === QueryInterface::OPERATOR_CONTAINS) {
0 ignored issues
show
introduced by
The condition $comparison->getOperator...face::OPERATOR_CONTAINS is always false.
Loading history...
320
            if ($comparison->getOperand2() === null) {
321
                throw new BadConstraintException('The value for the CONTAINS operator must not be null.', 1484828468);
322
            }
323
            $value = $this->dataMapper->getPlainValue($comparison->getOperand2());
324
            if (!$source instanceof SelectorInterface) {
325
                throw new \RuntimeException('Source is not of type "SelectorInterface"', 1395362539);
326
            }
327
            $className = $source->getNodeTypeName();
328
            $tableName = $this->dataMapper->convertClassNameToTableName($className);
329
            $operand1 = $comparison->getOperand1();
330
            $propertyName = $operand1->getPropertyName();
331
            $fullPropertyPath = '';
332
            while (strpos($propertyName, '.') !== false) {
333
                $this->addUnionStatement($className, $tableName, $propertyName, $fullPropertyPath);
334
            }
335
            $columnName = $this->dataMapper->convertPropertyNameToColumnName($propertyName, $className);
336
            $dataMap = $this->dataMapper->getDataMap($className);
337
            $columnMap = $dataMap->getColumnMap($propertyName);
338
            $typeOfRelation = $columnMap instanceof ColumnMap ? $columnMap->getTypeOfRelation() : null;
339
            if ($typeOfRelation === ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
340
                /** @var ColumnMap $columnMap */
341
                $relationTableName = (string)$columnMap->getRelationTableName();
342
                $queryBuilderForSubselect = $this->queryBuilder->getConnection()->createQueryBuilder();
343
                $queryBuilderForSubselect
344
                        ->select($columnMap->getParentKeyFieldName())
345
                        ->from($relationTableName)
346
                        ->where(
347
                            $queryBuilderForSubselect->expr()->eq(
348
                                $columnMap->getChildKeyFieldName(),
349
                                $this->queryBuilder->createNamedParameter($value)
350
                            )
351
                        );
352
                $additionalWhereForMatchFields = $this->getAdditionalMatchFieldsStatement($queryBuilderForSubselect->expr(), $columnMap, $relationTableName, $relationTableName);
353
                if ($additionalWhereForMatchFields) {
354
                    $queryBuilderForSubselect->andWhere($additionalWhereForMatchFields);
355
                }
356
357
                return $this->queryBuilder->expr()->comparison(
358
                    $this->queryBuilder->quoteIdentifier($tableName . '.uid'),
359
                    'IN',
360
                    '(' . $queryBuilderForSubselect->getSQL() . ')'
361
                );
362
            }
363
            if ($typeOfRelation === ColumnMap::RELATION_HAS_MANY) {
364
                $parentKeyFieldName = $columnMap->getParentKeyFieldName();
365
                if (isset($parentKeyFieldName)) {
366
                    $childTableName = $columnMap->getChildTableName();
367
368
                    // Build the SQL statement of the subselect
369
                    $queryBuilderForSubselect = $this->queryBuilder->getConnection()->createQueryBuilder();
370
                    $queryBuilderForSubselect
371
                            ->select($parentKeyFieldName)
372
                            ->from($childTableName)
373
                            ->where(
374
                                $queryBuilderForSubselect->expr()->eq(
375
                                    'uid',
376
                                    (int)$value
377
                                )
378
                            );
379
380
                    // Add it to the main query
381
                    return $this->queryBuilder->expr()->eq(
382
                        $tableName . '.uid',
383
                        '(' . $queryBuilderForSubselect->getSQL() . ')'
384
                    );
385
                }
386
                return $this->queryBuilder->expr()->inSet(
387
                    $tableName . '.' . $columnName,
388
                    $this->queryBuilder->quote($value)
389
                );
390
            }
391
            throw new RepositoryException('Unsupported or non-existing property name "' . $propertyName . '" used in relation matching.', 1327065745);
392
        }
393
        return $this->parseDynamicOperand($comparison, $source);
394
    }
395
396
    /**
397
     * Parse a DynamicOperand into SQL and parameter arrays.
398
     *
399
     * @param Qom\ComparisonInterface $comparison
400
     * @param Qom\SourceInterface $source The source
401
     * @return string
402
     * @throws Exception
403
     * @throws BadConstraintException
404
     */
405
    protected function parseDynamicOperand(ComparisonInterface $comparison, SourceInterface $source)
406
    {
407
        $value = $comparison->getOperand2();
408
        $fieldName = $this->parseOperand($comparison->getOperand1(), $source);
409
        $expr = null;
410
        $exprBuilder = $this->queryBuilder->expr();
411
        switch ($comparison->getOperator()) {
412
            case QueryInterface::OPERATOR_IN:
413
                $hasValue = false;
414
                $plainValues = [];
415
                foreach ($value as $singleValue) {
416
                    $plainValue = $this->dataMapper->getPlainValue($singleValue);
417
                    if ($plainValue !== null) {
418
                        $hasValue = true;
419
                        $plainValues[] = $this->createTypedNamedParameter($singleValue);
420
                    }
421
                }
422
                if (!$hasValue) {
423
                    throw new BadConstraintException(
424
                        'The IN operator needs a non-empty value list to compare against. ' .
425
                        'The given value list is empty.',
426
                        1484828466
427
                    );
428
                }
429
                $expr = $exprBuilder->comparison($fieldName, 'IN', '(' . implode(', ', $plainValues) . ')');
430
                break;
431
            case QueryInterface::OPERATOR_EQUAL_TO:
432
                if ($value === null) {
433
                    $expr = $fieldName . ' IS NULL';
434
                } else {
435
                    $placeHolder = $this->createTypedNamedParameter($value);
436
                    $expr = $exprBuilder->comparison($fieldName, $exprBuilder::EQ, $placeHolder);
437
                }
438
                break;
439
            case QueryInterface::OPERATOR_EQUAL_TO_NULL:
440
                $expr = $fieldName . ' IS NULL';
441
                break;
442
            case QueryInterface::OPERATOR_NOT_EQUAL_TO:
443
                if ($value === null) {
444
                    $expr = $fieldName . ' IS NOT NULL';
445
                } else {
446
                    $placeHolder = $this->createTypedNamedParameter($value);
447
                    $expr = $exprBuilder->comparison($fieldName, $exprBuilder::NEQ, $placeHolder);
448
                }
449
                break;
450
            case QueryInterface::OPERATOR_NOT_EQUAL_TO_NULL:
451
                $expr = $fieldName . ' IS NOT NULL';
452
                break;
453
            case QueryInterface::OPERATOR_LESS_THAN:
454
                $placeHolder = $this->createTypedNamedParameter($value);
455
                $expr = $exprBuilder->comparison($fieldName, $exprBuilder::LT, $placeHolder);
456
                break;
457
            case QueryInterface::OPERATOR_LESS_THAN_OR_EQUAL_TO:
458
                $placeHolder = $this->createTypedNamedParameter($value);
459
                $expr = $exprBuilder->comparison($fieldName, $exprBuilder::LTE, $placeHolder);
460
                break;
461
            case QueryInterface::OPERATOR_GREATER_THAN:
462
                $placeHolder = $this->createTypedNamedParameter($value);
463
                $expr = $exprBuilder->comparison($fieldName, $exprBuilder::GT, $placeHolder);
464
                break;
465
            case QueryInterface::OPERATOR_GREATER_THAN_OR_EQUAL_TO:
466
                $placeHolder = $this->createTypedNamedParameter($value);
467
                $expr = $exprBuilder->comparison($fieldName, $exprBuilder::GTE, $placeHolder);
468
                break;
469
            case QueryInterface::OPERATOR_LIKE:
470
                $placeHolder = $this->createTypedNamedParameter($value, \PDO::PARAM_STR);
471
                $expr = $exprBuilder->comparison($fieldName, 'LIKE', $placeHolder);
472
                break;
473
            default:
474
                throw new Exception(
475
                    'Unsupported operator encountered.',
476
                    1242816073
477
                );
478
        }
479
        return $expr;
480
    }
481
482
    /**
483
     * Maps plain value of operand to PDO types to help Doctrine and/or the database driver process the value
484
     * correctly when building the query.
485
     *
486
     * @param mixed $value The parameter value
487
     * @return int
488
     * @throws \InvalidArgumentException
489
     */
490
    protected function getParameterType($value): int
491
    {
492
        $parameterType = gettype($value);
493
        switch ($parameterType) {
494
            case 'integer':
495
                return \PDO::PARAM_INT;
496
            case 'string':
497
                return \PDO::PARAM_STR;
498
            default:
499
                throw new \InvalidArgumentException(
500
                    'Unsupported parameter type encountered. Expected integer or string, ' . $parameterType . ' given.',
501
                    1494878863
502
                );
503
        }
504
    }
505
506
    /**
507
     * Create a named parameter for the QueryBuilder and guess the parameter type based on the
508
     * output of DataMapper::getPlainValue(). The type of the named parameter can be forced to
509
     * one of the \PDO::PARAM_* types by specifying the $forceType argument.
510
     *
511
     * @param mixed $value The input value that should be sent to the database
512
     * @param int|null $forceType The \PDO::PARAM_* type that should be forced
513
     * @return string The placeholder string to be used in the query
514
     * @see \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper::getPlainValue()
515
     */
516
    protected function createTypedNamedParameter($value, int $forceType = null): string
517
    {
518
        if ($value instanceof AbstractDomainObject
519
            && $value->_hasProperty('_localizedUid')
520
            && $value->_getProperty('_localizedUid') > 0
521
        ) {
522
            $plainValue = (int)$value->_getProperty('_localizedUid');
523
        } else {
524
            $plainValue = $this->dataMapper->getPlainValue($value);
525
        }
526
        $parameterType = $forceType ?? $this->getParameterType($plainValue);
527
        $placeholder = $this->queryBuilder->createNamedParameter($plainValue, $parameterType);
528
529
        return $placeholder;
530
    }
531
532
    /**
533
     * @param Qom\DynamicOperandInterface $operand
534
     * @param Qom\SourceInterface $source The source
535
     * @return string
536
     * @throws \InvalidArgumentException
537
     */
538
    protected function parseOperand(DynamicOperandInterface $operand, SourceInterface $source)
539
    {
540
        $tableName = null;
541
        if ($operand instanceof LowerCaseInterface) {
542
            $constraintSQL = 'LOWER(' . $this->parseOperand($operand->getOperand(), $source) . ')';
543
        } elseif ($operand instanceof UpperCaseInterface) {
544
            $constraintSQL = 'UPPER(' . $this->parseOperand($operand->getOperand(), $source) . ')';
545
        } elseif ($operand instanceof PropertyValueInterface) {
546
            $propertyName = $operand->getPropertyName();
547
            $className = '';
548
            if ($source instanceof SelectorInterface) {
549
                $className = $source->getNodeTypeName();
550
                $tableName = $this->dataMapper->convertClassNameToTableName($className);
551
                $fullPropertyPath = '';
552
                while (strpos($propertyName, '.') !== false) {
553
                    $this->addUnionStatement($className, $tableName, $propertyName, $fullPropertyPath);
554
                }
555
            } elseif ($source instanceof JoinInterface) {
556
                $tableName = $source->getJoinCondition()->getSelector1Name();
557
            }
558
            $columnName = $this->dataMapper->convertPropertyNameToColumnName($propertyName, $className);
559
            $constraintSQL = (!empty($tableName) ? $tableName . '.' : '') . $columnName;
560
            $constraintSQL = $this->queryBuilder->getConnection()->quoteIdentifier($constraintSQL);
561
        } else {
562
            throw new \InvalidArgumentException('Given operand has invalid type "' . get_class($operand) . '".', 1395710211);
563
        }
564
        return $constraintSQL;
565
    }
566
567
    /**
568
     * Add a constraint to ensure that the record type of the returned tuples is matching the data type of the repository.
569
     *
570
     * @param string $className The class name
571
     */
572
    protected function addRecordTypeConstraint($className)
573
    {
574
        if ($className !== null) {
0 ignored issues
show
introduced by
The condition $className !== null is always true.
Loading history...
575
            $dataMap = $this->dataMapper->getDataMap($className);
576
            if ($dataMap->getRecordTypeColumnName() !== null) {
0 ignored issues
show
introduced by
The condition $dataMap->getRecordTypeColumnName() !== null is always true.
Loading history...
577
                $recordTypes = [];
578
                if ($dataMap->getRecordType() !== null) {
579
                    $recordTypes[] = $dataMap->getRecordType();
580
                }
581
                foreach ($dataMap->getSubclasses() as $subclassName) {
582
                    $subclassDataMap = $this->dataMapper->getDataMap($subclassName);
583
                    if ($subclassDataMap->getRecordType() !== null) {
584
                        $recordTypes[] = $subclassDataMap->getRecordType();
585
                    }
586
                }
587
                if (!empty($recordTypes)) {
588
                    $recordTypeStatements = [];
589
                    foreach ($recordTypes as $recordType) {
590
                        $tableName = $dataMap->getTableName();
591
                        $recordTypeStatements[] = $this->queryBuilder->expr()->eq(
592
                            $tableName . '.' . $dataMap->getRecordTypeColumnName(),
593
                            $this->queryBuilder->createNamedParameter($recordType)
594
                        );
595
                    }
596
                    $this->queryBuilder->andWhere(
597
                        $this->queryBuilder->expr()->orX(...$recordTypeStatements)
598
                    );
599
                }
600
            }
601
        }
602
    }
603
604
    /**
605
     * Builds a condition for filtering records by the configured match field,
606
     * e.g. MM_match_fields, foreign_match_fields or foreign_table_field.
607
     *
608
     * @param ExpressionBuilder $exprBuilder
609
     * @param ColumnMap $columnMap The column man for which the condition should be build.
610
     * @param string $childTableAlias The alias of the child record table used in the query.
611
     * @param string $parentTable The real name of the parent table (used for building the foreign_table_field condition).
612
     * @return string The match field conditions or an empty string.
613
     */
614
    protected function getAdditionalMatchFieldsStatement($exprBuilder, $columnMap, $childTableAlias, $parentTable = null)
615
    {
616
        $additionalWhereForMatchFields = [];
617
        $relationTableMatchFields = $columnMap->getRelationTableMatchFields();
618
        if (is_array($relationTableMatchFields) && !empty($relationTableMatchFields)) {
619
            foreach ($relationTableMatchFields as $fieldName => $value) {
620
                $additionalWhereForMatchFields[] = $exprBuilder->eq($childTableAlias . '.' . $fieldName, $this->queryBuilder->createNamedParameter($value));
621
            }
622
        }
623
624
        if (isset($parentTable)) {
625
            $parentTableFieldName = $columnMap->getParentTableFieldName();
626
            if (!empty($parentTableFieldName)) {
627
                $additionalWhereForMatchFields[] = $exprBuilder->eq($childTableAlias . '.' . $parentTableFieldName, $this->queryBuilder->createNamedParameter($parentTable));
628
            }
629
        }
630
631
        if (!empty($additionalWhereForMatchFields)) {
632
            return $exprBuilder->andX(...$additionalWhereForMatchFields);
633
        }
634
        return '';
635
    }
636
637
    /**
638
     * Adds additional WHERE statements according to the query settings.
639
     *
640
     * @param QuerySettingsInterface $querySettings The TYPO3 CMS specific query settings
641
     * @param string $tableName The table name to add the additional where clause for
642
     * @param string $tableAlias The table alias used in the query.
643
     * @return array
644
     */
645
    protected function getAdditionalWhereClause(QuerySettingsInterface $querySettings, $tableName, $tableAlias = null)
646
    {
647
        $tableAlias = (string)$tableAlias;
648
        // todo: $tableAlias must not be null
649
650
        $whereClause = [];
651
        if ($querySettings->getRespectSysLanguage()) {
652
            $systemLanguageStatement = $this->getLanguageStatement($tableName, $tableAlias, $querySettings);
653
            if (!empty($systemLanguageStatement)) {
654
                $whereClause[] = $systemLanguageStatement;
655
            }
656
        }
657
658
        if ($querySettings->getRespectStoragePage()) {
659
            $pageIdStatement = $this->getPageIdStatement($tableName, $tableAlias, $querySettings->getStoragePageIds());
660
            if (!empty($pageIdStatement)) {
661
                $whereClause[] = $pageIdStatement;
662
            }
663
        } elseif (!empty($GLOBALS['TCA'][$tableName]['ctrl']['versioningWS'])) {
664
            // Always prevent workspace records from being returned (except for newly created records)
665
            $whereClause[] = $this->queryBuilder->expr()->eq($tableAlias . '.t3ver_oid', 0);
666
        }
667
668
        return $whereClause;
669
    }
670
671
    /**
672
     * Adds enableFields and deletedClause to the query if necessary
673
     *
674
     * @param QuerySettingsInterface $querySettings
675
     * @param string $tableName The database table name
676
     * @param string $tableAlias
677
     * @return string
678
     */
679
    protected function getVisibilityConstraintStatement(QuerySettingsInterface $querySettings, $tableName, $tableAlias)
680
    {
681
        $statement = '';
682
        if (is_array($GLOBALS['TCA'][$tableName]['ctrl'] ?? null)) {
683
            $ignoreEnableFields = $querySettings->getIgnoreEnableFields();
684
            $enableFieldsToBeIgnored = $querySettings->getEnableFieldsToBeIgnored();
685
            $includeDeleted = $querySettings->getIncludeDeleted();
686
            if (($GLOBALS['TYPO3_REQUEST'] ?? null) instanceof ServerRequestInterface
687
                && ApplicationType::fromRequest($GLOBALS['TYPO3_REQUEST'])->isFrontend()
688
            ) {
689
                $statement .= $this->getFrontendConstraintStatement($tableName, $ignoreEnableFields, $enableFieldsToBeIgnored, $includeDeleted);
690
            } else {
691
                // applicationType backend
692
                $statement .= $this->getBackendConstraintStatement($tableName, $ignoreEnableFields, $includeDeleted);
693
            }
694
            if (!empty($statement)) {
695
                $statement = $this->replaceTableNameWithAlias($statement, $tableName, $tableAlias);
696
                $statement = strtolower(substr($statement, 1, 3)) === 'and' ? substr($statement, 5) : $statement;
697
            }
698
        }
699
        return $statement;
700
    }
701
702
    /**
703
     * Returns constraint statement for frontend context
704
     *
705
     * @param string $tableName
706
     * @param bool $ignoreEnableFields A flag indicating whether the enable fields should be ignored
707
     * @param array $enableFieldsToBeIgnored If $ignoreEnableFields is true, this array specifies enable fields to be ignored. If it is NULL or an empty array (default) all enable fields are ignored.
708
     * @param bool $includeDeleted A flag indicating whether deleted records should be included
709
     * @return string
710
     * @throws InconsistentQuerySettingsException
711
     */
712
    protected function getFrontendConstraintStatement($tableName, $ignoreEnableFields, array $enableFieldsToBeIgnored, $includeDeleted)
713
    {
714
        $statement = '';
715
        if ($ignoreEnableFields && !$includeDeleted) {
716
            if (!empty($enableFieldsToBeIgnored)) {
717
                // array_combine() is necessary because of the way \TYPO3\CMS\Core\Domain\Repository\PageRepository::enableFields() is implemented
718
                $statement .= $this->getPageRepository()->enableFields($tableName, -1, array_combine($enableFieldsToBeIgnored, $enableFieldsToBeIgnored));
719
            } elseif (!empty($GLOBALS['TCA'][$tableName]['ctrl']['delete'])) {
720
                $statement .= ' AND ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['delete'] . '=0';
721
            }
722
        } elseif (!$ignoreEnableFields && !$includeDeleted) {
723
            $statement .= $this->getPageRepository()->enableFields($tableName);
724
        } elseif (!$ignoreEnableFields && $includeDeleted) {
725
            throw new InconsistentQuerySettingsException('Query setting "ignoreEnableFields=FALSE" can not be used together with "includeDeleted=TRUE" in frontend context.', 1460975922);
726
        }
727
        return $statement;
728
    }
729
730
    /**
731
     * Returns constraint statement for backend context
732
     *
733
     * @param string $tableName
734
     * @param bool $ignoreEnableFields A flag indicating whether the enable fields should be ignored
735
     * @param bool $includeDeleted A flag indicating whether deleted records should be included
736
     * @return string
737
     */
738
    protected function getBackendConstraintStatement($tableName, $ignoreEnableFields, $includeDeleted)
739
    {
740
        $statement = '';
741
        // In case of versioning-preview, enableFields are ignored (checked in Typo3DbBackend::doLanguageAndWorkspaceOverlay)
742
        $isUserInWorkspace = GeneralUtility::makeInstance(Context::class)->getPropertyFromAspect('workspace', 'isOffline');
743
        if (!$ignoreEnableFields && !$isUserInWorkspace) {
744
            $statement .= BackendUtility::BEenableFields($tableName);
745
        }
746
        if (!$includeDeleted && !empty($GLOBALS['TCA'][$tableName]['ctrl']['delete'])) {
747
            $statement .= ' AND ' . $tableName . '.' . $GLOBALS['TCA'][$tableName]['ctrl']['delete'] . '=0';
748
        }
749
        return $statement;
750
    }
751
752
    /**
753
     * Builds the language field statement
754
     *
755
     * @param string $tableName The database table name
756
     * @param string $tableAlias The table alias used in the query.
757
     * @param QuerySettingsInterface $querySettings The TYPO3 CMS specific query settings
758
     * @return string
759
     */
760
    protected function getLanguageStatement($tableName, $tableAlias, QuerySettingsInterface $querySettings)
761
    {
762
        if (empty($GLOBALS['TCA'][$tableName]['ctrl']['languageField'])) {
763
            return '';
764
        }
765
766
        // Select all entries for the current language
767
        // If any language is set -> get those entries which are not translated yet
768
        // They will be removed by \TYPO3\CMS\Core\Domain\Repository\PageRepository::getRecordOverlay if not matching overlay mode
769
        $languageField = $GLOBALS['TCA'][$tableName]['ctrl']['languageField'];
770
771
        $transOrigPointerField = $GLOBALS['TCA'][$tableName]['ctrl']['transOrigPointerField'] ?? '';
772
        if (!$transOrigPointerField || !$querySettings->getLanguageUid()) {
773
            return $this->queryBuilder->expr()->in(
774
                $tableAlias . '.' . $languageField,
775
                [(int)$querySettings->getLanguageUid(), -1]
776
            );
777
        }
778
779
        $mode = $querySettings->getLanguageOverlayMode();
780
        if (!$mode) {
781
            return $this->queryBuilder->expr()->in(
782
                $tableAlias . '.' . $languageField,
783
                [(int)$querySettings->getLanguageUid(), -1]
784
            );
785
        }
786
787
        $defLangTableAlias = $tableAlias . '_dl';
788
        $defaultLanguageRecordsSubSelect = $this->queryBuilder->getConnection()->createQueryBuilder();
789
        $defaultLanguageRecordsSubSelect
790
            ->select($defLangTableAlias . '.uid')
791
            ->from($tableName, $defLangTableAlias)
792
            ->where(
793
                $defaultLanguageRecordsSubSelect->expr()->andX(
794
                    $defaultLanguageRecordsSubSelect->expr()->eq($defLangTableAlias . '.' . $transOrigPointerField, 0),
795
                    $defaultLanguageRecordsSubSelect->expr()->eq($defLangTableAlias . '.' . $languageField, 0)
796
                )
797
            );
798
799
        $andConditions = [];
800
        // records in language 'all'
801
        $andConditions[] = $this->queryBuilder->expr()->eq($tableAlias . '.' . $languageField, -1);
802
        // translated records where a default language exists
803
        $andConditions[] = $this->queryBuilder->expr()->andX(
804
            $this->queryBuilder->expr()->eq($tableAlias . '.' . $languageField, (int)$querySettings->getLanguageUid()),
805
            $this->queryBuilder->expr()->in(
806
                $tableAlias . '.' . $transOrigPointerField,
807
                $defaultLanguageRecordsSubSelect->getSQL()
808
            )
809
        );
810
        if ($mode !== 'hideNonTranslated') {
811
            // $mode = TRUE
812
            // returns records from current language which have default language
813
            // together with not translated default language records
814
            $translatedOnlyTableAlias = $tableAlias . '_to';
815
            $queryBuilderForSubselect = $this->queryBuilder->getConnection()->createQueryBuilder();
816
            $queryBuilderForSubselect
817
                ->select($translatedOnlyTableAlias . '.' . $transOrigPointerField)
818
                ->from($tableName, $translatedOnlyTableAlias)
819
                ->where(
820
                    $queryBuilderForSubselect->expr()->andX(
821
                        $queryBuilderForSubselect->expr()->gt($translatedOnlyTableAlias . '.' . $transOrigPointerField, 0),
822
                        $queryBuilderForSubselect->expr()->eq($translatedOnlyTableAlias . '.' . $languageField, (int)$querySettings->getLanguageUid())
823
                    )
824
                );
825
            // records in default language, which do not have a translation
826
            $andConditions[] = $this->queryBuilder->expr()->andX(
827
                $this->queryBuilder->expr()->eq($tableAlias . '.' . $languageField, 0),
828
                $this->queryBuilder->expr()->notIn(
829
                    $tableAlias . '.uid',
830
                    $queryBuilderForSubselect->getSQL()
831
                )
832
            );
833
        }
834
835
        return $this->queryBuilder->expr()->orX(...$andConditions);
836
    }
837
838
    /**
839
     * Builds the page ID checking statement
840
     *
841
     * @param string $tableName The database table name
842
     * @param string $tableAlias The table alias used in the query.
843
     * @param array $storagePageIds list of storage page ids
844
     * @return string
845
     * @throws InconsistentQuerySettingsException
846
     */
847
    protected function getPageIdStatement($tableName, $tableAlias, array $storagePageIds)
848
    {
849
        if (!is_array($GLOBALS['TCA'][$tableName]['ctrl'])) {
850
            return '';
851
        }
852
853
        $rootLevel = (int)($GLOBALS['TCA'][$tableName]['ctrl']['rootLevel'] ?? 0);
854
        switch ($rootLevel) {
855
            // Only in pid 0
856
            case 1:
857
                $storagePageIds = [0];
858
                break;
859
            // Pid 0 and pagetree
860
            case -1:
861
                if (empty($storagePageIds)) {
862
                    $storagePageIds = [0];
863
                } else {
864
                    $storagePageIds[] = 0;
865
                }
866
                break;
867
            // Only pagetree or not set
868
            case 0:
869
                if (empty($storagePageIds)) {
870
                    throw new InconsistentQuerySettingsException('Missing storage page ids.', 1365779762);
871
                }
872
                break;
873
            // Invalid configuration
874
            default:
875
                return '';
876
        }
877
        $storagePageIds = array_map('intval', $storagePageIds);
878
        if (count($storagePageIds) === 1) {
879
            return $this->queryBuilder->expr()->eq($tableAlias . '.pid', reset($storagePageIds));
880
        }
881
        return $this->queryBuilder->expr()->in($tableAlias . '.pid', $storagePageIds);
882
    }
883
884
    /**
885
     * Transforms a Join into SQL and parameter arrays
886
     *
887
     * @param Qom\JoinInterface $join The join
888
     * @param string $leftTableAlias The alias from the table to main
889
     */
890
    protected function parseJoin(JoinInterface $join, $leftTableAlias)
891
    {
892
        $leftSource = $join->getLeft();
893
        $leftClassName = $leftSource->getNodeTypeName();
894
        $this->addRecordTypeConstraint($leftClassName);
895
        $rightSource = $join->getRight();
896
        if ($rightSource instanceof JoinInterface) {
897
            $left = $rightSource->getLeft();
898
            $rightClassName = $left->getNodeTypeName();
899
            $rightTableName = $left->getSelectorName();
900
        } else {
901
            $rightClassName = $rightSource->getNodeTypeName();
902
            $rightTableName = $rightSource->getSelectorName();
903
            $this->queryBuilder->addSelect($rightTableName . '.*');
904
        }
905
        $this->addRecordTypeConstraint($rightClassName);
906
        $rightTableAlias = $this->getUniqueAlias($rightTableName);
907
        $joinCondition = $join->getJoinCondition();
908
        $joinConditionExpression = null;
909
        $this->unionTableAliasCache[] = $rightTableAlias;
910
        if ($joinCondition instanceof EquiJoinCondition) {
911
            $column1Name = $this->dataMapper->convertPropertyNameToColumnName($joinCondition->getProperty1Name(), $leftClassName);
912
            $column2Name = $this->dataMapper->convertPropertyNameToColumnName($joinCondition->getProperty2Name(), $rightClassName);
913
914
            $joinConditionExpression = $this->queryBuilder->expr()->eq(
915
                $leftTableAlias . '.' . $column1Name,
916
                $this->queryBuilder->quoteIdentifier($rightTableAlias . '.' . $column2Name)
917
            );
918
        }
919
        $this->queryBuilder->leftJoin($leftTableAlias, $rightTableName, $rightTableAlias, $joinConditionExpression);
920
        if ($rightSource instanceof JoinInterface) {
921
            $this->parseJoin($rightSource, $rightTableAlias);
922
        }
923
    }
924
925
    /**
926
     * Generates a unique alias for the given table and the given property path.
927
     * The property path will be mapped to the generated alias in the tablePropertyMap.
928
     *
929
     * @param string $tableName The name of the table for which the alias should be generated.
930
     * @param string $fullPropertyPath The full property path that is related to the given table.
931
     * @return string The generated table alias.
932
     */
933
    protected function getUniqueAlias($tableName, $fullPropertyPath = null)
934
    {
935
        if (isset($fullPropertyPath) && isset($this->tablePropertyMap[$fullPropertyPath])) {
936
            return $this->tablePropertyMap[$fullPropertyPath];
937
        }
938
939
        $alias = $tableName;
940
        $i = 0;
941
        while (isset($this->tableAliasMap[$alias])) {
942
            $alias = $tableName . $i;
943
            $i++;
944
        }
945
946
        $this->tableAliasMap[$alias] = $tableName;
947
948
        if (isset($fullPropertyPath)) {
949
            $this->tablePropertyMap[$fullPropertyPath] = $alias;
950
        }
951
952
        return $alias;
953
    }
954
955
    /**
956
     * adds a union statement to the query, mostly for tables referenced in the where condition.
957
     * The property for which the union statement is generated will be appended.
958
     *
959
     * @param string $className The name of the parent class, will be set to the child class after processing.
960
     * @param string $tableName The name of the parent table, will be set to the table alias that is used in the union statement.
961
     * @param string $propertyPath The remaining property path, will be cut of by one part during the process.
962
     * @param string $fullPropertyPath The full path the the current property, will be used to make table names unique.
963
     * @throws Exception
964
     * @throws InvalidRelationConfigurationException
965
     * @throws MissingColumnMapException
966
     */
967
    protected function addUnionStatement(&$className, &$tableName, &$propertyPath, &$fullPropertyPath)
968
    {
969
        $explodedPropertyPath = explode('.', $propertyPath, 2);
970
        $propertyName = $explodedPropertyPath[0];
971
        $columnName = $this->dataMapper->convertPropertyNameToColumnName($propertyName, $className);
972
        $realTableName = $this->dataMapper->convertClassNameToTableName($className);
973
        $tableName = $this->tablePropertyMap[$fullPropertyPath] ?? $realTableName;
974
        $columnMap = $this->dataMapper->getDataMap($className)->getColumnMap($propertyName);
975
976
        if ($columnMap === null) {
977
            throw new MissingColumnMapException('The ColumnMap for property "' . $propertyName . '" of class "' . $className . '" is missing.', 1355142232);
978
        }
979
980
        $parentKeyFieldName = $columnMap->getParentKeyFieldName();
981
        $childTableName = $columnMap->getChildTableName();
982
983
        if ($childTableName === null) {
984
            throw new InvalidRelationConfigurationException('The relation information for property "' . $propertyName . '" of class "' . $className . '" is missing.', 1353170925);
985
        }
986
987
        $fullPropertyPath .= ($fullPropertyPath === '') ? $propertyName : '.' . $propertyName;
988
        $childTableAlias = $this->getUniqueAlias($childTableName, $fullPropertyPath);
989
990
        // If there is already a union with the current identifier we do not need to build it again and exit early.
991
        if (in_array($childTableAlias, $this->unionTableAliasCache, true)) {
992
            $propertyPath = $explodedPropertyPath[1];
993
            $tableName = $childTableAlias;
994
            $className = $this->dataMapper->getType($className, $propertyName);
995
            return;
996
        }
997
998
        if ($columnMap->getTypeOfRelation() === ColumnMap::RELATION_HAS_ONE) {
999
            if (isset($parentKeyFieldName)) {
1000
                // @todo: no test for this part yet
1001
                $joinConditionExpression = $this->queryBuilder->expr()->eq(
1002
                    $tableName . '.uid',
1003
                    $this->queryBuilder->quoteIdentifier($childTableAlias . '.' . $parentKeyFieldName)
1004
                );
1005
            } else {
1006
                $joinConditionExpression = $this->queryBuilder->expr()->eq(
1007
                    $tableName . '.' . $columnName,
1008
                    $this->queryBuilder->quoteIdentifier($childTableAlias . '.uid')
1009
                );
1010
            }
1011
            $this->queryBuilder->leftJoin($tableName, $childTableName, $childTableAlias, $joinConditionExpression);
1012
            $this->unionTableAliasCache[] = $childTableAlias;
1013
            $this->queryBuilder->andWhere(
1014
                $this->getAdditionalMatchFieldsStatement($this->queryBuilder->expr(), $columnMap, $childTableAlias, $realTableName)
1015
            );
1016
        } elseif ($columnMap->getTypeOfRelation() === ColumnMap::RELATION_HAS_MANY) {
1017
            // @todo: no tests for this part yet
1018
            if (isset($parentKeyFieldName)) {
1019
                $joinConditionExpression = $this->queryBuilder->expr()->eq(
1020
                    $tableName . '.uid',
1021
                    $this->queryBuilder->quoteIdentifier($childTableAlias . '.' . $parentKeyFieldName)
1022
                );
1023
            } else {
1024
                $joinConditionExpression = $this->queryBuilder->expr()->inSet(
1025
                    $tableName . '.' . $columnName,
1026
                    $this->queryBuilder->quoteIdentifier($childTableAlias . '.uid'),
1027
                    true
1028
                );
1029
            }
1030
            $this->queryBuilder->leftJoin($tableName, $childTableName, $childTableAlias, $joinConditionExpression);
1031
            $this->unionTableAliasCache[] = $childTableAlias;
1032
            $this->queryBuilder->andWhere(
1033
                $this->getAdditionalMatchFieldsStatement($this->queryBuilder->expr(), $columnMap, $childTableAlias, $realTableName)
1034
            );
1035
            $this->suggestDistinctQuery = true;
1036
        } elseif ($columnMap->getTypeOfRelation() === ColumnMap::RELATION_HAS_AND_BELONGS_TO_MANY) {
1037
            $relationTableName = (string)$columnMap->getRelationTableName();
1038
            $relationTableAlias = $this->getUniqueAlias($relationTableName, $fullPropertyPath . '_mm');
1039
1040
            $joinConditionExpression = $this->queryBuilder->expr()->andX(
1041
                $this->queryBuilder->expr()->eq(
1042
                    $tableName . '.uid',
1043
                    $this->queryBuilder->quoteIdentifier(
1044
                        $relationTableAlias . '.' . $columnMap->getParentKeyFieldName()
1045
                    )
1046
                ),
1047
                $this->getAdditionalMatchFieldsStatement($this->queryBuilder->expr(), $columnMap, $relationTableAlias, $realTableName)
1048
            );
1049
            $this->queryBuilder->leftJoin($tableName, $relationTableName, $relationTableAlias, $joinConditionExpression);
1050
            $joinConditionExpression = $this->queryBuilder->expr()->eq(
1051
                $relationTableAlias . '.' . $columnMap->getChildKeyFieldName(),
1052
                $this->queryBuilder->quoteIdentifier($childTableAlias . '.uid')
1053
            );
1054
            $this->queryBuilder->leftJoin($relationTableAlias, $childTableName, $childTableAlias, $joinConditionExpression);
1055
            $this->unionTableAliasCache[] = $childTableAlias;
1056
            $this->suggestDistinctQuery = true;
1057
        } else {
1058
            throw new Exception('Could not determine type of relation.', 1252502725);
1059
        }
1060
        $propertyPath = $explodedPropertyPath[1];
1061
        $tableName = $childTableAlias;
1062
        $className = $this->dataMapper->getType($className, $propertyName);
1063
    }
1064
1065
    /**
1066
     * If the table name does not match the table alias all occurrences of
1067
     * "tableName." are replaced with "tableAlias." in the given SQL statement.
1068
     *
1069
     * @param string $statement The SQL statement in which the values are replaced.
1070
     * @param string $tableName The table name that is replaced.
1071
     * @param string $tableAlias The table alias that replaced the table name.
1072
     * @return string The modified SQL statement.
1073
     */
1074
    protected function replaceTableNameWithAlias($statement, $tableName, $tableAlias)
1075
    {
1076
        if ($tableAlias !== $tableName) {
1077
            /** @var Connection $connection */
1078
            $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($tableName);
1079
            $quotedTableName = $connection->quoteIdentifier($tableName);
1080
            $quotedTableAlias = $connection->quoteIdentifier($tableAlias);
1081
            $statement = str_replace(
1082
                [$tableName . '.', $quotedTableName . '.'],
1083
                [$tableAlias . '.', $quotedTableAlias . '.'],
1084
                $statement
1085
            );
1086
        }
1087
1088
        return $statement;
1089
    }
1090
1091
    /**
1092
     * @return PageRepository
1093
     */
1094
    protected function getPageRepository()
1095
    {
1096
        if (!$this->pageRepository instanceof PageRepository) {
0 ignored issues
show
introduced by
$this->pageRepository is always a sub-type of TYPO3\CMS\Core\Domain\Repository\PageRepository.
Loading history...
1097
            $this->pageRepository = GeneralUtility::makeInstance(PageRepository::class);
1098
        }
1099
        return $this->pageRepository;
1100
    }
1101
}
1102