Passed
Pull Request — main (#3596)
by
unknown
45:38
created

Queue::addNewItem()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 21
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 5.0488

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 21
ccs 7
cts 8
cp 0.875
rs 9.6111
c 0
b 0
f 0
cc 5
nc 4
nop 5
crap 5.0488
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\Domain\Index\Queue\QueueInitializationService;
21
use ApacheSolrForTypo3\Solr\Domain\Index\Queue\QueueItemRepository;
22
use ApacheSolrForTypo3\Solr\Domain\Index\Queue\RecordMonitor\Exception\RootPageRecordNotFoundException;
23
use ApacheSolrForTypo3\Solr\Domain\Index\Queue\RecordMonitor\Helper\ConfigurationAwareRecordService;
24
use ApacheSolrForTypo3\Solr\Domain\Index\Queue\RecordMonitor\Helper\RootPageResolver;
25
use ApacheSolrForTypo3\Solr\Domain\Index\Queue\Statistic\QueueStatistic;
26
use ApacheSolrForTypo3\Solr\Domain\Index\Queue\Statistic\QueueStatisticsRepository;
27
use ApacheSolrForTypo3\Solr\Domain\Site\Site;
28
use ApacheSolrForTypo3\Solr\Domain\Site\SiteRepository;
29
use ApacheSolrForTypo3\Solr\FrontendEnvironment;
30
use ApacheSolrForTypo3\Solr\System\Cache\TwoLevelCache;
31
use ApacheSolrForTypo3\Solr\System\Logging\SolrLogManager;
32
use Doctrine\DBAL\ConnectionException;
33
use Doctrine\DBAL\Driver\Exception as DBALDriverException;
34
use Doctrine\DBAL\Exception as DBALException;
35
use Throwable;
36
use TYPO3\CMS\Backend\Utility\BackendUtility;
37
use TYPO3\CMS\Core\Utility\GeneralUtility;
38
39
/**
40
 * The Indexing Queue. It allows us to decouple from frontend indexing and
41
 * reacting to the changes faster.
42
 *
43
 * @author Ingo Renner <[email protected]>
44
 */
45
class Queue
46
{
47
    /**
48
     * @var RootPageResolver
49
     */
50
    protected RootPageResolver $rootPageResolver;
51
52
    /**
53
     * @var ConfigurationAwareRecordService
54
     */
55
    protected ConfigurationAwareRecordService $recordService;
56
57
    /**
58
     * @var SolrLogManager
59
     */
60
    protected SolrLogManager $logger;
61
62
    /**
63
     * @var QueueItemRepository
64
     */
65
    protected QueueItemRepository $queueItemRepository;
66
67
    /**
68
     * @var QueueStatisticsRepository
69
     */
70
    protected QueueStatisticsRepository $queueStatisticsRepository;
71
72
    /**
73
     * @var QueueInitializationService
74
     */
75
    protected QueueInitializationService $queueInitializationService;
76
77
    /**
78
     * @var FrontendEnvironment
79
     */
80
    protected FrontendEnvironment $frontendEnvironment;
81
82
    /**
83
     * Queue constructor.
84
     * @param RootPageResolver|null $rootPageResolver
85
     * @param ConfigurationAwareRecordService|null $recordService
86
     * @param QueueItemRepository|null $queueItemRepository
87
     * @param QueueStatisticsRepository|null $queueStatisticsRepository
88
     * @param QueueInitializationService|null $queueInitializationService
89
     */
90 156
    public function __construct(
91
        RootPageResolver $rootPageResolver = null,
92
        ConfigurationAwareRecordService $recordService = null,
93
        QueueItemRepository $queueItemRepository = null,
94
        QueueStatisticsRepository $queueStatisticsRepository = null,
95
        QueueInitializationService $queueInitializationService = null,
96
        FrontendEnvironment $frontendEnvironment = null
97
    ) {
98 156
        $this->logger = GeneralUtility::makeInstance(SolrLogManager::class, /** @scrutinizer ignore-type */ __CLASS__);
99 156
        $this->rootPageResolver = $rootPageResolver ?? GeneralUtility::makeInstance(RootPageResolver::class);
100 156
        $this->recordService = $recordService ?? GeneralUtility::makeInstance(ConfigurationAwareRecordService::class);
101 156
        $this->queueItemRepository = $queueItemRepository ?? GeneralUtility::makeInstance(QueueItemRepository::class);
102 156
        $this->queueStatisticsRepository = $queueStatisticsRepository ??  GeneralUtility::makeInstance(QueueStatisticsRepository::class);
103 156
        $this->queueInitializationService = $queueInitializationService ?? GeneralUtility::makeInstance(QueueInitializationService::class, /** @scrutinizer ignore-type */ $this);
104 156
        $this->frontendEnvironment = $frontendEnvironment ?? GeneralUtility::makeInstance(FrontendEnvironment::class);
105
    }
106
107
    // FIXME some of the methods should be renamed to plural forms
108
    // FIXME singular form methods should deal with exactly one item only
109
110
    /**
111
     * Returns the timestamp of the last indexing run.
112
     *
113
     * @param int $rootPageId The root page uid for which to get
114
     *      the last indexed item id
115
     * @return int Timestamp of last index run.
116
     * @throws DBALDriverException
117
     * @throws DBALException|\Doctrine\DBAL\DBALException
118
     */
119 2
    public function getLastIndexTime(int $rootPageId): int
120
    {
121 2
        $lastIndexTime = 0;
122
123 2
        $lastIndexedRow = $this->queueItemRepository->findLastIndexedRow($rootPageId);
124
125 2
        if ($lastIndexedRow[0]['indexed']) {
126 1
            $lastIndexTime = $lastIndexedRow[0]['indexed'];
127
        }
128
129 2
        return $lastIndexTime;
130
    }
131
132
    /**
133
     * Returns the uid of the last indexed item in the queue
134
     *
135
     * @param int $rootPageId The root page uid for which to get
136
     *      the last indexed item id
137
     * @return int The last indexed item's ID.
138
     * @throws DBALDriverException
139
     * @throws DBALException|\Doctrine\DBAL\DBALException
140
     */
141 3
    public function getLastIndexedItemId(int $rootPageId): int
142
    {
143 3
        $lastIndexedItemId = 0;
144
145 3
        $lastIndexedItemRow = $this->queueItemRepository->findLastIndexedRow($rootPageId);
146 3
        if ($lastIndexedItemRow[0]['uid']) {
147 2
            $lastIndexedItemId = $lastIndexedItemRow[0]['uid'];
148
        }
149
150 3
        return $lastIndexedItemId;
151
    }
152
153
    /**
154
     * @return QueueInitializationService
155
     */
156 6
    public function getInitializationService(): QueueInitializationService
157
    {
158 6
        return $this->queueInitializationService;
159
    }
160
161
    /**
162
     * Marks an item as needing (re)indexing.
163
     *
164
     * Like with Solr itself, there's no add method, just a simple update method
165
     * that handles the adds, too.
166
     *
167
     * The method creates or updates the index queue items for all related rootPageIds.
168
     *
169
     * @param string $itemType The item's type, usually a table name.
170
     * @param int|string $itemUid The item's uid, usually an integer uid, could be a different value for non-database-record types.
171
     * @param int $forcedChangeTime The change time for the item if set, otherwise value from getItemChangedTime() is used.
172
     * @return int Number of updated/created items
173
     * @throws DBALDriverException
174
     * @throws DBALException|\Doctrine\DBAL\DBALException
175
     * @throws Throwable
176
     */
177 94
    public function updateItem(string $itemType, $itemUid, int $forcedChangeTime = 0): int
178
    {
179 94
        $updateCount = $this->updateOrAddItemForAllRelatedRootPages($itemType, $itemUid, $forcedChangeTime);
180 94
        return $this->postProcessIndexQueueUpdateItem($itemType, $itemUid, $updateCount, $forcedChangeTime);
181
    }
182
183
    /**
184
     * Updates or adds the item for all relevant root pages.
185
     *
186
     * @param string $itemType The item's type, usually a table name.
187
     * @param int|string $itemUid The item's uid, usually an integer uid, could be a different value for non-database-record types.
188
     * @param int $forcedChangeTime The change time for the item if set, otherwise value from getItemChangedTime() is used.
189
     * @return int
190
     * @throws DBALDriverException
191
     * @throws DBALException|\Doctrine\DBAL\DBALException
192
     * @throws Throwable
193
     */
194 92
    protected function updateOrAddItemForAllRelatedRootPages(string $itemType, $itemUid, int $forcedChangeTime): int
195
    {
196 92
        $updateCount = 0;
197
        try {
198 92
            $rootPageIds = $this->rootPageResolver->getResponsibleRootPageIds($itemType, $itemUid);
0 ignored issues
show
Bug introduced by
It seems like $itemUid can also be of type string; however, parameter $uid of ApacheSolrForTypo3\Solr\...esponsibleRootPageIds() 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

198
            $rootPageIds = $this->rootPageResolver->getResponsibleRootPageIds($itemType, /** @scrutinizer ignore-type */ $itemUid);
Loading history...
199 4
        } catch (RootPageRecordNotFoundException $e) {
200 4
            $this->deleteItem($itemType, $itemUid);
201 4
            return 0;
202
        }
203
204 88
        foreach ($rootPageIds as $rootPageId) {
205 88
            $skipInvalidRootPage = $rootPageId === 0;
206 88
            if ($skipInvalidRootPage) {
207
                continue;
208
            }
209
210
            /* @var SiteRepository $siteRepository */
211 88
            $siteRepository = GeneralUtility::makeInstance(SiteRepository::class);
212 88
            if ($siteRepository->getSiteByRootPageId($rootPageId) === null) {
213 88
                continue;
214 88
            }
215 3
            
216
            $solrConfiguration = $siteRepository->getSiteByRootPageId($rootPageId)->getSolrConfiguration();
217 87
            $indexingConfiguration = $this->recordService->getIndexingConfigurationName($itemType, $itemUid, $solrConfiguration);
0 ignored issues
show
Bug introduced by
It seems like $itemUid can also be of type string; however, parameter $recordUid of ApacheSolrForTypo3\Solr\...xingConfigurationName() 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

217
            $indexingConfiguration = $this->recordService->getIndexingConfigurationName($itemType, /** @scrutinizer ignore-type */ $itemUid, $solrConfiguration);
Loading history...
218 87
            if ($indexingConfiguration === null) {
219 87
                continue;
220
            }
221 19
            $indexingPriority = $solrConfiguration->getIndexQueueIndexingPriorityByConfigurationName($indexingConfiguration);
222 19
            $itemInQueueForRootPage = $this->containsItemWithRootPageId($itemType, $itemUid, $rootPageId);
223
            if ($itemInQueueForRootPage) {
224
                // update changed time if that item is in the queue already
225 80
                $changedTime = ($forcedChangeTime > 0) ? $forcedChangeTime : $this->getItemChangedTime($itemType, $itemUid);
226
                $updatedRows = $this->queueItemRepository->updateExistingItemByItemTypeAndItemUidAndRootPageId($itemType, $itemUid, $rootPageId, $changedTime, $indexingConfiguration, $indexingPriority);
0 ignored issues
show
Bug introduced by
It seems like $itemUid can also be of type string; however, parameter $itemUid of ApacheSolrForTypo3\Solr\...dItemUidAndRootPageId() 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

226
                $updatedRows = $this->queueItemRepository->updateExistingItemByItemTypeAndItemUidAndRootPageId($itemType, /** @scrutinizer ignore-type */ $itemUid, $rootPageId, $changedTime, $indexingConfiguration, $indexingPriority);
Loading history...
227
            } else {
228 87
                // add the item since it's not in the queue yet
229
                $updatedRows = $this->addNewItem($itemType, $itemUid, $indexingConfiguration, $rootPageId, $indexingPriority);
230
            }
231 88
232
            $updateCount += $updatedRows;
233
        }
234
235
        return $updateCount;
236
    }
237
238
    /**
239
     * Executes the updateItem post-processing hook.
240
     *
241
     * @param string $itemType
242
     * @param int|string $itemUid The item's uid, usually an integer uid, could be a different value for non-database-record types.
243 94
     * @param int $updateCount
244
     * @param int $forcedChangeTime
245
     * @return int
246
     */
247
    protected function postProcessIndexQueueUpdateItem(
248
        string $itemType,
249 94
        $itemUid,
250 93
        int $updateCount,
251
        int $forcedChangeTime = 0
252
    ): int {
253 1
        if (!is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['postProcessIndexQueueUpdateItem'] ?? null)) {
254 1
            return $updateCount;
255 1
        }
256
257
        foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['postProcessIndexQueueUpdateItem'] as $classReference) {
258 1
            $updateHandler = $this->getHookImplementation($classReference);
259
            $updateCount = $updateHandler->postProcessIndexQueueUpdateItem($itemType, $itemUid, $updateCount, $forcedChangeTime);
260
        }
261
262
        return $updateCount;
263
    }
