Passed
Push — master ( b39217...9ad7ee )
by Sascha
01:01
created

IndexService::__construct()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 5
nc 4
nop 3
crap 3
1
<?php
2
3
namespace ApacheSolrForTypo3\Solr\Domain\Index;
4
5
/***************************************************************
6
 *  Copyright notice
7
 *
8
 *  (c) 2015-2016 Timo Hund <[email protected]>
9
 *  All rights reserved
10
 *
11
 *  This script is part of the TYPO3 project. The TYPO3 project is
12
 *  free software; you can redistribute it and/or modify
13
 *  it under the terms of the GNU General Public License as published by
14
 *  the Free Software Foundation; either version 2 of the License, or
15
 *  (at your option) any later version.
16
 *
17
 *  The GNU General Public License can be found at
18
 *  http://www.gnu.org/copyleft/gpl.html.
19
 *
20
 *  This script is distributed in the hope that it will be useful,
21
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
22
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23
 *  GNU General Public License for more details.
24
 *
25
 *  This copyright notice MUST APPEAR in all copies of the script!
26
 ***************************************************************/
27
28
use ApacheSolrForTypo3\Solr\ConnectionManager;
29
use ApacheSolrForTypo3\Solr\IndexQueue\Indexer;
30
use ApacheSolrForTypo3\Solr\IndexQueue\Item;
31
use ApacheSolrForTypo3\Solr\IndexQueue\Queue;
32
use ApacheSolrForTypo3\Solr\Site;
33
use ApacheSolrForTypo3\Solr\System\Configuration\TypoScriptConfiguration;
34
use ApacheSolrForTypo3\Solr\System\Logging\SolrLogManager;
35
use ApacheSolrForTypo3\Solr\Task\IndexQueueWorkerTask;
36
use TYPO3\CMS\Backend\Utility\BackendUtility;
37
use TYPO3\CMS\Core\Utility\GeneralUtility;
38
use TYPO3\CMS\Extbase\SignalSlot\Dispatcher;
39
40
/**
41
 * Service to perform indexing operations
42
 *
43
 * @author Timo Hund <[email protected]>
44
 */
