Passed
Pull Request — release-11.5.x (#3228)
by Rafael
06:38 queued 02:30
created

getTranslationOverlaysWithConfiguredSite()   B

Complexity

Conditions 10
Paths 6

Size

Total Lines 33
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 10.0203

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 20
dl 0
loc 33
ccs 16
cts 17
cp 0.9412
rs 7.6666
c 1
b 1
f 0
cc 10
nc 6
nop 3
crap 10.0203

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the TYPO3 CMS project.
7
 *
8
 * It is free software; you can redistribute it and/or modify it under
9
 * the terms of the GNU General Public License, either version 2
10
 * of the License, or any later version.
11
 *
12
 * For the full copyright and license information, please read the
13
 * LICENSE.txt file that was distributed with this source code.
14
 *
15
 * The TYPO3 project - inspiring people to share!
16
 */
17
18
namespace ApacheSolrForTypo3\Solr\IndexQueue;
19
20
use ApacheSolrForTypo3\Solr\ConnectionManager;
21
use ApacheSolrForTypo3\Solr\Domain\Search\ApacheSolrDocument\Builder;
22
use ApacheSolrForTypo3\Solr\Domain\Site\Site;
23
use ApacheSolrForTypo3\Solr\Domain\Site\SiteRepository;
24
use ApacheSolrForTypo3\Solr\FieldProcessor\Service;
25
use ApacheSolrForTypo3\Solr\FrontendEnvironment;
26
use ApacheSolrForTypo3\Solr\FrontendEnvironment\Exception\Exception as FrontendEnvironmentException;
27
use ApacheSolrForTypo3\Solr\FrontendEnvironment\Tsfe;
28
use ApacheSolrForTypo3\Solr\NoSolrConnectionFoundException;
29
use ApacheSolrForTypo3\Solr\System\Logging\SolrLogManager;
30
use ApacheSolrForTypo3\Solr\System\Records\Pages\PagesRepository;
31
use ApacheSolrForTypo3\Solr\System\Solr\Document\Document;
32
use ApacheSolrForTypo3\Solr\System\Solr\ResponseAdapter;
33
use ApacheSolrForTypo3\Solr\System\Solr\SolrConnection;
34
use Doctrine\DBAL\Driver\Exception as DBALDriverException;
35
use Doctrine\DBAL\Exception as DBALException;
36
use InvalidArgumentException;
37
use RuntimeException;
38
use Solarium\Exception\HttpException;
39
use Throwable;
40
use TYPO3\CMS\Core\Context\LanguageAspectFactory;
41
use TYPO3\CMS\Core\Exception\SiteNotFoundException;
42
use TYPO3\CMS\Core\Site\SiteFinder;
43
use TYPO3\CMS\Core\Utility\GeneralUtility;
44
use TYPO3\CMS\Core\Utility\RootlineUtility;
45
use UnexpectedValueException;
46
47
/**
48
 * A general purpose indexer to be used for indexing of any kind of regular
49
 * records like tt_news, tt_address, and so on.
50
 * Specialized indexers can extend this class to handle advanced stuff like
51
 * category resolution in tt_news or file indexing.
52
 *
53
 * @author Ingo Renner <[email protected]>
54
 * @copyright  (c) 2009-2015 Ingo Renner <[email protected]>
55
 */
56
class Indexer extends AbstractIndexer
57
{
58
    /**
59
     * A Solr service instance to interact with the Solr server
60
     *
61
     * @var SolrConnection|null
62
     */
63
    protected ?SolrConnection $solr;
64
65
    /**
66
     * @var ConnectionManager
67
     */
68
    protected ConnectionManager $connectionManager;
69
70
    /**
71
     * Holds options for a specific indexer
72
     *
73
     * @var array
74
     */
75
    protected array $options = [];
76
77
    /**
78
     * To log or not to log... #Shakespeare
79
     *
80
     * @var bool
81
     */
82
    protected bool $loggingEnabled = false;
83
84
    /**
85
     * @var SolrLogManager
86
     */
87
    protected SolrLogManager $logger;
88
89
    /**
90
     * @var PagesRepository
91
     */
92
    protected PagesRepository $pagesRepository;
93
94
    /**
95
     * @var Builder
96
     */
97
    protected Builder $documentBuilder;
98
99
    /**
100
     * @var FrontendEnvironment
101
     */
102
    protected FrontendEnvironment $frontendEnvironment;
103
104
    /**
105
     * Constructor
106
     *
107
     * @param array $options array of indexer options
108
     * @param PagesRepository|null $pagesRepository
109
     * @param Builder|null $documentBuilder
110
     * @param SolrLogManager|null $logger
111
     * @param ConnectionManager|null $connectionManager
112
     * @param FrontendEnvironment|null $frontendEnvironment
113
     */
114 48
    public function __construct(
115
        array $options = [],
116
        PagesRepository $pagesRepository = null,
117
        Builder $documentBuilder = null,
118
        SolrLogManager $logger = null,
119
        ConnectionManager $connectionManager = null,
120
        FrontendEnvironment $frontendEnvironment = null
121
    ) {
122 48
        $this->options = $options;
123 48
        $this->pagesRepository = $pagesRepository ?? GeneralUtility::makeInstance(PagesRepository::class);
124 48
        $this->documentBuilder = $documentBuilder ?? GeneralUtility::makeInstance(Builder::class);
125 48
        $this->logger = $logger ?? GeneralUtility::makeInstance(SolrLogManager::class, /** @scrutinizer ignore-type */ __CLASS__);
126 48
        $this->connectionManager = $connectionManager ?? GeneralUtility::makeInstance(ConnectionManager::class);
127 48
        $this->frontendEnvironment = $frontendEnvironment ?? GeneralUtility::makeInstance(FrontendEnvironment::class);
128
    }
129
130
    /**
131
     * Indexes an item from the indexing queue.
132
     *
133
     * @param Item $item An index queue item
134
     * @return bool returns true when indexed, false when not
135
     * @throws DBALDriverException
136
     * @throws DBALException
137
     * @throws FrontendEnvironmentException
138
     * @throws NoSolrConnectionFoundException
139
     * @throws SiteNotFoundException
140
     */
141 20
    public function index(Item $item): bool
142
    {
143 20
        $indexed = true;
144
145 20
        $this->type = $item->getType();
146 20
        $this->setLogging($item);
147
148 20
        $solrConnections = $this->getSolrConnectionsByItem($item);
149 20
        foreach ($solrConnections as $systemLanguageUid => $solrConnection) {
150 20
            $this->solr = $solrConnection;
151
152 20
            if (!$this->indexItem($item, (int)$systemLanguageUid)) {
153
                /*
154
                 * A single language voting for "not indexed" should make the whole
155
                 * item count as being not indexed, even if all other languages are
156
                 * indexed.
157
                 * If there is no translation for a single language, this item counts
158
                 * as TRUE since it's not an error which that should make the item
159
                 * being reindexed during another index run.
160
                 */
161
                $indexed = false;
162
            }
163
        }
164
165 20
        return $indexed;
166
    }
167
168
    /**
169
     * Creates a single Solr Document for an item in a specific language.
170
     *
171
     * @param Item $item An index queue item to index.
172
     * @param int $language The language to use.
173
     * @return bool TRUE if item was indexed successfully, FALSE on failure
174
     * @throws DBALDriverException
175
     * @throws DBALException
176
     * @throws FrontendEnvironmentException
177
     * @throws SiteNotFoundException
178
     */
179 20
    protected function indexItem(Item $item, int $language = 0): bool
180
    {
181 20
        $itemIndexed = false;
182 20
        $documents = [];
183
184 20
        $itemDocument = $this->itemToDocument($item, $language);
185 20
        if (is_null($itemDocument)) {
186
            /*
187
             * If there is no itemDocument, this means there was no translation
188
             * for this record. This should not stop the current item to count as
189
             * being valid because not-indexing not-translated items is perfectly
190
             * fine.
191
             */
192
            return true;
193
        }
194
195 20
        $documents[] = $itemDocument;
196 20
        $documents = array_merge($documents, $this->getAdditionalDocuments($item, $language, $itemDocument));
197 20
        $documents = $this->processDocuments($item, $documents);
198 20
        $documents = $this->preAddModifyDocuments($item, $language, $documents);
199
200
        try {
201 20
            $response = $this->solr->getWriteService()->addDocuments($documents);
0 ignored issues
show
Bug introduced by
The method getWriteService() does not exist on null. ( Ignorable by Annotation )

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

201
            $response = $this->solr->/** @scrutinizer ignore-call */ getWriteService()->addDocuments($documents);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
202 20
            if ($response->getHttpStatus() == 200) {
203 20
                $itemIndexed = true;
204
            }
205
        } catch (HttpException $e) {
206
            $response = new ResponseAdapter($e->getBody(), 500, $e->getStatusMessage());
207
        }
208
209 20
        $this->log($item, $documents, $response);
210
211 20
        return $itemIndexed;
212
    }
213
214
    /**
215
     * Gets the full item record.
216
     *
217
     * This general record indexer simply gets the record from the item. Other
218
     * more specialized indexers may provide more data for their specific item
219
     * types.
220
     *
221
     * @param Item $item The item to be indexed
222
     * @param int $language Language Id (sys_language.uid)
223
     * @return array|null The full record with fields of data to be used for indexing or NULL to prevent an item from being indexed
224
     * @throws DBALDriverException
225
     * @throws FrontendEnvironmentException
226
     * @throws SiteNotFoundException
227
     */
228 20
    protected function getFullItemRecord(Item $item, int $language = 0): ?array
229
    {
230 20
        $itemRecord = $this->getItemRecordOverlayed($item, $language);
231
232 20
        if (!is_null($itemRecord)) {
233 20
            $itemRecord['__solr_index_language'] = $language;
234
        }
235
236 20
        return $itemRecord;
237
    }
238
239
    /**
240
     * Returns the overlaid item record.
241
     *
242
     * @param Item $item
243
     * @param int $language
244
     * @return array|mixed|null
245
     * @throws DBALDriverException
246
     * @throws FrontendEnvironmentException
247
     * @throws SiteNotFoundException
248
     */
249 20
    protected function getItemRecordOverlayed(Item $item, int $language): ?array
250
    {
251 20
        $itemRecord = $item->getRecord();
252 20
        $languageField = $GLOBALS['TCA'][$item->getType()]['ctrl']['languageField'] ?? null;
253
        // skip "free content mode"-record for other languages, if item is a "free content mode"-record
254 20
        if ($this->isAFreeContentModeItemRecord($item)
255
            && isset($languageField)
256 20
            && (int)($itemRecord[$languageField] ?? null) !== $language
257
        ) {
258
            return null;
259
        }
260
        // skip fallback for "free content mode"-languages
261 20
        if ($this->isLanguageInAFreeContentMode($item, $language)
262
            && isset($languageField)
263 20
            && (int)($itemRecord[$languageField] ?? null) !== $language
264
        ) {
265
            return null;
266
        }
267
268 20
        $pidToUse = $this->getPageIdOfItem($item);
269
270 20
        return GeneralUtility::makeInstance(Tsfe::class)
271 20
            ->getTsfeByPageIdAndLanguageId($pidToUse, $language, $item->getRootPageUid())
272 20
            ->sys_page->getLanguageOverlay($item->getType(), $itemRecord);
273
    }
274
275
    /**
276
     * @param Item $item
277
     *
278
     * @return bool
279
     */
280 20
    protected function isAFreeContentModeItemRecord(Item $item): bool
281
    {
282 20
        $languageField = $GLOBALS['TCA'][$item->getType()]['ctrl']['languageField'] ?? null;
283 20
        $itemRecord = $item->getRecord();
284 20
        return isset($languageField)
285 20
            && (int)($itemRecord[$languageField] ?? null) > 0
286 20
            && $this->isLanguageInAFreeContentMode($item, (int)($itemRecord[$languageField] ?? null));
287
    }
288
289
    /**
290
     * Gets the configuration how to process an item's fields for indexing.
291
     *
292
     * @param Item $item An index queue item
293
     * @param int $language Language ID
294
     * @return array Configuration array from TypoScript
295
     * @throws DBALDriverException
296
     */
297 20
    protected function getItemTypeConfiguration(Item $item, int $language = 0): array
298
    {
299 20
        $indexConfigurationName = $item->getIndexingConfigurationName();
300 20
        $fields = $this->getFieldConfigurationFromItemRecordPage($item, $language, $indexConfigurationName);
301 20
        if (!$this->isRootPageIdPartOfRootLine($item) || count($fields) === 0) {
302 2
            $fields = $this->getFieldConfigurationFromItemRootPage($item, $language, $indexConfigurationName);
303 2
            if (count($fields) === 0) {
304
                throw new RuntimeException('The item indexing configuration "' . $item->getIndexingConfigurationName() .
305
                    '" on root page uid ' . $item->getRootPageUid() . ' could not be found!', 1455530112);
306
            }
307
        }
308
309 20
        return $fields;
310
    }
311
312
    /**
313
     * The method retrieves the field configuration of the items record page id (pid).
314
     *
315
     * @param Item $item
316
     * @param int $language
317
     * @param string $indexConfigurationName
318
     * @return array
319
     */
320 20
    protected function getFieldConfigurationFromItemRecordPage(Item $item, int $language, string $indexConfigurationName): array
321
    {
322
        try {
323 20
            $pageId = $this->getPageIdOfItem($item);
324 20
            $solrConfiguration = $this->frontendEnvironment->getSolrConfigurationFromPageId($pageId, $language, $item->getRootPageUid());
325 20
            return $solrConfiguration->getIndexQueueFieldsConfigurationByConfigurationName($indexConfigurationName, []);
326
        } catch (Throwable $e) {
327
            return [];
328
        }
329
    }
330
331
    /**
332
     * @param Item $item
333
     * @return int
334
     */
335 20
    protected function getPageIdOfItem(Item $item): int
336
    {
337 20
        if ($item->getType() === 'pages') {
338 2
            return $item->getRecordUid();
339
        }
340 18
        return $item->getRecordPageId();
341
    }
342
343
    /**
344
     * The method returns the field configuration of the items root page id (uid of the related root page).
345
     *
346
     * @param Item $item
347
     * @param int $language
348
     * @param string $indexConfigurationName
349
     * @return array
350
     * @throws DBALDriverException
351
     */
352 2
    protected function getFieldConfigurationFromItemRootPage(Item $item, int $language, string $indexConfigurationName): array
353
    {
354 2
        $solrConfiguration = $this->frontendEnvironment->getSolrConfigurationFromPageId($item->getRootPageUid(), $language);
0 ignored issues
show
Bug introduced by
It seems like $item->getRootPageUid() can also be of type null; however, parameter $pageId of ApacheSolrForTypo3\Solr\...nfigurationFromPageId() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

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

354
        $solrConfiguration = $this->frontendEnvironment->getSolrConfigurationFromPageId(/** @scrutinizer ignore-type */ $item->getRootPageUid(), $language);
Loading history...
355
356 2
        return $solrConfiguration->getIndexQueueFieldsConfigurationByConfigurationName($indexConfigurationName, []);
357
    }
358
359
    /**
360
     * In case of additionalStoragePid config recordPageId can be outside siteroot.
361
     * In that case we should not read TS config of foreign siteroot.
362
     *
363
     * @param Item $item
364
     * @return bool
365
     */
366 20
    protected function isRootPageIdPartOfRootLine(Item $item): bool
367
    {
368 20
        $rootPageId = (int)$item->getRootPageUid();
369 20
        $buildRootlineWithPid = $this->getPageIdOfItem($item);
370 20
        $rootlineUtility = GeneralUtility::makeInstance(RootlineUtility::class, $buildRootlineWithPid);
371 20
        $rootline = $rootlineUtility->get();
372
373 20
        $pageInRootline = array_filter($rootline, function ($page) use ($rootPageId) {
374 20
            return (int)$page['uid'] === $rootPageId;
375
        });
376 20
        return !empty($pageInRootline);
377
    }
378
379
    /**
380
     * Converts an item array (record) to a Solr document by mapping the
381
     * record's fields onto Solr document fields as configured in TypoScript.
382
     *
383
     * @param Item $item An index queue item
384
     * @param int $language Language Id
385
     *
386
     * @return Document|null The Solr document converted from the record
387
     *
388
     * @throws DBALDriverException
389
     * @throws FrontendEnvironmentException
390
     * @throws SiteNotFoundException
391
     */
392 20
    protected function itemToDocument(Item $item, int $language = 0): ?Document
393
    {
394 20
        $document = null;
395
396 20
        $itemRecord = $this->getFullItemRecord($item, $language);
397 20
        if (!is_null($itemRecord)) {
398 20
            $itemIndexingConfiguration = $this->getItemTypeConfiguration($item, $language);
399 20
            $document = $this->getBaseDocument($item, $itemRecord);
400 20
            $pidToUse = $this->getPageIdOfItem($item);
401 20
            $tsfe = GeneralUtility::makeInstance(Tsfe::class)->getTsfeByPageIdAndLanguageId($pidToUse, $language, $item->getRootPageUid());
402 20
            $document = $this->addDocumentFieldsFromTyposcript($document, $itemIndexingConfiguration, $itemRecord, $tsfe);
403
        }
404
405 20
        return $document;
406
    }
407
408
    /**
409
     * Creates a Solr document with the basic / core fields set already.
410
     *
411
     * @param Item $item The item to index
412
     * @param array $itemRecord The record to use to build the base document
413
     * @return Document A basic Solr document
414
     */
415 20
    protected function getBaseDocument(Item $item, array $itemRecord): Document
416
    {
417 20
        $type = $item->getType();
418 20
        $rootPageUid = $item->getRootPageUid();
419 20
        $accessRootLine = $this->getAccessRootline($item);
420 20
        return $this->documentBuilder->fromRecord($itemRecord, $type, $rootPageUid, $accessRootLine);
0 ignored issues
show
Bug introduced by
It seems like $type can also be of type null; however, parameter $type of ApacheSolrForTypo3\Solr\...t\Builder::fromRecord() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

420
        return $this->documentBuilder->fromRecord($itemRecord, /** @scrutinizer ignore-type */ $type, $rootPageUid, $accessRootLine);
Loading history...
Bug introduced by
It seems like $rootPageUid can also be of type null; however, parameter $rootPageUid of ApacheSolrForTypo3\Solr\...t\Builder::fromRecord() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

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

420
        return $this->documentBuilder->fromRecord($itemRecord, $type, /** @scrutinizer ignore-type */ $rootPageUid, $accessRootLine);
Loading history...
421
    }
422
423
    /**
424
     * Generates an Access Rootline for an item.
425
     *
426
     * @param Item $item Index Queue item to index.
427
     * @return mixed|string The Access Rootline for the item
428
     */
429 20
    protected function getAccessRootline(Item $item)
430
    {
431 20
        $accessRestriction = '0';
432 20
        $itemRecord = $item->getRecord();
433
434
        // TODO support access restrictions set on storage page
435
436 20
        if (isset($GLOBALS['TCA'][$item->getType()]['ctrl']['enablecolumns']['fe_group'])) {
437 2
            $accessRestriction = $itemRecord[$GLOBALS['TCA'][$item->getType()]['ctrl']['enablecolumns']['fe_group']];
438
439 2
            if (empty($accessRestriction)) {
440
                // public
441 2
                $accessRestriction = '0';
442
            }
443
        }
444
445 20
        return 'r:' . $accessRestriction;
446
    }
447
448
    /**
449
     * Sends the documents to the field processing service which takes care of
450
     * manipulating fields as defined in the field's configuration.
451
     *
452
     * @param Item $item An index queue item
453
     * @param array $documents An array of \ApacheSolrForTypo3\Solr\System\Solr\Document\Document objects to manipulate.
454
     * @return Document[] An array of manipulated Document objects.
455
     * @throws DBALDriverException
456
     * @throws DBALException
457
     */
458 20
    protected function processDocuments(Item $item, array $documents): array
459
    {
460
//        // needs to respect the TS settings for the page the item is on, conditions may apply
461
//        $solrConfiguration = $this->frontendEnvironment->getSolrConfigurationFromPageId($item->getRootPageUid());
462
463 20
        $siteRepository = GeneralUtility::makeInstance(SiteRepository::class);
464 20
        $solrConfiguration = $siteRepository->getSiteByPageId($item->getRootPageUid())->getSolrConfiguration();
465 20
        $fieldProcessingInstructions = $solrConfiguration->getIndexFieldProcessingInstructionsConfiguration();
466
467
        // same as in the FE indexer
468 20
        if (is_array($fieldProcessingInstructions)) {
469 20
            $service = GeneralUtility::makeInstance(Service::class);
470 20
            $service->processDocuments($documents, $fieldProcessingInstructions);
471
        }
472
473 20
        return $documents;
474
    }
475
476
    /**
477
     * Allows third party extensions to provide additional documents which
478
     * should be indexed for the current item.
479
     *
480
     * @param Item $item The item currently being indexed.
481
     * @param int $language The language uid currently being indexed.
482
     * @param Document $itemDocument The document representing the item for the given language.
483
     * @return Document[] array An array of additional Document objects to index.
484
     */
485 24
    protected function getAdditionalDocuments(Item $item, int $language, Document $itemDocument): array
486
    {
487 24
        $documents = [];
488
489 24
        if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['IndexQueueIndexer']['indexItemAddDocuments'] ?? null)) {
490 4
            foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['IndexQueueIndexer']['indexItemAddDocuments'] as $classReference) {
491 4
                if (!class_exists($classReference)) {
492 2
                    throw new InvalidArgumentException('Class does not exits' . $classReference, 1490363487);
493
                }
494 2
                $additionalIndexer = GeneralUtility::makeInstance($classReference);
495 2
                if ($additionalIndexer instanceof AdditionalIndexQueueItemIndexer) {
496 1
                    $additionalDocuments = $additionalIndexer->getAdditionalItemDocuments($item, $language, $itemDocument);
497
498 1
                    if (is_array($additionalDocuments)) {
499 1
                        $documents = array_merge(
500
                            $documents,
501
                            $additionalDocuments
502
                        );
503
                    }
504
                } else {
505 1
                    throw new UnexpectedValueException(
506 1
                        get_class($additionalIndexer) . ' must implement interface ' . AdditionalIndexQueueItemIndexer::class,
507
                        1326284551
508
                    );
509
                }
510
            }
511
        }
