Completed
Push — master ( 6ee2a7...5f60a5 )
by Rafael
04:29
created

Relation::getRelatedItems()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 4.128

Importance

Changes 0
Metric Value
dl 0
loc 25
ccs 16
cts 20
cp 0.8
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 16
nc 3
nop 1
crap 4.128
1
<?php
2
namespace ApacheSolrForTypo3\Solr\ContentObject;
3
4
/***************************************************************
5
 *  Copyright notice
6
 *
7
 *  (c) 2011-2015 Ingo Renner <[email protected]>
8
 *  All rights reserved
9
 *
10
 *  This script is part of the TYPO3 project. The TYPO3 project is
11
 *  free software; you can redistribute it and/or modify
12
 *  it under the terms of the GNU General Public License as published by
13
 *  the Free Software Foundation; either version 3 of the License, or
14
 *  (at your option) any later version.
15
 *
16
 *  The GNU General Public License can be found at
17
 *  http://www.gnu.org/copyleft/gpl.html.
18
 *
19
 *  This script is distributed in the hope that it will be useful,
20
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 *  GNU General Public License for more details.
23
 *
24
 *  This copyright notice MUST APPEAR in all copies of the script!
25
 ***************************************************************/
26
27
use ApacheSolrForTypo3\Solr\Util;
28
use Doctrine\DBAL\Driver\Statement;
29
use TYPO3\CMS\Core\Database\ConnectionPool;
30
use TYPO3\CMS\Core\Database\Query\QueryBuilder;
31
use TYPO3\CMS\Core\Database\RelationHandler;
32
use TYPO3\CMS\Core\Utility\GeneralUtility;
33
use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer;
34
35
/**
36
 * A content object (cObj) to resolve relations between database records
37
 *
38
 * Configuration options:
39
 *
40
 * localField: the record's field to use to resolve relations
41
 * foreignLabelField: Usually the label field to retrieve from the related records is determined automatically using TCA, using this option the desired field can be specified explicitly
42
 * multiValue: whether to return related records suitable for a multi value field
43
 * singleValueGlue: when not using multiValue, the related records need to be concatenated using a glue string, by default this is ", ". Using this option a custom glue can be specified. The custom value must be wrapped by pipe (|) characters.
44
 * relationTableSortingField: field in an mm relation table to sort by, usually "sorting"
45
 * enableRecursiveValueResolution: if the specified remote table's label field is a relation to another table, the value will be resolve by following the relation recursively.
46
 * removeEmptyValues: Removes empty values when resolving relations, defaults to TRUE
47
 * removeDuplicateValues: Removes duplicate values
48
 *
49
 * @author Ingo Renner <[email protected]>
50
 */