264
265
    /**
266
     * @param string $classReference
267
     * @return object
268
     */
269
    protected function getHookImplementation(string $classReference): object
270
    {
271
        return GeneralUtility::makeInstance($classReference);
272
    }
273
274
    /**
275
     * Finds indexing errors for the current site
276
     *
277
     * @param Site $site
278 3
     * @return array Error items for the current site's Index Queue
279
     * @throws DBALDriverException
280 3
     * @throws DBALException|\Doctrine\DBAL\DBALException
281
     */
282
    public function getErrorsBySite(Site $site): array
283
    {
284
        return $this->queueItemRepository->findErrorsBySite($site);
285
    }
286
287
    /**
288
     * Resets all the errors for all index queue items.
289 1
     *
290
     * @return mixed
291 1
     * @throws DBALException|\Doctrine\DBAL\DBALException
292
     */
293
    public function resetAllErrors()
294
    {
295
        return $this->queueItemRepository->flushAllErrors();
296
    }
297
298
    /**
299
     * Resets the errors in the index queue for a specific site
300
     *
301 1
     * @param Site $site
302
     * @return mixed
303 1
     * @throws DBALException|\Doctrine\DBAL\DBALException
304
     */
305
    public function resetErrorsBySite(Site $site)
306
    {
307
        return $this->queueItemRepository->flushErrorsBySite($site);
308
    }