512 21
        return $documents;
513
    }
514
515
    /**
516
     * Provides a hook to manipulate documents right before they get added to
517
     * the Solr index.
518
     *
519
     * @param Item $item The item currently being indexed.
520
     * @param int $language The language uid of the documents
521
     * @param array $documents An array of documents to be indexed
522
     * @return array An array of modified documents
523
     */
524 20
    protected function preAddModifyDocuments(Item $item, int $language, array $documents): array
525
    {
526 20
        if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['IndexQueueIndexer']['preAddModifyDocuments'] ?? null)) {
527
            foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['IndexQueueIndexer']['preAddModifyDocuments'] as $classReference) {
528
                $documentsModifier = GeneralUtility::makeInstance($classReference);
529
530
                if ($documentsModifier instanceof PageIndexerDocumentsModifier) {
531
                    $documents = $documentsModifier->modifyDocuments($item, $language, $documents);
532
                } else {
533
                    throw new RuntimeException(
534
                        'The class "' . get_class($documentsModifier)
535
                        . '" registered as document modifier in hook
536
							preAddModifyDocuments must implement interface
537
							ApacheSolrForTypo3\Solr\IndexQueue\PageIndexerDocumentsModifier',
538
                        1309522677
539
                    );
540
                }
541
            }
542
        }
