Passed
Push — sheepy/introspection ( 69e16c...c6c7ca )
by Marco
05:28
created

SolrCoreService::coreReload()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 5
c 0
b 0
f 0
dl 0
loc 10
rs 10
ccs 2
cts 2
cp 1
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Firesphere\SolrSearch\Services;
4
5
use Exception;
6
use Firesphere\SolrSearch\Factories\DocumentFactory;
7
use Firesphere\SolrSearch\Helpers\SearchIntrospection;
8
use Firesphere\SolrSearch\Indexes\BaseIndex;
9
use Firesphere\SolrSearch\Interfaces\ConfigStore;
10
use GuzzleHttp\HandlerStack;
11
use LogicException;
12
use ReflectionClass;
13
use ReflectionException;
14
use SilverStripe\Control\Director;
15
use SilverStripe\Core\ClassInfo;
16
use SilverStripe\Core\Config\Configurable;
17
use SilverStripe\Core\Injector\Injector;
18
use SilverStripe\ORM\ArrayList;
19
use SilverStripe\ORM\DataObject;
20
use SilverStripe\ORM\SS_List;
21
use Solarium\Client;
22
use Solarium\Core\Client\Adapter\Guzzle;
23
use Solarium\QueryType\Server\CoreAdmin\Query\Query;
24
use Solarium\QueryType\Server\CoreAdmin\Result\StatusResult;
25
use Solarium\QueryType\Update\Result;
26
27
class SolrCoreService
28
{
29
    /**
30
     * Unique ID in Solr
31
     */
32
    public const ID_FIELD = 'id';
33
    /**
34
     * SilverStripe ID of the object
35
     */
36
    public const CLASS_ID_FIELD = 'ObjectID';
37
    /**
38
     * Name of the field that can be used for queries
39
     */
40
    public const CLASSNAME = 'ClassName';
41
    /**
42
     * Solr update types
43
     */
44
    public const DELETE_TYPE_ALL = 'deleteall';
45
    public const DELETE_TYPE = 'delete';
46
    public const UPDATE_TYPE = 'update';
47
    public const CREATE_TYPE = 'create';
48
49
50
    use Configurable;
51
52
    /**
53
     * @var Client
54
     */
55
    protected $client;
56
57
    /**
58
     * @var array
59
     */
60
    protected $validIndexes = [];
61
62
    /**
63
     * @var Query
64
     */
65
    protected $admin;
66
67
    /**
68
     * Add debugging information
69
     * @var bool
70
     */
71
    protected $inDebugMode = false;
72
73 30
74
    /**
75 30
     * SolrCoreService constructor.
76 30
     * @throws ReflectionException
77 30
     */
78 30
    public function __construct()
79 30
    {
80 30
        $config = static::config()->get('config');
81
        $this->client = new Client($config);
82
        $this->client->setAdapter(new Guzzle());
83
        $this->admin = $this->client->createCoreAdmin();
84
        $this->filterIndexes();
85 30
    }
86
87 30
    /**
88 30
     * @throws ReflectionException
89 30
     */
90 30
    protected function filterIndexes(): void
91 30
    {
92
        $indexes = ClassInfo::subclassesFor(BaseIndex::class);
93
        $enabledIndexes = static::config()->get('indexes');
94 30
        $enabledIndexes = is_array($enabledIndexes) ? $enabledIndexes : [$enabledIndexes];
95
        foreach ($indexes as $subindex) {
96
            $ref = new ReflectionClass($subindex);
97
            $notEnabled = !in_array($subindex, $enabledIndexes, true);
98
            // If the config of indexes is set, and the requested index isn't in it, skip addition
99
            // Or, the index simply doesn't exist, also a valid option
100
            if ((count($enabledIndexes) && $notEnabled) && $ref->isInstantiable()) {
101
                $this->validIndexes[] = $subindex;
102 2
            }
103
        }
104 2
    }
105
106 2
    /**
107
     * Create a new core
108 2
     * @param $core string - The name of the core
109
     * @param ConfigStore $configStore
110 2
     * @return bool
111
     */
112 2
    public function coreCreate($core, $configStore): bool
113
    {
114 2
        $action = $this->admin->createCreate();
115
116
        $action->setCore($core);
117
        $action->setInstanceDir($configStore->instanceDir($core));
118
        $this->admin->setAction($action);
119
        $response = $this->client->coreAdmin($this->admin);
120
121 12
        return $response->getWasSuccessful();
122
    }
123 12
124 12
    /**
125
     * @param $core
126 12
     * @return StatusResult|null
127
     */
128 12
    public function coreReload($core): ?StatusResult
129
    {
130 12
        $reload = $this->admin->createReload();
131
        $reload->setCore($core);
132
133
        $this->admin->setAction($reload);
134
135
        $response = $this->client->coreAdmin($this->admin);
136
137
        return $response->getStatusResult();
138 1
    }
139
140 1
    /**
141
     * @param string $core
142
     * @return StatusResult|null
143
     * @deprecated backward compatibility stub
144
     */
145
    public function coreIsActive($core): ?StatusResult
146
    {
147 12
        return $this->coreStatus($core);
148
    }
149 12
150 12
    /**
151
     * @param string $core
152 12
     * @return StatusResult|null
153 12
     */
154
    public function coreStatus($core): ?StatusResult
155 12
    {
156
        $status = $this->admin->createStatus();
157
        $status->setCore($core);
158
159
        $this->admin->setAction($status);
160
        $response = $this->client->coreAdmin($this->admin);
161
162
        return $response->getStatusResult();
163 1
    }
164
165 1
    /**
166 1
     * Remove a core from Solr
167
     * @param string $core core name
168 1
     * @return StatusResult|null A result is successful
169 1
     */
170
    public function coreUnload($core): ?StatusResult
171 1
    {
172
        $unload = $this->admin->createUnload();
173
        $unload->setCore($core);
174
175
        $this->admin->setAction($unload);
176
        $response = $this->client->coreAdmin($this->admin);
177
178
        return $response->getStatusResult();
179
    }
180
181
    /**
182 21
     * @param SS_List|DataObject $items
183
     * @param string $type
184 21
     * @param null|string $index
185 1
     * @return bool|Result
186
     * @throws ReflectionException
187 20
     * @throws Exception
188 1
     */
189
    public function updateItems($items, $type, $index = null)
190
    {
191 19
        $indexes = $this->getValidIndexes($index);
192
193 18
        $result = false;
194 18
        $items = ($items instanceof DataObject) ? ArrayList::create([$items]) : $items;
195 18
        $items = ($items instanceof SS_List) ? $items : ArrayList::create($items);
196
197 18
        $hierarchy = SearchIntrospection::getHierarchy($items->first()->ClassName);
198
199 18
        foreach ($indexes as $indexString) {
200
            /** @var BaseIndex $index */
201 18
            $index = Injector::inst()->get($indexString);
202 18
            $classes = $index->getClasses();
203 18
            $inArray = array_intersect($classes, $hierarchy);
204
            // No point in sending a delete|update|create for something that's not in the index
205 18
            if (!count($inArray)) {
206 17
                continue;
207
            }
208
209 3
            $result = $this->doManipulate($items, $type, $index);
210
        }
211
212 18
        return $result;
213
    }
214
215
    /**
216
     * Get valid indexes for the project
217
     * @param null|string $index
218
     * @return array
219
     */
220 28
    public function getValidIndexes($index = null): ?array
221
    {
222 28
        if ($index && !in_array($index, $this->validIndexes, true)) {
223 1
            throw new LogicException('Incorrect index ' . $index);
224
        }
225
226 28
        if ($index) {
227 4
            return [$index];
228
        }
229
230
        // return the array values, to reset the keys
231 27
        return array_values($this->validIndexes);
232
    }
233
234
    /**
235
     * @param SS_List $items
236
     * @param $type
237
     * @param BaseIndex $index
238
     * @return Result
239
     * @throws Exception
240
     */
241 5
    public function doManipulate($items, $type, BaseIndex $index): Result
242
    {
243 5
        $client = $index->getClient();
244
245
        $update = $this->getUpdate($items, $type, $index, $client);
246 5
        // commit immediately when in dev mode
247
        if (Director::isDev()) {
248
            $update->addCommit();
249 5
        }
250
251
        return $client->update($update);
252 1
    }
253 1
254 1
    /**
255 1
     * @param SS_List $items
256 1
     * @param string $type
257
     * @param BaseIndex $index
258 1
     * @param \Solarium\Core\Client\Client $client
259 5
     * @return mixed
260 2
     * @throws Exception
261 2
     */
262 3
    protected function getUpdate($items, $type, BaseIndex $index, \Solarium\Core\Client\Client $client)
263
    {
264 3
        // get an update query instance
265
        $update = $client->createUpdate();
266 5
267
        switch ($type) {
268 5
            case static::DELETE_TYPE:
269
                // By pushing to a single array, we have less memory usage and no duplicates
270
                // This is faster, and more efficient, because we only do one DB query
271
                $delete = $items->map('ID', 'ClassName')->toArray();
272
                array_walk($delete, static function (&$item, $key) {
273
                    $item = sprintf('%s-%s', $item, $key);
274
                });
275
                $update->addDeleteByIds(array_values($delete));
276
                // Remove the deletion array from memory
277 13
                break;
278
            case static::DELETE_TYPE_ALL:
279 13
                $update->addDeleteQuery('*:*');
280 13
                break;
281 13
            case static::UPDATE_TYPE:
282 13
            case static::CREATE_TYPE:
283 13
                $this->updateIndex($index, $items, $update);
284
        }
285 13
286
        return $update;
287
    }
288
289
    /**
290
     * @param BaseIndex $index
291 13
     * @param SS_List $items
292
     * @param \Solarium\QueryType\Update\Query\Query $update
293 13
     * @throws Exception
294 13
     */
295 13
    public function updateIndex($index, $items, $update): void
296 13
    {
297
        $fields = $index->getFieldsForIndexing();
298 13
        $factory = $this->getFactory($items);
299
        $docs = $factory->buildItems($fields, $index, $update);
300
        if (count($docs)) {
301
            $update->addDocuments($docs);
302
        }
303
    }
304 13
305
    /**
306 13
     * @param SS_List $items
307
     * @return DocumentFactory
308
     */
309
    protected function getFactory($items): DocumentFactory
310
    {
311
        $factory = Injector::inst()->get(DocumentFactory::class);
312
        $factory->setItems($items);
313 28
        $factory->setClass($items->first()->ClassName);
314
        $factory->setDebug($this->isInDebugMode());
315 28
316
        return $factory;
317 28
    }
318
319
    /**
320
     * @return bool
321
     */
322
    public function isInDebugMode(): bool
323
    {
324 13
        return $this->inDebugMode;
325
    }
326 13
327 13
    /**
328
     * @param bool $inDebugMode
329 13
     * @return SolrCoreService
330
     */
331
    public function setInDebugMode(bool $inDebugMode): SolrCoreService
332 13
    {
333 1
        $this->inDebugMode = $inDebugMode;
334
335
        return $this;
336 13
    }
337
338 13
    /**
339 13
     * @param HandlerStack|null $handler Used for testing the solr version
340
     * @return int
341 13
     */
342 13
    public function getSolrVersion($handler = null): int
343 13
    {
344 1
        $config = self::config()->get('config');
345
        $firstEndpoint = array_shift($config['endpoint']);
346
        $clientConfig = [
347 13
            'base_uri' => 'http://' . $firstEndpoint['host'] . ':' . $firstEndpoint['port']
348
        ];
349
350
        if ($handler) {
351
            $clientConfig['handler'] = $handler;
352
        }
353 1
354
        $client = new \GuzzleHttp\Client($clientConfig);
355 1
356
        $result = $client->get('solr/admin/info/system');
357
        $result = json_decode($result->getBody(), 1);
358
359
        $solrVersion = 5;
360
        $version = version_compare('5.0.0', $result['lucene']['solr-spec-version']);
361
        if ($version > 0) {
362 1
            $solrVersion = 4;
363
        }
364 1
365
        return $solrVersion;
366 1
    }
367
368
    /**
369
     * @return Client
370
     */
371
    public function getClient(): Client
372
    {
373
        return $this->client;
374
    }
375
376
    /**
377
     * @param Client $client
378
     * @return SolrCoreService
379
     */
380
    public function setClient($client): SolrCoreService
381
    {
382
        $this->client = $client;
383
384
        return $this;
385
    }
386
}
387