309
310
    /**
311
     * Resets the error in the index queue for a specific item
312
     *
313 1
     * @param Item $item
314
     * @return mixed
315 1
     * @throws DBALException|\Doctrine\DBAL\DBALException
316
     */
317
    public function resetErrorByItem(Item $item)
318
    {
319
        return $this->queueItemRepository->flushErrorByItem($item);
320
    }
321
322
    /**
323
     * Adds an item to the index queue.
324
     *
325
     * Not meant for public use.
326
     *
327
     * @param string $itemType The item's type, usually a table name.
328
     * @param int|string $itemUid The item's uid, usually an integer uid, could be a
329
     *      different value for non-database-record types.
330
     * @param string $indexingConfiguration The item's indexing configuration to use.
331
     *      Optional, overwrites existing / determined configuration.
332
     * @param int $rootPageId
333
     * @param int $indexingPriority
334 80
     * @return int
335
     * @throws DBALDriverException
336
     * @throws DBALException|\Doctrine\DBAL\DBALException
337
     */
338
    private function addNewItem(
339
        string $itemType,
340
        $itemUid,
341 80
        string $indexingConfiguration,
342 80
        int $rootPageId,
343 52
        int $indexingPriority = 0
344
    ): int {
345
        $additionalRecordFields = '';
346 80
        if ($itemType === 'pages') {
347
            $additionalRecordFields = ', doktype, uid';
348 80
        }
349
350
        $record = $this->getRecordCached($itemType, $itemUid, $additionalRecordFields);
351
352 80
        if (empty($record) || ($itemType === 'pages' && !$this->frontendEnvironment->isAllowedPageType($record, $indexingConfiguration))) {
353
            return 0;
354 80
        }
355
356
        $changedTime = $this->getItemChangedTime($itemType, $itemUid);
357
358
        return $this->queueItemRepository->add($itemType, $itemUid, $rootPageId, $changedTime, $indexingConfiguration, $indexingPriority);
0 ignored issues
show
Bug introduced by
It seems like $itemUid can also be of type string; however, parameter $itemUid of ApacheSolrForTypo3\Solr\...ueItemRepository::add() 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

358
        return $this->queueItemRepository->add($itemType, /** @scrutinizer ignore-type */ $itemUid, $rootPageId, $changedTime, $indexingConfiguration, $indexingPriority);
Loading history...
359
    }