543
544 20
        return $documents;
545
    }
546
547
    // Initialization
548
549
    /**
550
     * Gets the Solr connections applicable for an item.
551
     *
552
     * The connections include the default connection and connections to be used
553
     * for translations of an item.
554
     *
555
     * @param Item $item An index queue item
556
     * @return array An array of ApacheSolrForTypo3\Solr\System\Solr\SolrConnection connections, the array's keys are the sys_language_uid of the language of the connection
557
     * @throws DBALDriverException
558
     * @throws NoSolrConnectionFoundException
559
     */
560 23
    protected function getSolrConnectionsByItem(Item $item): array
561
    {
562 23
        $solrConnections = [];
563
564 23
        $rootPageId = $item->getRootPageUid();
565 23
        if ($item->getType() === 'pages') {
566 4
            $pageId = $item->getRecordUid();
567
        } else {
568 19
            $pageId = $item->getRecordPageId();
569
        }
570
571
        // Solr configurations possible for this item
572 23
        $site = $item->getSite();
573 23
        $solrConfigurationsBySite = $site->getAllSolrConnectionConfigurations();
574 23
        $siteLanguages = [];
575 23
        foreach ($solrConfigurationsBySite as $solrConfiguration) {
576 23
            $siteLanguages[] = $solrConfiguration['language'];
577
        }
578
579 23
        $defaultLanguageUid = $this->getDefaultLanguageUid($item, $site->getRootPage(), $siteLanguages);
580 23
        $translationOverlays = $this->getTranslationOverlaysWithConfiguredSite((int)$pageId, $site, $siteLanguages);
0 ignored issues
show
Bug introduced by
It seems like $site can also be of type null; however, parameter $site of ApacheSolrForTypo3\Solr\...aysWithConfiguredSite() does only seem to accept ApacheSolrForTypo3\Solr\Domain\Site\Site, maybe add an additional type check? ( Ignorable by Annotation )

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

580
        $translationOverlays = $this->getTranslationOverlaysWithConfiguredSite((int)$pageId, /** @scrutinizer ignore-type */ $site, $siteLanguages);
Loading history...
581
582 23
        $defaultConnection = $this->connectionManager->getConnectionByPageId($rootPageId, $defaultLanguageUid, $item->getMountPointIdentifier() ?? '');
0 ignored issues
show
Bug introduced by
It seems like $rootPageId can also be of type null; however, parameter $pageId of ApacheSolrForTypo3\Solr\...getConnectionByPageId() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

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

582
        $defaultConnection = $this->connectionManager->getConnectionByPageId(/** @scrutinizer ignore-type */ $rootPageId, $defaultLanguageUid, $item->getMountPointIdentifier() ?? '');
Loading history...
583 23
        $translationConnections = $this->getConnectionsForIndexableLanguages($translationOverlays);
584
585 23
        if ($defaultLanguageUid == 0) {
586 21
            $solrConnections[0] = $defaultConnection;
587
        }
588
589 23
        foreach ($translationConnections as $systemLanguageUid => $solrConnection) {
590 20
            $solrConnections[$systemLanguageUid] = $solrConnection;
591
        }
592 23
        return $solrConnections;
593
    }
