Passed
Push — hans/bufferadd ( dd4951...8221cf )
by Simon
08:32 queued 06:25
created

SolrIndexTask::run()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 29
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 3

Importance

Changes 11
Bugs 0 Features 0
Metric Value
cc 3
eloc 17
c 11
b 0
f 0
nc 3
nop 1
dl 0
loc 29
ccs 18
cts 18
cp 1
crap 3
rs 9.7
1
<?php
2
3
4
namespace Firesphere\SolrSearch\Tasks;
5
6
use Exception;
7
use Firesphere\SolrSearch\Factories\DocumentFactory;
8
use Firesphere\SolrSearch\Helpers\SolrLogger;
9
use Firesphere\SolrSearch\Indexes\BaseIndex;
10
use Firesphere\SolrSearch\Services\SolrCoreService;
11
use Firesphere\SolrSearch\States\SiteState;
12
use Firesphere\SolrSearch\Traits\LoggerTrait;
13
use GuzzleHttp\Exception\GuzzleException;
14
use Psr\Log\LoggerInterface;
15
use ReflectionException;
16
use SilverStripe\Control\Director;
17
use SilverStripe\Control\HTTPRequest;
18
use SilverStripe\Core\Injector\Injector;
19
use SilverStripe\Dev\BuildTask;
20
use SilverStripe\ORM\ArrayList;
21
use SilverStripe\ORM\DataList;
22
use SilverStripe\ORM\DataObject;
23
use SilverStripe\ORM\ValidationException;
24
use SilverStripe\Versioned\Versioned;
25
26
/**
27
 * Class SolrIndexTask
28
 *
29
 * @description Index items to Solr through a tasks
30
 * @package Firesphere\SolrSearch\Tasks
31
 */