360
361
    /**
362
     * Get record to be added in addNewItem
363
     *
364
     * @param string $itemType The item's type, usually a table name.
365
     * @param int|string $itemUid The item's uid, usually an integer uid, could be a
366
     *      different value for non-database-record types.
367 80
     * @param string $additionalRecordFields for sql-query
368
     *
369 80
     * @return array|null
370 80
     */
371
    protected function getRecordCached(string $itemType, $itemUid, string $additionalRecordFields): ?array
372 80
    {
373 80
        $cache = GeneralUtility::makeInstance(TwoLevelCache::class, /** @scrutinizer ignore-type */ 'runtime');
374 80
        $cacheId = md5('Queue' . ':' . 'getRecordCached' . ':' . $itemType . ':' . $itemUid . ':' . 'pid' . $additionalRecordFields);
375 80
376
        $record = $cache->get($cacheId);
377
        if (empty($record)) {
378 80
            $record = BackendUtility::getRecord($itemType, $itemUid, 'pid' . $additionalRecordFields);
379
            $cache->set($cacheId, $record);
380
        }
381
382
        return $record;
383
    }
384
385
    /**
386
     * Determines the time for when an item should be indexed. This timestamp
387
     * is then stored in the changed column in the Index Queue.
388
     *
389
     * The changed timestamp usually is now - time(). For records which are set
390
     * to published at a later time, this timestamp is the start time. So if a
391
     * future start time has been set, that will be used to delay indexing
392
     * of an item.
393
     *
394
     * @param string $itemType The item's table name.
395
     * @param int|string $itemUid The item's uid, usually an integer uid, could be a
396
     *      different value for non-database-record types.
397 87
     * @return int Timestamp of the item's changed time or future start time
398
     * @throws DBALDriverException
399 87
     * @throws DBALException|\Doctrine\DBAL\DBALException
400 87
     */