594
595
    /**
596
     * @param int $pageId
597
     * @param Site $site
598
     * @param array $siteLanguages
599
     * @return array
600
     */
601 23
    protected function getTranslationOverlaysWithConfiguredSite(int $pageId, Site $site, array $siteLanguages): array
602
    {
603 23
        $translationOverlays = $this->pagesRepository->findTranslationOverlaysByPageId($pageId);
604 23
        $translatedLanguages = [];
605 23
        foreach ($translationOverlays as $key => $translationOverlay) {
606 6
            if (!in_array($translationOverlay['sys_language_uid'], $siteLanguages)) {
607
                unset($translationOverlays[$key]);
608
            } else {
609 6
                $translatedLanguages[] = (int)$translationOverlay['sys_language_uid'];
610
            }
611
        }
612
613 23
        if (count($translationOverlays) + 1 !== count($siteLanguages)) {
614
            // not all Languages are translated
615
            // add Language Fallback
616 22
            foreach ($siteLanguages as $languageId) {
617 22
                if ($languageId !== 0 && !in_array((int)$languageId, $translatedLanguages, true)) {
618 22
                    $fallbackLanguageIds = $this->getFallbackOrder($site, (int)$languageId);
619 22
                    foreach ($fallbackLanguageIds as $fallbackLanguageId) {
620 21
                        if ($fallbackLanguageId === 0 || in_array((int)$fallbackLanguageId, $translatedLanguages, true)) {
621 15
                            $translationOverlay = [
622
                                'pid' => $pageId,
623
                                'sys_language_uid' => $languageId,
624
                                'l10n_parent' => $pageId,
625
                            ];
626 15
                            $translationOverlays[] = $translationOverlay;
627 15
                            continue 2;
628
                        }
629
                    }
630
                }
631
            }
632
        }
633 23
        return $translationOverlays;
634
    }
