Passed
Push — release-11.5.x ( 282d0d...a0b867 )
by Rafael
36:25
created

getTranslationOverlaysWithConfiguredSite()   B

Complexity

Conditions 10
Paths 6

Size

Total Lines 33
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 10.0107

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 20
dl 0
loc 33
ccs 20
cts 21
cp 0.9524
rs 7.6666
c 1
b 1
f 0
cc 10
nc 6
nop 3
crap 10.0107

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\IndexQueue\Exception\IndexingException;
29
use ApacheSolrForTypo3\Solr\NoSolrConnectionFoundException;
30
use ApacheSolrForTypo3\Solr\System\Logging\SolrLogManager;
31
use ApacheSolrForTypo3\Solr\System\Records\Pages\PagesRepository;
32
use ApacheSolrForTypo3\Solr\System\Solr\Document\Document;
33
use ApacheSolrForTypo3\Solr\System\Solr\ResponseAdapter;
34
use ApacheSolrForTypo3\Solr\System\Solr\SolrConnection;
35
use Doctrine\DBAL\Driver\Exception as DBALDriverException;
36
use Doctrine\DBAL\Exception as DBALException;
37
use InvalidArgumentException;
38
use RuntimeException;
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 51
    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 51
        $this->options = $options;
123 51
        $this->pagesRepository = $pagesRepository ?? GeneralUtility::makeInstance(PagesRepository::class);
124 51
        $this->documentBuilder = $documentBuilder ?? GeneralUtility::makeInstance(Builder::class);
125 51
        $this->logger = $logger ?? GeneralUtility::makeInstance(SolrLogManager::class, /** @scrutinizer ignore-type */ __CLASS__);
126 51
        $this->connectionManager = $connectionManager ?? GeneralUtility::makeInstance(ConnectionManager::class);
127 51
        $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 IndexingException
178
     * @throws SiteNotFoundException
179
     */
180 22
    protected function indexItem(Item $item, int $language = 0): bool
181
    {
182 22
        $documents = [];
183
184 22
        $itemDocument = $this->itemToDocument($item, $language);
185 22
        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 22
        $documents[] = $itemDocument;
196 22
        $documents = array_merge($documents, $this->getAdditionalDocuments($item, $language, $itemDocument));
197 22
        $documents = $this->processDocuments($item, $documents);
198 22
        $documents = self::preAddModifyDocuments($item, $language, $documents);
199
200 22
        $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

200
        $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...
201 22
        if ($response->getHttpStatus() !== 200) {
202 1
            $responseData = json_decode($response->getRawResponse() ?? '', true);
203 1
            throw new IndexingException(
204 1
                $response->getHttpStatusMessage() . ': ' . ($responseData['error']['msg'] ?? $response->getHttpStatus()),
205 1
                1678693955
206 1
            );
207
        }
208
209 21
        $this->log($item, $documents, $response);
210
211 21
        return true;
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 20
            && 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 20
            && isset($languageField)
263 20
            && (int)($itemRecord[$languageField] ?? null) !== $language
264
        ) {
265
            return null;
266
        }
267
        // skip translated records for default language within "free content mode"-languages
268 20
        if ($language === 0
269 20
            && isset($languageField)
270 20
            && (int)($itemRecord[$languageField] ?? null) !== $language
271 20
            && $this->isLanguageInAFreeContentMode($item, (int)($itemRecord[$languageField] ?? null))
272
        ) {
273
            return null;
274
        }
275
276 20
        $pidToUse = $this->getPageIdOfItem($item);
277
278 20
        return GeneralUtility::makeInstance(Tsfe::class)
279 20
            ->getTsfeByPageIdAndLanguageId($pidToUse, $language, $item->getRootPageUid())
280 20
            ->sys_page->getLanguageOverlay($item->getType(), $itemRecord);
281
    }
282
283
    /**
284
     * @param Item $item
285
     *
286
     * @return bool
287
     */
288 20
    protected function isAFreeContentModeItemRecord(Item $item): bool
289
    {
290 20
        $languageField = $GLOBALS['TCA'][$item->getType()]['ctrl']['languageField'] ?? null;
291 20
        $itemRecord = $item->getRecord();
292
293 20
        $l10nParentField = $GLOBALS['TCA'][$item->getType()]['ctrl']['transOrigPointerField'] ?? null;
294 20
        if ($languageField === null || $l10nParentField === null) {
295
            return true;
296
        }
297 20
        $languageOfRecord = (int)($itemRecord[$languageField] ?? null);
298 20
        $l10nParentRecordUid = (int)($itemRecord[$l10nParentField] ?? null);
299
300 20
        if ($languageOfRecord > 0 && $l10nParentRecordUid === 0) {
301
            return true;
302
        }
303
304 20
        return false;
305
    }
306
307
    /**
308
     * Gets the configuration how to process an item's fields for indexing.
309
     *
310
     * @param Item $item An index queue item
311
     * @param int $language Language ID
312
     * @return array Configuration array from TypoScript
313
     * @throws DBALDriverException
314
     */
315 20
    protected function getItemTypeConfiguration(Item $item, int $language = 0): array
316
    {
317 20
        $indexConfigurationName = $item->getIndexingConfigurationName();
318 20
        $fields = $this->getFieldConfigurationFromItemRecordPage($item, $language, $indexConfigurationName);
319 20
        if (!$this->isRootPageIdPartOfRootLine($item) || count($fields) === 0) {
320 2
            $fields = $this->getFieldConfigurationFromItemRootPage($item, $language, $indexConfigurationName);
321 2
            if (count($fields) === 0) {
322
                throw new RuntimeException('The item indexing configuration "' . $item->getIndexingConfigurationName() .
323
                    '" on root page uid ' . $item->getRootPageUid() . ' could not be found!', 1455530112);
324
            }
325
        }
326
327 20
        return $fields;
328
    }
329
330
    /**
331
     * The method retrieves the field configuration of the items record page id (pid).
332
     *
333
     * @param Item $item
334
     * @param int $language
335
     * @param string $indexConfigurationName
336
     * @return array
337
     */
338 20
    protected function getFieldConfigurationFromItemRecordPage(Item $item, int $language, string $indexConfigurationName): array
339
    {
340
        try {
341 20
            $pageId = $this->getPageIdOfItem($item);
342 20
            $solrConfiguration = $this->frontendEnvironment->getSolrConfigurationFromPageId($pageId, $language, $item->getRootPageUid());
343 20
            return $solrConfiguration->getIndexQueueFieldsConfigurationByConfigurationName($indexConfigurationName, []);
344
        } catch (Throwable $e) {
345
            return [];
346
        }
347
    }
348
349
    /**
350
     * @param Item $item
351
     * @return int
352
     */
353 20
    protected function getPageIdOfItem(Item $item): int
354
    {
355 20
        if ($item->getType() === 'pages') {
356 2
            return $item->getRecordUid();
357
        }
358 18
        return $item->getRecordPageId();
359
    }
360
361
    /**
362
     * The method returns the field configuration of the items root page id (uid of the related root page).
363
     *
364
     * @param Item $item
365
     * @param int $language
366
     * @param string $indexConfigurationName
367
     * @return array
368
     * @throws DBALDriverException
369
     */
370 2
    protected function getFieldConfigurationFromItemRootPage(Item $item, int $language, string $indexConfigurationName): array
371
    {
372 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

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

438
        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

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

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

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

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