401 87
    protected function getItemChangedTime(string $itemType, $itemUid): int
402 87
    {
403
        $itemTypeHasStartTimeColumn = false;
404 87
        $changedTimeColumns = $GLOBALS['TCA'][$itemType]['ctrl']['tstamp'];
405 87
        $startTime = 0;
406 87
        $pageChangedTime = 0;
407
408 87
        if (!empty($GLOBALS['TCA'][$itemType]['ctrl']['enablecolumns']['starttime'])) {
409
            $itemTypeHasStartTimeColumn = true;
410
            $changedTimeColumns .= ', ' . $GLOBALS['TCA'][$itemType]['ctrl']['enablecolumns']['starttime'];
411 59
        }
412
        if ($itemType === 'pages') {
413
            // does not carry time information directly, but needed to support
414 87
            // canonical pages
415 87
            $changedTimeColumns .= ', content_from_pid';
416
        }
417 87
418 87
        $record = BackendUtility::getRecord($itemType, $itemUid, $changedTimeColumns);
419
        $itemChangedTime = $record[$GLOBALS['TCA'][$itemType]['ctrl']['tstamp']];
420
421 87
        if ($itemTypeHasStartTimeColumn) {
422 59
            $startTime = $record[$GLOBALS['TCA'][$itemType]['ctrl']['enablecolumns']['starttime']];
423
        }
424
425 59
        if ($itemType === 'pages') {
426
            $record['uid'] = $itemUid;
427
            // overrule the page's last changed time with the most recent
428 87
            //content element change
429
            $pageChangedTime = $this->getPageItemChangedTime($record);
0 ignored issues
show
Bug introduced by
It seems like $record can also be of type null; however, parameter $page of ApacheSolrForTypo3\Solr\...etPageItemChangedTime() does only seem to accept array, 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

429
            $pageChangedTime = $this->getPageItemChangedTime(/** @scrutinizer ignore-type */ $record);
Loading history...
430
        }
431
432
        $localizationsChangedTime = $this->queueItemRepository->getLocalizableItemChangedTime($itemType, (int)$itemUid);
433 87
434 87
        // if start time exists and start time is higher than last changed timestamp
435 87
        // then set changed to the future start time to make the item
436 87
        // indexed at a later time
437 87
        return (int)max(
438 87
            $itemChangedTime,
439
            $pageChangedTime,
440
            $localizationsChangedTime,
441
            $startTime
442
        );
443
    }
444
445
    /**
446
     * Gets the most recent changed time of a page's content elements
447
     *
448
     * @param array $page Partial page record
449 59
     * @return int Timestamp of the most recent content element change
450
     * @throws DBALDriverException
451 59
     * @throws DBALException|\Doctrine\DBAL\DBALException
452
     */
453
    protected function getPageItemChangedTime(array $page): int