635
636
    /**
637
     * @param Site $site
638
     * @param int $languageId
639
     * @return array
640
     */
641 22
    protected function getFallbackOrder(Site $site, int $languageId): array
642
    {
643 22
        $fallbackChain = [];
644 22
        $siteFinder = GeneralUtility::makeInstance(SiteFinder::class);
645
        try {
646 22
            $site = $siteFinder->getSiteByRootPageId($site->getRootPageId());
647 21
            $languageAspect = LanguageAspectFactory::createFromSiteLanguage($site->getLanguageById($languageId));
648 21
            $fallbackChain = $languageAspect->getFallbackChain();
649 1
        } catch (SiteNotFoundException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
650
        }
651 22
        return $fallbackChain;
652
    }
653
654
    /**
655
     * @param Item $item An index queue item
656
     * @param array $rootPage
657
     * @param array $siteLanguages
658
     *
659
     * @return int
660
     * @throws RuntimeException
661
     */
662 23
    protected function getDefaultLanguageUid(Item $item, array $rootPage, array $siteLanguages): int
663
    {
664 23
        $defaultLanguageUid = 0;
665 23
        if (($rootPage['l18n_cfg'] & 1) == 1 && count($siteLanguages) == 1 && $siteLanguages[min(array_keys($siteLanguages))] > 0) {
666
            $defaultLanguageUid = $siteLanguages[min(array_keys($siteLanguages))];
667 23
        } elseif (($rootPage['l18n_cfg'] & 1) == 1 && count($siteLanguages) > 1) {
668 2
            unset($siteLanguages[array_search('0', $siteLanguages)]);
669 2
            $defaultLanguageUid = $siteLanguages[min(array_keys($siteLanguages))];
670 21
        } elseif (($rootPage['l18n_cfg'] & 1) == 1 && count($siteLanguages) == 1) {
671
            $message = 'Root page ' . (int)$item->getRootPageUid() . ' is set to hide default translation, but no other language is configured!';
672
            throw new RuntimeException($message);
673
        }
674
675 23
        return $defaultLanguageUid;
676
    }
