Passed
Branch main (7dbc49)
by Rafael
04:08
created

Indexer   F

Complexity

Total Complexity 88

Size/Duplication

Total Lines 752
Duplicated Lines 0 %

Test Coverage

Coverage 83.33%

Importance

Changes 5
Bugs 1 Features 0
Metric Value
wmc 88
eloc 250
c 5
b 1
f 0
dl 0
loc 752
ccs 205
cts 246
cp 0.8333
rs 2

26 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 14 1
A index() 0 25 3
A getFullItemRecord() 0 9 2
B getItemRecordOverlayed() 0 24 7
A isAFreeContentModeItemRecord() 0 17 5
A getSolrConnectionsByItem() 0 33 5
A getPageIdOfItem() 0 6 2
A preAddModifyDocuments() 0 21 4
A getBaseDocument() 0 6 1
A getItemTypeConfiguration() 0 13 4
A getAdditionalDocuments() 0 28 6
A getFieldConfigurationFromItemRootPage() 0 5 1
A isRootPageIdPartOfRootLine() 0 11 1
A isLanguageInAFreeContentMode() 0 12 3
A itemToDocument() 0 14 2
A getFallbackOrder() 0 11 2
A getFieldConfigurationFromItemRecordPage() 0 8 2
A getLanguageFieldFromTable() 0 9 2
A getAccessRootline() 0 17 3
A setLogging() 0 5 1
A processDocuments() 0 16 2
A log() 0 28 4
B getTranslationOverlaysWithConfiguredSite() 0 33 10
A indexItem() 0 33 4
A getConnectionsForIndexableLanguages() 0 18 3
B getDefaultLanguageUid() 0 14 8

How to fix   Complexity   

Complex Class

Complex classes like Indexer often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Indexer, and based on these observations, apply Extract Interface, too.

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
285 20
        $l10nParentField = $GLOBALS['TCA'][$item->getType()]['ctrl']['transOrigPointerField'] ?? null;
286 20
        if ($languageField === null || $l10nParentField === null) {
287
            return true;
288
        }
289 20
        $languageOfRecord = (int)($itemRecord[$languageField] ?? null);
290 20
        $l10nParentRecordUid = (int)($itemRecord[$l10nParentField] ?? null);
291
292 20
        if ($languageOfRecord > 0 && $l10nParentRecordUid === 0) {
293
            return true;
294
        }
295
296 20
        return false;
297
    }
298
299
    /**
300
     * Gets the configuration how to process an item's fields for indexing.
301
     *
302
     * @param Item $item An index queue item
303
     * @param int $language Language ID
304
     * @return array Configuration array from TypoScript
305
     * @throws DBALDriverException
306
     */
307 20
    protected function getItemTypeConfiguration(Item $item, int $language = 0): array
308
    {
309 20
        $indexConfigurationName = $item->getIndexingConfigurationName();
310 20
        $fields = $this->getFieldConfigurationFromItemRecordPage($item, $language, $indexConfigurationName);
311 20
        if (!$this->isRootPageIdPartOfRootLine($item) || count($fields) === 0) {
312 2
            $fields = $this->getFieldConfigurationFromItemRootPage($item, $language, $indexConfigurationName);
313 2
            if (count($fields) === 0) {
314
                throw new RuntimeException('The item indexing configuration "' . $item->getIndexingConfigurationName() .
315
                    '" on root page uid ' . $item->getRootPageUid() . ' could not be found!', 1455530112);
316
            }
317
        }
318
319 20
        return $fields;
320
    }
321
322
    /**
323
     * The method retrieves the field configuration of the items record page id (pid).
324
     *
325
     * @param Item $item
326
     * @param int $language
327
     * @param string $indexConfigurationName
328
     * @return array
329
     */
330 20
    protected function getFieldConfigurationFromItemRecordPage(Item $item, int $language, string $indexConfigurationName): array
331
    {
332
        try {
333 20
            $pageId = $this->getPageIdOfItem($item);
334 20
            $solrConfiguration = $this->frontendEnvironment->getSolrConfigurationFromPageId($pageId, $language, $item->getRootPageUid());
335 20
            return $solrConfiguration->getIndexQueueFieldsConfigurationByConfigurationName($indexConfigurationName, []);
336
        } catch (Throwable $e) {
337
            return [];
338
        }
339
    }