454
    {
455 59
        if (!empty($page['content_from_pid'])) {
456
            // canonical page, get the original page's last changed time
457
            return $this->queueItemRepository->getPageItemChangedTimeByPageUid((int)$page['content_from_pid']);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->queueItemR...ge['content_from_pid']) could return the type null which is incompatible with the type-hinted return integer. Consider adding an additional type-check to rule them out.
Loading history...
458
        }
459
        return $this->queueItemRepository->getPageItemChangedTimeByPageUid((int)$page['uid']) ?? 0;
460
    }
461
462
    /**
463
     * Checks whether the Index Queue contains a specific item.
464
     *
465
     * @param string $itemType The item's type, usually a table name.
466
     * @param int|string $itemUid The item's uid, usually an integer uid, could be a
467
     *      different value for non-database-record types.
468 10
     * @return bool TRUE if the item is found in the queue, FALSE otherwise
469
     * @throws DBALDriverException
470 10
     * @throws DBALException|\Doctrine\DBAL\DBALException
471
     */
472
    public function containsItem(string $itemType, $itemUid): bool
473
    {
474
        return $this->queueItemRepository->containsItem($itemType, (int)$itemUid);
475
    }
476
477
    /**
478
     * Checks whether the Index Queue contains a specific item.
479
     *
480
     * @param string $itemType The item's type, usually a table name.
481
     * @param int|string $itemUid The item's uid, usually an integer uid, could be a
482
     *      different value for non-database-record types.
483
     * @param int $rootPageId
484 87
     * @return bool TRUE if the item is found in the queue, FALSE otherwise
485
     * @throws DBALDriverException
486 87
     * @throws DBALException|\Doctrine\DBAL\DBALException
487
     */
488
    public function containsItemWithRootPageId(string $itemType, $itemUid, int $rootPageId): bool
489
    {
490
        return $this->queueItemRepository->containsItemWithRootPageId($itemType, (int)$itemUid, $rootPageId);
491
    }
492
493
    /**
494
     * Checks whether the Index Queue contains a specific item that has been
495
     * marked as indexed.
496
     *
497
     * @param string $itemType The item's type, usually a table name.
498
     * @param int|string $itemUid The item's uid, usually an integer uid, could be a
499
     *      different value for non-database-record types.
500
     * @return bool TRUE if the item is found in the queue and marked as
501 4
     *      indexed, FALSE otherwise
502
     * @throws DBALDriverException
503 4
     * @throws DBALException|\Doctrine\DBAL\DBALException
504
     */
505
    public function containsIndexedItem(string $itemType, $itemUid): bool
506
    {
507
        return $this->queueItemRepository->containsIndexedItem($itemType, (int)$itemUid);
508
    }
509
510
    /**
511
     * Removes an item from the Index Queue.
512
     *
513
     * @param string $itemType The type of the item to remove, usually a table name.
514
     * @param int|string $itemUid The uid of the item to remove
515 61
     * @throws ConnectionException
516
     * @throws DBALException
517 61
     * @throws Throwable
518
     */
519
    public function deleteItem(string $itemType, $itemUid)
520
    {
521
        $this->queueItemRepository->deleteItem($itemType, (int)$itemUid);
522
    }
523
524
    /**
525
     * Removes all items of a certain type from the Index Queue.
526
     *
527
     * @param string $itemType The type of items to remove, usually a table name.
528 1
     * @throws ConnectionException
529
     * @throws DBALException
530 1
     * @throws Throwable
531
     */
532
    public function deleteItemsByType(string $itemType)
533
    {
534
        $this->queueItemRepository->deleteItemsByType($itemType);
535
    }
536
537
    /**
538
     * Removes all items of a certain site from the Index Queue. Accepts an
539
     * optional parameter to limit the deleted items by indexing configuration.
540
     *
541
     * @param Site $site The site to remove items for.
542
     * @param string $indexingConfigurationName Name of a specific indexing
543
     *      configuration
544 6
     * @throws ConnectionException
545
     * @throws \Doctrine\DBAL\DBALException
546 6
     * @throws Throwable
547
     */
548
    public function deleteItemsBySite(Site $site, string $indexingConfigurationName = '')
549
    {
550
        $this->queueItemRepository->deleteItemsBySite($site, $indexingConfigurationName);
551
    }
552 1
553
    /**
554 1
     * Removes all items from the Index Queue.
555
     */
556
    public function deleteAllItems()
557
    {
558
        $this->queueItemRepository->deleteAllItems();
559
    }