677
678
    /**
679
     * Checks for which languages connections have been configured and returns
680
     * these connections.
681
     *
682
     * @param array $translationOverlays An array of translation overlays to check for configured connections.
683
     * @return array An array of ApacheSolrForTypo3\Solr\System\Solr\SolrConnection connections.
684
     * @throws DBALDriverException
685
     */
686 23
    protected function getConnectionsForIndexableLanguages(array $translationOverlays): array
687
    {
688 23
        $connections = [];
689
690 23
        foreach ($translationOverlays as $translationOverlay) {
691 21
            $pageId = $translationOverlay['l10n_parent'];
692 21
            $languageId = $translationOverlay['sys_language_uid'];
693
694
            try {
695 21
                $connection = $this->connectionManager->getConnectionByPageId($pageId, $languageId);
696 20
                $connections[$languageId] = $connection;
697 1
            } catch (NoSolrConnectionFoundException $e) {
698
                // ignore the exception as we seek only those connections
699
                // actually available
700
            }
701
        }
702
703 23
        return $connections;
704
    }
705
706
    // Utility methods
707
708
    // FIXME extract log() and setLogging() to ApacheSolrForTypo3\Solr\IndexQueue\AbstractIndexer
709
    // FIXME extract an interface Tx_Solr_IndexQueue_ItemInterface