45
class IndexService
46
{
47
    /**
48
     * @var TypoScriptConfiguration
49
     */
50
    protected $configuration;
51
52
    /**
53
     * @var Site
54
     */
55
    protected $site;
56
57
    /**
58
     * @var IndexQueueWorkerTask
59
     */
60
    protected $contextTask;
61
62
    /**
63
     * @var Queue
64
     */
65
    protected $indexQueue;
66
67
    /**
68
     * @var Dispatcher
69
     */
70
    protected $signalSlotDispatcher;
71
72
    /**
73
     * @var \ApacheSolrForTypo3\Solr\System\Logging\SolrLogManager
74
     */
75
    protected $logger = null;
76
77
    /**
78
     * IndexService constructor.
79
     * @param Site $site
80
     * @param Queue|null $queue
81
     * @param Dispatcher|null $dispatcher
82
     */
83 8
    public function __construct(Site $site, Queue $queue = null, Dispatcher $dispatcher = null)
84
    {
85 8
        $this->logger = GeneralUtility::makeInstance(SolrLogManager::class, __CLASS__);
86 8
        $this->site = $site;
87 8
        $this->indexQueue = is_null($queue) ? GeneralUtility::makeInstance(Queue::class) : $queue;
88 8
        $this->signalSlotDispatcher = is_null($dispatcher) ? GeneralUtility::makeInstance(Dispatcher::class) : $dispatcher;
89 8
    }
90
91
    /**
92
     * @param \ApacheSolrForTypo3\Solr\Task\IndexQueueWorkerTask $contextTask
93
     */
94 2
    public function setContextTask($contextTask)
95
    {
96 2
        $this->contextTask = $contextTask;
97 2
    }
98
99
    /**
100
     * @return \ApacheSolrForTypo3\Solr\Task\IndexQueueWorkerTask
101
     */
102 6
    public function getContextTask()
103
    {
104 6
        return $this->contextTask;
105
    }
106
107
    /**
108
     * Indexes items from the Index Queue.
109
     *
110
     * @param int $limit
111
     * @return bool
112
     */
113 6
    public function indexItems($limit)
114
    {
115 6
        $errors     = 0;
116 6
        $indexRunId = uniqid();
117 6
        $configurationToUse = $this->site->getSolrConfiguration();
118 6
        $enableCommitsSetting = $configurationToUse->getEnableCommits();
119
120
        // get items to index
121 6
        $itemsToIndex = $this->indexQueue->getItemsToIndex($this->site, $limit);
122
123 6
        $this->emitSignal('beforeIndexItems', [$itemsToIndex, $this->getContextTask(), $indexRunId]);
124
125 6
        foreach ($itemsToIndex as $itemToIndex) {
126
            try {
127
                // try indexing
128 6
                $this->emitSignal('beforeIndexItem', [$itemToIndex, $this->getContextTask(), $indexRunId]);
129 6
                $this->indexItem($itemToIndex, $configurationToUse);
130 6
                $this->emitSignal('afterIndexItem', [$itemToIndex, $this->getContextTask(), $indexRunId]);
131
            } catch (\Exception $e) {
132
                $errors++;
133
                $this->indexQueue->markItemAsFailed($itemToIndex, $e->getCode() . ': ' . $e->__toString());
134
                $this->generateIndexingErrorLog($itemToIndex, $e);
135
            }
136
        }
137
138 6
        $this->emitSignal('afterIndexItems', [$itemsToIndex, $this->getContextTask(), $indexRunId]);
139
140 6
        if ($enableCommitsSetting && count($itemsToIndex) > 0) {
141 5
            $solrServers = GeneralUtility::makeInstance(ConnectionManager::class)->getConnectionsBySite($this->site);
142 5
            foreach ($solrServers as $solrServer) {
143 5
                $solrServer->commit(false, false, false);
144
            }
145
        }
146
147 6
        return ($errors === 0);
148
    }
149
150
    /**
151
     * Generates a message in the error log when an error occured.
152
     *
153
     * @param Item $itemToIndex
154
     * @param \Exception  $e
155
     */
156
    protected function generateIndexingErrorLog(Item $itemToIndex, \Exception $e)
157
    {
158
        $message = 'Failed indexing Index Queue item ' . $itemToIndex->getIndexQueueUid();
159
        $data = ['code' => $e->getCode(), 'message' => $e->getMessage(), 'trace' => $e->getTrace(), 'item' => (array)$itemToIndex];
160
161
        $this->logger->log(
162
            SolrLogManager::ERROR,
163
            $message,
164
            $data
165
        );
166
    }
167
168
    /**
169
     * Builds an emits a singal for the IndexService.
170
     *
171
     * @param string $name
172
     * @param array $arguments
173
     * @return mixed
174
     */
175 6
    protected function emitSignal($name, $arguments)
176
    {
177 6
        return $this->signalSlotDispatcher->dispatch(__CLASS__, $name, $arguments);
178
    }
179
180
    /**
181
     * Indexes an item from the Index Queue.
182
     *
183
     * @param Item $item An index queue item to index
184
     * @param TypoScriptConfiguration $configuration
185
     * @return bool TRUE if the item was successfully indexed, FALSE otherwise
186
     */
187 5
    protected function indexItem(Item $item, TypoScriptConfiguration $configuration)
188
    {
189 5
        $indexer = $this->getIndexerByItem($item->getIndexingConfigurationName(), $configuration);
190
191
        // Remember original http host value
192 5
        $originalHttpHost = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : null;
193
194 5
        $this->initializeHttpServerEnvironment($item);
195 5
        $itemIndexed = $indexer->index($item);
196
197
        // update IQ item so that the IQ can determine what's been indexed already
198 5
        if ($itemIndexed) {
199 5
            $this->indexQueue->updateIndexTimeByItem($item);
200
        }
201
202 5
        if (!is_null($originalHttpHost)) {
203
            $_SERVER['HTTP_HOST'] = $originalHttpHost;
204
        } else {
205 5
            unset($_SERVER['HTTP_HOST']);
206
        }
207
208
        // needed since TYPO3 7.5
209 5
        GeneralUtility::flushInternalRuntimeCaches();
210
211 5
        return $itemIndexed;
212
    }
213
214
    /**
215
     * A factory method to get an indexer depending on an item's configuration.
216
     *
217
     * By default all items are indexed using the default indexer
218
     * (ApacheSolrForTypo3\Solr\IndexQueue\Indexer) coming with EXT:solr. Pages by default are
219
     * configured to be indexed through a dedicated indexer
220
     * (ApacheSolrForTypo3\Solr\IndexQueue\PageIndexer). In all other cases a dedicated indexer
221
     * can be specified through TypoScript if needed.
222
     *
223
     * @param string $indexingConfigurationName Indexing configuration name.
224
     * @param TypoScriptConfiguration $configuration
225
     * @return Indexer
226
     */
227 5
    protected function getIndexerByItem($indexingConfigurationName, TypoScriptConfiguration $configuration)
228
    {
229 5
        $indexerClass = $configuration->getIndexQueueIndexerByConfigurationName($indexingConfigurationName);
230 5
        $indexerConfiguration = $configuration->getIndexQueueIndexerConfigurationByConfigurationName($indexingConfigurationName);
231
232 5
        $indexer = GeneralUtility::makeInstance($indexerClass, $indexerConfiguration);
233 5
        if (!($indexer instanceof Indexer)) {
234
            throw new \RuntimeException(
235
                'The indexer class "' . $indexerClass . '" for indexing configuration "' . $indexingConfigurationName . '" is not a valid indexer. Must be a subclass of ApacheSolrForTypo3\Solr\IndexQueue\Indexer.',
236
                1260463206
237
            );
238
        }
239
240 5
        return $indexer;
241
    }
242
243
    /**
244
     * Gets the indexing progress.
245
     *
246
     * @return float Indexing progress as a two decimal precision float. f.e. 44.87
247
     */
248 2
    public function getProgress()
249
    {
250 2
        return $this->indexQueue->getStatisticsBySite($this->site)->getSuccessPercentage();
251
    }
252
253
    /**
254
     * Returns the amount of failed queue items for the current site.
255
     *
256
     * @return int
257
     */
258 1
    public function getFailCount()
259
    {
260 1
        return $this->indexQueue->getStatisticsBySite($this->site)->getFailedCount();
261
    }
262
263
    /**
264
     * Initializes the $_SERVER['HTTP_HOST'] environment variable in CLI
265
     * environments dependent on the Index Queue item's root page.
266
     *
267
     * When the Index Queue Worker task is executed by a cron job there is no
268
     * HTTP_HOST since we are in a CLI environment. RealURL needs the host
269
     * information to generate a proper URL though. Using the Index Queue item's
270
     * root page information we can determine the correct host although being
271
     * in a CLI environment.
272
     *
273
     * @param Item $item Index Queue item to use to determine the host.
274
     * @param
275
     */
276 5
    protected function initializeHttpServerEnvironment(Item $item)
277
    {
278 5
        static $hosts = [];
279 5
        $rootpageId = $item->getRootPageUid();
280 5
        $hostFound = !empty($hosts[$rootpageId]);
281
282 5
        if (!$hostFound) {
283 5
            $rootline = BackendUtility::BEgetRootLine($rootpageId);
284 5
            $host = BackendUtility::firstDomainRecord($rootline);
285 5
            $hosts[$rootpageId] = $host;
286
        }
287
288 5
        $_SERVER['HTTP_HOST'] = $hosts[$rootpageId];
289
290
        // needed since TYPO3 7.5
291 5
        GeneralUtility::flushInternalRuntimeCaches();
292 5
    }
293
}
294