Passed
Push — sheepy/introspection ( 000d40...b6b869 )
by Marco
02:43
created

SolrIndexTask::setService()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 2
c 2
b 0
f 0
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
4
namespace Firesphere\SolrSearch\Tasks;
5
6
use Exception;
7
use Firesphere\SolrSearch\Factories\DocumentFactory;
8
use Firesphere\SolrSearch\Indexes\BaseIndex;
9
use Firesphere\SolrSearch\Services\SolrCoreService;
10
use GuzzleHttp\Exception\RequestException;
11
use Psr\Log\LoggerInterface;
12
use SilverStripe\Control\Director;
13
use SilverStripe\Control\HTTPRequest;
14
use SilverStripe\Core\Injector\Injector;
15
use SilverStripe\Dev\BuildTask;
16
use SilverStripe\ORM\ArrayList;
17
use SilverStripe\ORM\DataList;
18
use SilverStripe\ORM\DataObject;
19
use SilverStripe\Versioned\Versioned;
20
21
class SolrIndexTask extends BuildTask
22
{
23
    /**
24
     * @var string
25
     */
26
    private static $segment = 'SolrIndexTask';
27
28
    /**
29
     * @var string
30
     */
31
    protected $title = 'Solr Index update';
32
33
    /**
34
     * @var string
35
     */
36
    protected $description = 'Add or update documents to an existing Solr core.';
37
38
    /**
39
     * @var bool
40
     */
41
    protected $debug = false;
42
43
    /**
44
     * @var null|LoggerInterface
45
     */
46
    protected $logger;
47
48
    /**
49
     * @var SolrCoreService
50
     */
51
    protected $service;
52
53
    /**
54
     * SolrIndexTask constructor. Sets up the document factory
55
     */
56 13
    public function __construct()
57
    {
58 13
        parent::__construct();
59
        // Only index live items.
60
        // The old FTS module also indexed Draft items. This is unnecessary
61 13
        Versioned::set_reading_mode(Versioned::DRAFT . '.' . Versioned::LIVE);
62 13
        $this->setService(Injector::inst()->get(SolrCoreService::class));
63 13
        $this->setLogger(Injector::inst()->get(LoggerInterface::class));
64 13
        $this->setDebug(Director::isDev() || Director::is_cli());
65 13
    }
66
67
    /**
68
     * @param SolrCoreService $service
69
     * @return SolrIndexTask
70
     */
71 13
    public function setService(SolrCoreService $service): SolrIndexTask
72
    {
73 13
        $this->service = $service;
74
75 13
        return $this;
76
    }
77
78
    /**
79
     * @param bool $debug
80
     * @return SolrIndexTask
81
     */
82 13
    public function setDebug(bool $debug): SolrIndexTask
83
    {
84 13
        $this->debug = $debug;
85
86 13
        return $this;
87
    }
88
89
    /**
90
     * Implement this method in the task subclass to
91
     * execute via the TaskRunner
92
     *
93
     * @param HTTPRequest $request
94
     * @return int|bool
95
     * @throws Exception
96
     * @todo defer to background because it may run out of memory
97
     */
98 12
    public function run($request)
99
    {
100 12
        $startTime = time();
101 12
        [$vars, $group, $isGroup] = $this->taskSetup($request);
102 12
        $groups = 0;
103 12
        $indexes = $this->service->getValidIndexes($request->getVar('index'));
104
105 12
        foreach ($indexes as $indexName) {
106
            /** @var BaseIndex $index */
107 12
            $index = Injector::inst()->get($indexName);
108
109 12
            $indexClasses = $index->getClasses();
110 12
            $classes = $this->getClasses($vars, $indexClasses);
111 12
            if (!count($classes)) {
112
                continue;
113
            }
114
115 12
            if (!empty($vars['clear'])) {
116 1
                $this->getLogger()->info(sprintf('Clearing index %s', $indexName));
117 1
                $this->service->doManipulate(ArrayList::create([]), SolrCoreService::DELETE_TYPE_ALL, $index);
118
            }
119
120 12
            foreach ($classes as $class) {
121 12
                $groups = $this->indexClass($isGroup, $class, $index, $group);
122
            }
123
        }
124 12
        $this->getLogger()->info(
125 12
            sprintf('It took me %d seconds to do all the indexing%s', (time() - $startTime), PHP_EOL)
126
        );
127
128 12
        return $groups;
129
    }
130
131
    /**
132
     * @param HTTPRequest $request
133
     * @return array
134
     */
135 12
    protected function taskSetup($request): array
136
    {
137 12
        $vars = $request->getVars();
138 12
        $this->debug = $this->debug || isset($vars['debug']);
139 12
        $group = $vars['group'] ?? 0;
140 12
        $start = $vars['start'] ?? 0;
141 12
        $group = ($start > $group) ? $start : $group;
142 12
        $isGroup = isset($vars['group']);
143
144 12
        return [$vars, $group, $isGroup];
145
    }
146
147
    /**
148
     * @param $vars
149
     * @param array $classes
150
     * @return bool|array
151
     */
152 12
    protected function getClasses($vars, array $classes): array
153
    {
154 12
        if (isset($vars['class'])) {
155 1
            return array_intersect($classes, [$vars['class']]);
156
        }
157
158 11
        return $classes;
159
    }
160
161
    /**
162
     * @return LoggerInterface
163
     */
164 13
    public function getLogger(): LoggerInterface
165
    {
166
        // Constructor should take care of this, but it's a good safeguard
167 13
        if (!$this->logger) {
168 1
            $this->setLogger(Injector::inst()->get(LoggerInterface::class));
169
        }
170
171 13
        return $this->logger;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->logger could return the type null which is incompatible with the type-hinted return Psr\Log\LoggerInterface. Consider adding an additional type-check to rule them out.
Loading history...
172
    }
173
174
    /**
175
     * @param LoggerInterface|null $logger
176
     * @return SolrIndexTask
177
     */
178 13
    public function setLogger($logger = null): SolrIndexTask
179
    {
180 13
        $this->logger = $logger;
181
182 13
        return $this;
183
    }
184
185
    /**
186
     * @param $isGroup
187
     * @param $class
188
     * @param BaseIndex $index
189
     * @param int $group
190
     * @return int
191
     * @throws Exception
192
     */
193 12
    private function indexClass($isGroup, $class, BaseIndex $index, int $group): int
194
    {
195 12
        $this->getLogger()->info(sprintf('Indexing %s for %s', $class, $index->getIndexName()), []);
196
197 12
        $batchLength = DocumentFactory::config()->get('batchLength');
198 12
        $groups = (int)ceil($class::get()->count() / $batchLength);
199 12
        while ($group <= $groups) { // Run from oldest to newest
200
            try {
201 12
                $this->getLogger()->info(sprintf('Indexing group %s', $group));
202 12
                $this->doReindex($group, $class, $batchLength, $index);
203
            } catch (RequestException $error) {
204
                $this->getLogger()->error($error->getResponse()->getBody()->__toString());
205
                continue;
206
            }
207
            // If it's a specific group to index, break after the first run
208 12
            if ($isGroup) {
209 2
                break;
210
            }
211 11
            $group++;
212
        }
213
214 12
        return $groups;
215
    }
216
217
    /**
218
     * @param int $group
219
     * @param string $class
220
     * @param int $batchLength
221
     * @param BaseIndex $index
222
     * @throws Exception
223
     */
224 12
    private function doReindex($group, $class, $batchLength, BaseIndex $index): void
225
    {
226
        // Generate filtered list of local records
227 12
        $baseClass = DataObject::getSchema()->baseDataClass($class);
228 12
        $filter = [];
229 12
        $client = $index->getClient();
230
        /** @var DataList|DataObject[] $items */
231 12
        $items = $baseClass::get()
232 12
            ->filter($filter)
233 12
            ->sort('ID ASC')
234 12
            ->limit($batchLength, ($group * $batchLength));
235 12
        $update = $client->createUpdate();
236 12
        if ($items->count()) {
237 11
            $this->service->setInDebugMode($this->debug);
238 11
            $this->service->updateIndex($index, $items, $update);
239 11
            $update->addCommit();
240 11
            $client->update($update);
241
        }
242 12
    }
243
}
244