340
341
    /**
342
     * @param Item $item
343
     * @return int
344
     */
345 20
    protected function getPageIdOfItem(Item $item): int
346
    {
347 20
        if ($item->getType() === 'pages') {
348 2
            return $item->getRecordUid();
349
        }
350 18
        return $item->getRecordPageId();
351
    }
352
353
    /**
354
     * The method returns the field configuration of the items root page id (uid of the related root page).
355
     *
356
     * @param Item $item
357
     * @param int $language
358
     * @param string $indexConfigurationName
359
     * @return array
360
     * @throws DBALDriverException
361
     */
362 2
    protected function getFieldConfigurationFromItemRootPage(Item $item, int $language, string $indexConfigurationName): array
363
    {
364 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

364
        $solrConfiguration = $this->frontendEnvironment->getSolrConfigurationFromPageId(/** @scrutinizer ignore-type */ $item->getRootPageUid(), $language);
Loading history...
365
366 2
        return $solrConfiguration->getIndexQueueFieldsConfigurationByConfigurationName($indexConfigurationName, []);
367
    }
368
369
    /**
370
     * In case of additionalStoragePid config recordPageId can be outside siteroot.
371
     * In that case we should not read TS config of foreign siteroot.
372
     *
373
     * @param Item $item
374
     * @return bool
375
     */
376 20
    protected function isRootPageIdPartOfRootLine(Item $item): bool
377
    {
378 20
        $rootPageId = (int)$item->getRootPageUid();
379 20
        $buildRootlineWithPid = $this->getPageIdOfItem($item);
380 20
        $rootlineUtility = GeneralUtility::makeInstance(RootlineUtility::class, $buildRootlineWithPid);
381 20
        $rootline = $rootlineUtility->get();
382
383 20
        $pageInRootline = array_filter($rootline, function ($page) use ($rootPageId) {
384 20
            return (int)$page['uid'] === $rootPageId;
385
        });
386 20
        return !empty($pageInRootline);
387
    }
388
389
    /**
390
     * Converts an item array (record) to a Solr document by mapping the
391
     * record's fields onto Solr document fields as configured in TypoScript.
392
     *
393
     * @param Item $item An index queue item
394
     * @param int $language Language Id
395
     *
396
     * @return Document|null The Solr document converted from the record
397
     *
398
     * @throws DBALDriverException
399
     * @throws FrontendEnvironmentException
400
     * @throws SiteNotFoundException
401
     */
402 20
    protected function itemToDocument(Item $item, int $language = 0): ?Document
403
    {
404 20
        $document = null;
405
406 20
        $itemRecord = $this->getFullItemRecord($item, $language);
407 20
        if (!is_null($itemRecord)) {
408 20
            $itemIndexingConfiguration = $this->getItemTypeConfiguration($item, $language);
409 20
            $document = $this->getBaseDocument($item, $itemRecord);
410 20
            $pidToUse = $this->getPageIdOfItem($item);
411 20
            $tsfe = GeneralUtility::makeInstance(Tsfe::class)->getTsfeByPageIdAndLanguageId($pidToUse, $language, $item->getRootPageUid());
412 20
            $document = $this->addDocumentFieldsFromTyposcript($document, $itemIndexingConfiguration, $itemRecord, $tsfe);
413
        }
414
415 20
        return $document;
416
    }
417
418
    /**
419
     * Creates a Solr document with the basic / core fields set already.
420
     *
421
     * @param Item $item The item to index
422
     * @param array $itemRecord The record to use to build the base document
423
     * @return Document A basic Solr document
424
     */
425 20
    protected function getBaseDocument(Item $item, array $itemRecord): Document
426
    {
427 20
        $type = $item->getType();
428 20
        $rootPageUid = $item->getRootPageUid();
429 20
        $accessRootLine = $this->getAccessRootline($item);
430 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

430
        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

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

590
        $translationOverlays = $this->getTranslationOverlaysWithConfiguredSite((int)$pageId, /** @scrutinizer ignore-type */ $site, $siteLanguages);
Loading history...
591
592 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

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

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