51
class Relation
52
{
53
    const CONTENT_OBJECT_NAME = 'SOLR_RELATION';
54
55
    /**
56
     * Content object configuration
57
     *
58
     * @var array
59
     */
60
    protected $configuration = [];
61
62
    /**
63
     * Constructor.
64
     *
65 11
     */
66
    public function __construct()
67 11
    {
68 11
        $this->configuration['enableRecursiveValueResolution'] = 1;
69 11
        $this->configuration['removeEmptyValues'] = 1;
70
    }
71
72
    /**
73
     * Executes the SOLR_RELATION content object.
74
     *
75
     * Resolves relations between records. Currently supported relations are
76
     * TYPO3-style m:n relations.
77
     * May resolve single value and multi value relations.
78
     *
79
     * @param string $name content object name 'SOLR_RELATION'
80
     * @param array $configuration for the content object
81
     * @param string $TyposcriptKey not used
82
     * @param \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer $parentContentObject parent content object
83
     * @return string serialized array representation of the given list
84 11
     */
85
    public function cObjGetSingleExt(
86
        /** @noinspection PhpUnusedParameterInspection */ $name,
0 ignored issues
show
Unused Code introduced by
The parameter $name is not used and could be removed.

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

Loading history...
87
        array $configuration,
88
        /** @noinspection PhpUnusedParameterInspection */ $TyposcriptKey,
0 ignored issues
show
Unused Code introduced by
The parameter $TyposcriptKey is not used and could be removed.

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

Loading history...
89
        $parentContentObject
90 11
    ) {
91
        $this->configuration = array_merge($this->configuration, $configuration);
92 11
93
        $relatedItems = $this->getRelatedItems($parentContentObject);
94 11
95
        if (!empty($this->configuration['removeDuplicateValues'])) {
96
            $relatedItems = array_unique($relatedItems);
97
        }
98 11
99
        if (empty($configuration['multiValue'])) {
100
            // single value, need to concatenate related items
101
            $singleValueGlue = ', ';
102
103
            if (!empty($configuration['singleValueGlue'])) {
104
                $singleValueGlue = trim($configuration['singleValueGlue'], '|');
105
            }
106
107
            $result = implode($singleValueGlue, $relatedItems);
108
        } else {
109 11
            // multi value, need to serialize as content objects must return strings
110
            $result = serialize($relatedItems);
111
        }
112 11
113
        return $result;
114
    }
115
116
    /**
117
     * Gets the related items of the current record's configured field.
118
     *
119
     * @param ContentObjectRenderer $parentContentObject parent content object
120
     * @return array Array of related items, values already resolved from related records
121 11
     */
122
    protected function getRelatedItems(
123
        ContentObjectRenderer $parentContentObject
124 11
    ) {
125
126 11
        list($localTableNameOrg, $localRecordUid) = explode(':', $parentContentObject->currentRecord);
127 11
        $localFieldName = $this->configuration['localField'];
128
129 11
        if (!$this->isTcaConfiguredForTablesField($localTableNameOrg, $localFieldName)) {
130
            return [];
131 11
        }
132 1
133
        $localTableName = $this->usePagesLanguageOverlayInsteadOfPagesIfPossible($localTableNameOrg, $localFieldName);
134
        $localRecordUid = $this->getUidOfRecordOverlay($localTableNameOrg, $localFieldName, $localRecordUid);
135 11
136 11
        $localFieldTca = $GLOBALS['TCA'][$localTableName]['columns'][$localFieldName];
137
        if (isset($localFieldTca['config']['MM']) && trim($localFieldTca['config']['MM']) !== '') {
138 11
            $relatedItems = $this->getRelatedItemsFromMMTable($localTableName,
139 11
                $localRecordUid, $localFieldTca);
140 11
        } else {
141 11
            $relatedItems = $this->getRelatedItemsFromForeignTable($localTableName,
142 8
                $localRecordUid, $localFieldTca, $parentContentObject);
143 8
        }
144
145 3
        return $relatedItems;
146 3
    }
147
148
    /**
149
     * @param string $localTableName
150 11
     * @param string $localFieldName
151
     * @return string
152
     * @todo this can be removed when TYPO3 8 support is dropped since pages translations are in pages then as well
153
     */
154
    protected function usePagesLanguageOverlayInsteadOfPagesIfPossible(string $localTableName, string $localFieldName) : string
155
    {
156
        // pages has a special overlay table constriction
157
        if ($GLOBALS['TSFE']->sys_language_uid > 0
158
            && $localTableName === 'pages'
159
            && $this->isTcaConfiguredForTablesField('pages_language_overlay', $localFieldName)
160
            && Util::getIsTYPO3VersionBelow9()) {
161 8
            return 'pages_language_overlay';
162 8
        }
163 8
164 8
        return $localTableName;
165 8
    }
166 8
167
    /**
168
     * Checks if TCA is available for column by table
169 8
     *
170
     * @param string $tableName
171
     * @param string $fieldName
172
     * @return bool
173
     */
174
    protected function isTcaConfiguredForTablesField(string $tableName, string $fieldName) : bool
175 8
    {
176 8
        return isset($GLOBALS['TCA'][$tableName]['columns'][$fieldName]);
177 8
    }
178 8
179 2
    /**
180
     * Gets the related items from a table using a n:m relation.
181
     *
182 8
     * @param string $localTableName Local table name
183 8
     * @param int $localRecordUid Local record uid
184 8
     * @param array $localFieldTca The local table's TCA
185 8
     * @return array Array of related items, values already resolved from related records
186
     */
187
    protected function getRelatedItemsFromMMTable($localTableName, $localRecordUid, array $localFieldTca)
188
    {
189
        $relatedItems = [];
190
        $foreignTableName = $localFieldTca['config']['foreign_table'];
191
        $foreignTableTca = $GLOBALS['TCA'][$foreignTableName];
192
        $foreignTableLabelField = $this->resolveForeignTableLabelField($foreignTableTca);
193
        $mmTableName = $localFieldTca['config']['MM'];
194
195
        // Remove the first option of foreignLabelField for recursion
196
        if (strpos($this->configuration['foreignLabelField'], '.') !== false) {
197
            $foreignTableLabelFieldArr = explode('.', $this->configuration['foreignLabelField']);
198
            unset($foreignTableLabelFieldArr[0]);
199
            $this->configuration['foreignLabelField'] = implode('.', $foreignTableLabelFieldArr);
200 8
        }
201 3
202
        $relationHandler = GeneralUtility::makeInstance(RelationHandler::class);
203 8
        $relationHandler->start('', $foreignTableName, $mmTableName, $localRecordUid, $localTableName, $localFieldTca['config']);
204
        $selectUids = $relationHandler->tableArray[$foreignTableName];
205
        if (!is_array($selectUids) || count($selectUids) <= 0) {
206
            return $relatedItems;
207 8
        }
208
209
        $relatedRecords = $this->getRelatedRecords($foreignTableName, ...$selectUids);
210
        foreach ($relatedRecords as $record) {
211
            if (isset($foreignTableTca['columns'][$foreignTableLabelField]['config']['foreign_table'])
212
                && $this->configuration['enableRecursiveValueResolution']
213
            ) {
214
                if (strpos($this->configuration['foreignLabelField'], '.') !== false) {
215
                    $foreignLabelFieldArr = explode('.', $this->configuration['foreignLabelField']);
216
                    unset($foreignLabelFieldArr[0]);
217 11
                    $this->configuration['foreignLabelField'] = implode('.', $foreignLabelFieldArr);
218
                }
219 11
220
                $this->configuration['localField'] = $foreignTableLabelField;
221
222 11
                $contentObject = GeneralUtility::makeInstance(ContentObjectRenderer::class);
223 9
                $contentObject->start($record, $foreignTableName);
224
225
                return $this->getRelatedItems($contentObject);
226 4
            } else {
227 2
                if ($GLOBALS['TSFE']->sys_language_uid > 0) {
228
                    $record = $this->getTranslationOverlay($foreignTableName, $record);
229 4
                }
230
                $relatedItems[] = $record[$foreignTableLabelField];
231
            }
232 4
        }
233
234
        return $relatedItems;
235
    }
236
237
    /**
238
     * Resolves the field to use as the related item's label depending on TCA
239
     * and TypoScript configuration
240
     *
241
     * @param array $foreignTableTca The foreign table's TCA
242 3
     * @return string The field to use for the related item's label
243
     */
244 3
    protected function resolveForeignTableLabelField(array $foreignTableTca)
245 2
    {
246
        $foreignTableLabelField = $foreignTableTca['ctrl']['label'];
247
248 2
        // when foreignLabelField is not enabled we can return directly
249
        if (empty($this->configuration['foreignLabelField'])) {
250
            return $foreignTableLabelField;
251
        }
252
253
        if (strpos($this->configuration['foreignLabelField'], '.') !== false) {
254
            list($foreignTableLabelField) = explode('.', $this->configuration['foreignLabelField'], 2);
255
        } else {
256
            $foreignTableLabelField = $this->configuration['foreignLabelField'];
257
        }
258
259
        return $foreignTableLabelField;
260 3
    }
261
262
    /**
263
     * Return the translated record
264
     *
265
     * @param string $tableName
266 3
     * @param array $record
267 3
     * @return array
268 3
     */
269 3
    protected function getTranslationOverlay($tableName, $record)
270
    {
271
        if ($tableName === 'pages') {
272 3
            return $GLOBALS['TSFE']->sys_page->getPageOverlay($record, $GLOBALS['TSFE']->sys_language_uid);
273
        }
274 3
275 3
        return $GLOBALS['TSFE']->sys_page->getRecordOverlay($tableName, $record, $GLOBALS['TSFE']->sys_language_uid);
276
    }
277 3
278 3
    /**
279
     * Gets the related items from a table using a 1:n relation.
280 3
     *
281
     * @param string $localTableName Local table name
282
     * @param int $localRecordUid Local record uid
283
     * @param array $localFieldTca The local table's TCA
284 3
     * @param ContentObjectRenderer $parentContentObject parent content object
285
     * @return array Array of related items, values already resolved from related records
286 3
     */
287 3
    protected function getRelatedItemsFromForeignTable(
288 3
        $localTableName,
289 3
        $localRecordUid,
290 3
        array $localFieldTca,
291 3
        ContentObjectRenderer $parentContentObject
292 3
    ) {
293
        $relatedItems = [];
294 3
        $foreignTableName = $localFieldTca['config']['foreign_table'];
295 3
        $foreignTableTca = $GLOBALS['TCA'][$foreignTableName];
296
        $foreignTableLabelField = $this->resolveForeignTableLabelField($foreignTableTca);
297
298
            /** @var $relationHandler RelationHandler */
299 3
        $relationHandler = GeneralUtility::makeInstance(RelationHandler::class);
300
301
        $itemList = isset($parentContentObject->data[$this->configuration['localField']]) ?
302
                        $parentContentObject->data[$this->configuration['localField']] : '';
303
304
        $relationHandler->start($itemList, $foreignTableName, '', $localRecordUid, $localTableName, $localFieldTca['config']);
305
        $selectUids = $relationHandler->tableArray[$foreignTableName];
306
307
        if (!is_array($selectUids) || count($selectUids) <= 0) {
308
            return $relatedItems;
309
        }
310
311
        $relatedRecords = $this->getRelatedRecords($foreignTableName, ...$selectUids);
312
313
        foreach ($relatedRecords as $relatedRecord) {
314 3
            $resolveRelatedValue = $this->resolveRelatedValue(
315
                $relatedRecord,
316
                $foreignTableTca,
317
                $foreignTableLabelField,
318
                $parentContentObject,
319
                $foreignTableName
320
            );
321 3
            if (!empty($resolveRelatedValue) || !$this->configuration['removeEmptyValues']) {
322
                $relatedItems[] = $resolveRelatedValue;
323
            }
324
        }
325 3
326
        return $relatedItems;
327
    }
328 3
329 3
    /**
330 3
     * Resolves the value of the related field. If the related field's value is
331
     * a relation itself, this method takes care of resolving it recursively.
332
     *
333 2
     * @param array $relatedRecord Related record as array
334 2
     * @param array $foreignTableTca TCA of the related table
335
     * @param string $foreignTableLabelField Field name of the foreign label field
336
     * @param ContentObjectRenderer $parentContentObject cObject
337 2
     * @param string $foreignTableName Related record table name
338 2
     *
339 2
     * @return string
340 2
     */
341 2
    protected function resolveRelatedValue(
342
        array $relatedRecord,
343 2
        $foreignTableTca,
344
        $foreignTableLabelField,
345
        ContentObjectRenderer $parentContentObject,
346
        $foreignTableName = ''
347 2
    ) {
348 2
        if ($GLOBALS['TSFE']->sys_language_uid > 0 && !empty($foreignTableName)) {
349 2
            $relatedRecord = $this->getTranslationOverlay($foreignTableName, $relatedRecord);
350 2
        }
351 2
352
        $value = $relatedRecord[$foreignTableLabelField];
353 2
354
        if (
355
            !empty($foreignTableName)
356 2
            && isset($foreignTableTca['columns'][$foreignTableLabelField]['config']['foreign_table'])
357 2
            && $this->configuration['enableRecursiveValueResolution']
358
        ) {
359
            // backup
360 3
            $backupRecord = $parentContentObject->data;
361
            $backupConfiguration = $this->configuration;
362
363
            // adjust configuration for next level
364
            $this->configuration['localField'] = $foreignTableLabelField;
365
            $parentContentObject->data = $relatedRecord;
366
            if (strpos($this->configuration['foreignLabelField'], '.') !== false) {
367
                list(, $this->configuration['foreignLabelField']) = explode('.',
368
                    $this->configuration['foreignLabelField'], 2);
369
            } else {
370
                $this->configuration['foreignLabelField'] = '';
371 11
            }
372
373
            // recursion
374 11
            $relatedItemsFromForeignTable = $this->getRelatedItemsFromForeignTable(
375
                $foreignTableName,
376
                $relatedRecord['uid'],
377
                $foreignTableTca['columns'][$foreignTableLabelField],
378 11
                $parentContentObject
379 11
            );
380
            $value = array_pop($relatedItemsFromForeignTable);
381
382
            // restore
383 3
            $this->configuration = $backupConfiguration;
384 3
            $parentContentObject->data = $backupRecord;
385
        }
386
387 3
        return $parentContentObject->stdWrap($value, $this->configuration);
388 3
    }
389 3
390 3
    /**
391
     * When the record has an overlay we retrieve the uid of the translated record,
392 3
     * to resolve the relations from the translation.
393 3
     *
394
     * @param string $localTableName
395
     * @param int $localRecordUid
396 3
     * @return int
397
     */
398
    protected function getUidOfRecordOverlay($localTableName, $localFieldName, $localRecordUid)
399
    {
400 3
        // when no language is set at all we do not need to overlay
401 3
        if (!isset($GLOBALS['TSFE']->sys_language_uid)) {
402 3
            return $localRecordUid;
403
        }
404
        // when no language is set we can return the passed recordUid
405
        if (!$GLOBALS['TSFE']->sys_language_uid > 0) {
406
            return $localRecordUid;
407
        }
408
        // when no TCA configured for pages_language_overlay's field, then use original record Uid
409
        if ($localTableName === 'pages' && !$this->isTcaConfiguredForTablesField('pages_language_overlay', $localFieldName)) {
410
            return $localRecordUid;
411
        }
412 3
413
        /** @var QueryBuilder $queryBuilder */
414 3
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
415
            ->getQueryBuilderForTable($localTableName);
416
417 3
        $record = $queryBuilder
418 1
            ->select('*')
419 2
            ->from($localTableName)
420 2
            ->where(
421
                $queryBuilder->expr()->eq('uid', $localRecordUid)
422
            )
423
            ->execute()
424
            ->fetch();
425
426
        // when the overlay is not an array, we return the localRecordUid
427
        if (!is_array($record)) {
428
            return $localRecordUid;
429
        }
430
431
        $overlayUid = $this->getLocalRecordUidFromOverlay($localTableName, $record);
432
        $localRecordUid = ($overlayUid !== 0) ? $overlayUid : $localRecordUid;
433 11
        return $localRecordUid;
434
    }
435
436 11
    /**
437 11
     * This method retrieves the _PAGES_OVERLAY_UID or _LOCALIZED_UID from the localized record.
438 11
     *
439 11
     * @param string $localTableName
440 11
     * @param array $overlayRecord
441 2
     * @return int
442
     */
443 11
    protected function getLocalRecordUidFromOverlay($localTableName, $overlayRecord)
444
    {
445 11
        $overlayRecord = $this->getTranslationOverlay($localTableName, $overlayRecord);
446
447
        // when there is a _PAGES_OVERLAY_UID | _LOCALIZED_UID in the overlay, we return it
448
        if ($localTableName === 'pages' && isset($overlayRecord['_PAGES_OVERLAY_UID'])) {
449
            return (int)$overlayRecord['_PAGES_OVERLAY_UID'];
450
        } elseif (isset($overlayRecord['_LOCALIZED_UID'])) {
451
            return (int)$overlayRecord['_LOCALIZED_UID'];
452
        }
453
454
        return 0;
455
    }
456
457
    /**
458
     * Return records via relation.
459 11
     *
460
     * @param string $foreignTable The table to fetch records from.
461 11
     * @param int[] ...$uids The uids to fetch from table.
462 11
     * @return array
463 11
     */
464 11
    protected function getRelatedRecords($foreignTable, int ...$uids): array
465
    {
466 11
        /** @var QueryBuilder $queryBuilder */
467 11
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($foreignTable);
468
        $queryBuilder->select('*')
469
            ->from($foreignTable)
470
            ->where($queryBuilder->expr()->in('uid', $uids));
471
        if (isset($this->configuration['additionalWhereClause'])) {
472
            $queryBuilder->andWhere($this->configuration['additionalWhereClause']);
473
        }
474
        $statement = $queryBuilder->execute();
475
476
        return $this->sortByKeyInIN($statement, 'uid', ...$uids);
477
    }
478
479
    /**
480
     * Sorts the result set by key in array for IN values.
481
     *   Simulates MySqls ORDER BY FIELD(fieldname, COPY_OF_IN_FOR_WHERE)
482
     *   Example: SELECT * FROM a_table WHERE field_name IN (2, 3, 4) SORT BY FIELD(field_name, 2, 3, 4)
483
     *
484
     *
485
     * @param Statement $statement
486
     * @param string $columnName
487
     * @param array $arrayWithValuesForIN
488
     * @return array
489
     */
490
    protected function sortByKeyInIN(Statement $statement, string $columnName, ...$arrayWithValuesForIN) : array
491
    {
492
        $records = [];
493
        while ($record = $statement->fetch()) {
494
            $indexNumber = array_search($record[$columnName], $arrayWithValuesForIN);
495
            $records[$indexNumber] = $record;
496
        }
497
        ksort($records);
498
        return $records;
499
    }
500
}
501