32
class SolrIndexTask extends BuildTask
33
{
34
    use LoggerTrait;
35
    /**
36
     * URLSegment of this task
37
     *
38
     * @var string
39
     */
40
    private static $segment = 'SolrIndexTask';
41
    /**
42
     * Store the current states for all instances of SiteState
43
     *
44
     * @var array
45
     */
46
    public $currentStates;
47
    /**
48
     * My name
49
     *
50
     * @var string
51
     */
52
    protected $title = 'Solr Index update';
53
    /**
54
     * What do I do?
55
     *
56
     * @var string
57
     */
58
    protected $description = 'Add or update documents to an existing Solr core.';
59
    /**
60
     * Debug mode enabled, default false
61
     *
62
     * @var bool
63
     */
64
    protected $debug = false;
65
    /**
66
     * Singleton of {@link SolrCoreService}
67
     *
68
     * @var SolrCoreService
69
     */
70
    protected $service;
71
72
    /**
73
     * SolrIndexTask constructor. Sets up the document factory
74
     *
75
     * @throws ReflectionException
76
     */
77 14
    public function __construct()
78
    {
79 14
        parent::__construct();
80
        // Only index live items.
81
        // The old FTS module also indexed Draft items. This is unnecessary
82 14
        Versioned::set_reading_mode(Versioned::DEFAULT_MODE);
83 14
        $this->setService(Injector::inst()->get(SolrCoreService::class, false));
84 14
        $this->setLogger(Injector::inst()->get(LoggerInterface::class));
85 14
        $this->setDebug(Director::isDev() || Director::is_cli());
86 14
        $currentStates = SiteState::currentStates();
87 14
        SiteState::setDefaultStates($currentStates);
88 14
    }
89
90
    /**
91
     * Set the {@link SolrCoreService}
92
     *
93
     * @param SolrCoreService $service
94
     * @return SolrIndexTask
95
     */
96 14
    public function setService(SolrCoreService $service): SolrIndexTask
97
    {
98 14
        $this->service = $service;
99
100 14
        return $this;
101
    }
102
103
    /**
104
     * Set the debug mode
105
     *
106
     * @param bool $debug
107
     * @return SolrIndexTask
108
     */
109 14
    public function setDebug(bool $debug): SolrIndexTask
110
    {
111 14
        $this->debug = $debug;
112
113 14
        return $this;
114
    }
115
116
    /**
117
     * Implement this method in the task subclass to
118
     * execute via the TaskRunner
119
     *
120
     * @param HTTPRequest $request
121
     * @return int|bool
122
     * @throws Exception
123
     * @throws GuzzleException
124
     * @todo defer to background because it may run out of memory
125
     */
126 13
    public function run($request)
127
    {
128 13
        $startTime = time();
129 13
        list($vars, $group) = $this->taskSetup($request);
130 13
        $groups = 0;
131 13
        $indexes = $this->service->getValidIndexes($request->getVar('index'));
132
133 13
        foreach ($indexes as $indexName) {
134
            /** @var BaseIndex $index */
135 13
            $index = Injector::inst()->get($indexName, false);
136
137 13
            $indexClasses = $index->getClasses();
138 13
            $classes = $this->getClasses($vars, $indexClasses);
139 13
            if (!count($classes)) {
140 10
                continue;
141
            }
142
143 13
            $this->clearIndex($vars, $index);
144
145 13
            $groups = $this->indexClassForIndex($classes, $index, $group);
146
        }
147 13
        $this->getLogger()->info(
148 13
            sprintf('It took me %d seconds to do all the indexing%s', (time() - $startTime), PHP_EOL)
149
        );
150
        // Grab the latest logs from indexing if needed
151 13
        $solrLogger = new SolrLogger();
152 13
        $solrLogger->saveSolrLog('Config');
153
154 13
        return $groups;
155
    }
156
157
    /**
158
     * Set up the requirements for this task
159
     *
160
     * @param HTTPRequest $request
161
     * @return array
162
     */
163 13
    protected function taskSetup($request): array
164
    {
165 13
        $vars = $request->getVars();
166 13
        $this->debug = $this->debug || isset($vars['debug']);
167 13
        $group = $vars['group'] ?? false;
168 13
        $start = $vars['start'] ?? 0;
169 13
        $group = ($group !== false && $start > $group) ? $start : $group;
170
171 13
        return [$vars, $group];
172
    }
173
174
    /**
175
     * get the classes to run for this task execution
176
     *
177
     * @param $vars
178
     * @param array $classes
179
     * @return bool|array
180
     */
181 13
    protected function getClasses($vars, array $classes): array
182
    {
183 13
        if (isset($vars['class'])) {
184 1
            return array_intersect($classes, [$vars['class']]);
185
        }
186
187 12
        return $classes;
188
    }
189
190
    /**
191
     * Clear the given index if a full re-index is needed
192
     *
193
     * @param $vars
194
     * @param BaseIndex $index
195
     * @throws Exception
196
     */
197 13
    public function clearIndex($vars, BaseIndex $index)
198
    {
199 13
        if (!empty($vars['clear'])) {
200 1
            $this->getLogger()->info(sprintf('Clearing index %s', $index->getIndexName()));
201 1
            $this->service->doManipulate(ArrayList::create([]), SolrCoreService::DELETE_TYPE_ALL, $index);
202
        }
203 13
    }
204
205
    /**
206
     * Index the classes for a specific index
207
     *
208
     * @param array $classes
209
     * @param BaseIndex $index
210
     * @param int|bool $group
211
     * @return int|bool
212
     * @throws Exception
213
     * @throws GuzzleException
214
     */
215 13
    protected function indexClassForIndex($classes, BaseIndex $index, $group): int
216
    {
217 13
        $groups = 0;
218 13
        foreach ($classes as $class) {
219 13
            $groups = $this->indexClass($class, $index, $group);
0 ignored issues
show
Bug introduced by
It seems like $group can also be of type boolean; however, parameter $group of Firesphere\SolrSearch\Ta...IndexTask::indexClass() 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

219
            $groups = $this->indexClass($class, $index, /** @scrutinizer ignore-type */ $group);
Loading history...
220
        }
221
222 13
        return $groups;
223
    }
224
225
    /**
226
     * Index a single class for a given index. {@link static::indexClassForIndex()}
227
     *
228
     * @param string $class
229
     * @param BaseIndex $index
230
     * @param int|bool $group
231
     * @return int|bool
232
     * @throws GuzzleException
233
     * @throws ValidationException
234
     */
235 13
    private function indexClass($class, BaseIndex $index, int $group): int
236
    {
237 13
        $this->getLogger()->info(sprintf('Indexing %s for %s', $class, $index->getIndexName()), []);
238
239
        try {
240 13
            $this->doReindex($group, $class, $index);
241
        } catch (Exception $error) {
242
            $this->logException($index->getIndexName(), $group, $error);
243
        }
244
245 13
        return $group;
246
    }
247
248
    /**
249
     * Reindex the given group, for each state
250
     *
251
     * @param int|bool $group
252
     * @param string $class
253
     * @param BaseIndex $index
254
     * @throws ReflectionException
255
     * @throws Exception
256
     */
257 13
    private function doReindex($group, $class, BaseIndex $index): void
258
    {
259 13
        foreach (SiteState::getStates() as $state) {
260 13
            if ($state !== 'default' && !empty($state)) {
261
                SiteState::withState($state);
262
            }
263 13
            $this->stateReindex($group, $class, $index);
264
        }
265
266 13
        SiteState::withState(SiteState::DEFAULT_STATE);
267 13
    }
268
269
    /**
270
     * Index a group of a class for a specific state and index
271
     *
272
     * @param int|bool $group
273
     * @param string $class
274
     * @param BaseIndex $index
275
     * @throws Exception
276
     */
277 13
    private function stateReindex($group, $class, BaseIndex $index): void
278
    {
279
        // Generate filtered list of local records
280 13
        $baseClass = DataObject::getSchema()->baseDataClass($class);
281
        /** @var DataList|DataObject[] $items */
282 13
        $items = DataObject::get($baseClass)
283 13
            ->sort('ID ASC');
284 13
        if ($group !== false) {
285 13
            $batchLength = DocumentFactory::config()->get('batchLength');
286 13
            $items = $items->limit($batchLength, ($group * $batchLength));
287
        }
288 13
        if ($items->count()) {
289 1
            $this->updateIndex($index, $items);
290
        }
291 13
    }
292
293
    /**
294
     * Execute the update on the client
295
     *
296
     * @param BaseIndex $index
297
     * @param $items
298
     * @throws Exception
299
     */
300 1
    private function updateIndex(BaseIndex $index, $items): void
301
    {
302 1
        $this->service->setInDebugMode($this->debug);
303 1
        $this->service->updateIndex($index, $items);
304 1
    }
305
306
    /**
307
     * Log an exception if it happens. Most are catched, these logs are for the developers
308
     * to identify problems and fix them.
309
     *
310
     * @param string $index
311
     * @param int $group
312
     * @param Exception $exception
313
     * @throws GuzzleException
314
     * @throws ValidationException
315
     */
316
    private function logException($index, int $group, Exception $exception): void
317
    {
318
        $this->getLogger()->error($exception->getMessage());
319
        $msg = sprintf(
320
            'Error indexing core %s on group %s,' . PHP_EOL .
321
            'Please log in to the CMS to find out more about Indexing errors' . PHP_EOL,
322
            $index,
323
            $group
324
        );
325
        SolrLogger::logMessage('ERROR', $msg, $index);
326
    }
327
}
328