710
711
    /**
712
     * Enables logging dependent on the configuration of the item's site
713
     *
714
     * @param Item $item An item being indexed
715
     * @throws DBALDriverException
716
     */
717 21
    protected function setLogging(Item $item)
718
    {
719 21
        $solrConfiguration = $this->frontendEnvironment->getSolrConfigurationFromPageId($item->getRootPageUid());
0 ignored issues
show
Bug introduced by
It seems like $item->getRootPageUid() can also be of type null; however, parameter $pageId of ApacheSolrForTypo3\Solr\...nfigurationFromPageId() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

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

719
        $solrConfiguration = $this->frontendEnvironment->getSolrConfigurationFromPageId(/** @scrutinizer ignore-type */ $item->getRootPageUid());
Loading history...
720 21
        $this->loggingEnabled = $solrConfiguration->getLoggingIndexingQueueOperationsByConfigurationNameWithFallBack(
721 21
            $item->getIndexingConfigurationName()
722
        );
723
    }
724
725
    /**
726
     * Logs the item and what document was created from it
727
     *
728
     * @param Item $item The item that is being indexed.
729
     * @param array $itemDocuments An array of Solr documents created from the item's data
730
     * @param ResponseAdapter $response The Solr response for the particular index document
731
     */
732 20
    protected function log(Item $item, array $itemDocuments, ResponseAdapter $response)