560
561
    /**
562
     * Gets a single Index Queue item by its uid.
563
     *
564
     * @param int $itemId Index Queue item uid
565 34
     * @return Item|null The request Index Queue item or NULL if no item with $itemId was found
566
     * @throws DBALDriverException
567 34
     * @throws DBALException|\Doctrine\DBAL\DBALException
568
     */
569
    public function getItem(int $itemId): ?Item
570
    {
571
        return $this->queueItemRepository->findItemByUid($itemId);
572
    }
573
574
    /**
575
     * Gets Index Queue items by type and uid.
576
     *
577
     * @param string $itemType item type, usually  the table name
578
     * @param int|string $itemUid item uid
579
     * @return Item[] An array of items matching $itemType and $itemUid
580
     * @throws ConnectionException
581 52
     * @throws DBALDriverException
582
     * @throws DBALException
583 52
     * @throws Throwable
584
     */
585
    public function getItems(string $itemType, $itemUid): array
586
    {
587
        return $this->queueItemRepository->findItemsByItemTypeAndItemUid($itemType, (int)$itemUid);
588
    }
589
590
    /**
591
     * Returns all items in the queue.
592
     *
593
     * @return Item[] An array of items
594
     * @throws ConnectionException
595 4
     * @throws DBALDriverException
596
     * @throws DBALException
597 4
     * @throws Throwable
598
     */
599
    public function getAllItems(): array
600
    {
601
        return $this->queueItemRepository->findAll();
602
    }
603
604
    /**
605
     * Returns the number of items for all queues.
606
     *
607 112
     * @return int
608
     * @throws DBALDriverException
609 112
     * @throws DBALException
610
     */
611
    public function getAllItemsCount(): int
612
    {
613
        return $this->queueItemRepository->count();
614
    }
615
616
    /**
617
     * Extracts the number of pending, indexed and erroneous items from the
618
     * Index Queue.
619
     *
620
     * @param Site $site
621
     * @param string $indexingConfigurationName
622
     *
623 5
     * @return QueueStatistic
624
     * @throws DBALDriverException
625 5
     * @throws DBALException
626 5
     */
627 5
    public function getStatisticsBySite(Site $site, string $indexingConfigurationName = ''): QueueStatistic
628 5
    {
629 5
        return $this->queueStatisticsRepository
630
            ->findOneByRootPidAndOptionalIndexingConfigurationName(
631
                $site->getRootPageId(),
632
                $indexingConfigurationName
633
            );
634
    }
635
636
    /**
637
     * Gets $limit number of items to index for a particular $site.
638
     *
639
     * @param Site $site TYPO3 site
640
     * @param int $limit Number of items to get from the queue
641
     * @return Item[] Items to index to the given solr server
642
     * @throws ConnectionException
643 3
     * @throws DBALDriverException
644
     * @throws DBALException
645 3
     * @throws Throwable
646
     */
647
    public function getItemsToIndex(Site $site, int $limit = 50): array
648
    {
649
        return $this->queueItemRepository->findItemsToIndex($site, $limit);
650
    }
651
652
    /**
653
     * Marks an item as failed and causes the indexer to skip the item in the
654
     * next run.
655
     *
656 6
     * @param int|Item $item Either the item's Index Queue uid or the complete item
657
     * @param string $errorMessage Error message
658 6
     * @throws DBALException|\Doctrine\DBAL\DBALException
659
     */
660
    public function markItemAsFailed($item, string $errorMessage = '')
661
    {
662
        $this->queueItemRepository->markItemAsFailed($item, $errorMessage);
663
    }
664
665
    /**
666
     * Sets the timestamp of when an item last has been indexed.
667 2
     *
668
     * @param Item $item
669 2
     * @throws DBALException|\Doctrine\DBAL\DBALException
670
     */
671
    public function updateIndexTimeByItem(Item $item)
672
    {
673
        $this->queueItemRepository->updateIndexTimeByItem($item);
674
    }
675
676
    /**
677
     * Sets the change timestamp of an item.
678
     *
679
     * @param Item $item
680
     * @param int $forcedChangeTime The change time for the item
681
     * @throws DBALException|\Doctrine\DBAL\DBALException
682
     */
683
    public function setForcedChangeTimeByItem(Item $item, int $forcedChangeTime = 0)
684
    {
685
        $this->queueItemRepository->updateChangedTimeByItem($item, $forcedChangeTime);
686
    }
687
}
688