733
    {
734 20
        if (!$this->loggingEnabled) {
735 20
            return;
736
        }
737
738
        $message = 'Index Queue indexing ' . $item->getType() . ':' . $item->getRecordUid() . ' - ';
739
740
        // preparing data
741
        $documents = [];
742
        foreach ($itemDocuments as $document) {
743
            $documents[] = (array)$document;
744
        }
745
746
        $logData = ['item' => (array)$item, 'documents' => $documents, 'response' => (array)$response];
747
748
        if ($response->getHttpStatus() == 200) {
749
            $severity = SolrLogManager::NOTICE;
750
            $message .= 'Success';
751
        } else {
752
            $severity = SolrLogManager::ERROR;
753
            $message .= 'Failure';
754
755
            $logData['status'] = $response->getHttpStatus();
756
            $logData['status message'] = $response->getHttpStatusMessage();
757
        }
758
759
        $this->logger->log($severity, $message, $logData);
760
    }
761
762
    /**
763
     * Returns the language field from given table or null
764
     *
765
     * @param string $tableName
766
     * @return string|null
767
     */
768
    protected function getLanguageFieldFromTable(string $tableName): ?string
769
    {
770
        $tableControl = $GLOBALS['TCA'][$tableName]['ctrl'] ?? [];
771
772
        if (!empty($tableControl['languageField'])) {
773
            return $tableControl['languageField'];
774
        }
775
776
        return null;
777
    }
778
779
    /**
780
     * Checks the given language, if it is in "free" mode.
781
     *
782
     * @param Item $item
783
     * @param int $language
784
     * @return bool
785
     */
786 20
    protected function isLanguageInAFreeContentMode(Item $item, int $language): bool
787
    {
788 20
        if ($language === 0) {
789 20
            return false;
790
        }
791 18
        $typo3site = $item->getSite()->getTypo3SiteObject();
792 18
        $typo3siteLanguage = $typo3site->getLanguageById($language);
793 18
        $typo3siteLanguageFallbackType = $typo3siteLanguage->getFallbackType();
794 18
        if ($typo3siteLanguageFallbackType === 'free') {
795
            return true;
796
        }
797 18
        return false;
798
    }
799
}
800