Passed
Pull Request — master (#72)
by
unknown
08:48
created

Solr::__isset()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
/**
4
 * (c) Kitodo. Key to digital objects e.V. <[email protected]>
5
 *
6
 * This file is part of the Kitodo and TYPO3 projects.
7
 *
8
 * @license GNU General Public License version 3 or later.
9
 * For the full copyright and license information, please read the
10
 * LICENSE.txt file that was distributed with this source code.
11
 */
12
13
namespace Kitodo\Dlf\Common;
14
15
use Psr\Log\LoggerAwareInterface;
16
use Psr\Log\LoggerAwareTrait;
17
use TYPO3\CMS\Core\Cache\CacheManager;
18
use TYPO3\CMS\Core\Configuration\ExtensionConfiguration;
19
use TYPO3\CMS\Core\Database\ConnectionPool;
20
use TYPO3\CMS\Core\Log\LogManager;
21
use TYPO3\CMS\Core\Utility\GeneralUtility;
22
use TYPO3\CMS\Core\Utility\MathUtility;
23
24
/**
25
 * Solr class for the 'dlf' extension
26
 *
27
 * @author Sebastian Meyer <[email protected]>
28
 * @author Henrik Lochmann <[email protected]>
29
 * @package TYPO3
30
 * @subpackage dlf
31
 * @access public
32
 * @property-read string|null $core This holds the core name for the current instance
33
 * @property-write int $cPid This holds the PID for the configuration
34
 * @property int $limit This holds the max results
35
 * @property-read int $numberOfHits This holds the number of hits for last search
36
 * @property-write array $params This holds the additional query parameters
37
 * @property-read bool $ready Is the Solr service instantiated successfully?
38
 * @property-read \Solarium\Client $service This holds the Solr service object
39
 */
40
class Solr implements LoggerAwareInterface
41
{
42
    use LoggerAwareTrait;
43
44
    /**
45
     * This holds the Solr configuration
46
     *
47
     * @var array
48
     * @access protected
49
     */
50
    protected $config = [];
51
52
    /**
53
     * This holds the core name
54
     *
55
     * @var string|null
56
     * @access protected
57
     */
58
    protected $core = null;
59
60
    /**
61
     * This holds the PID for the configuration
62
     *
63
     * @var int
64
     * @access protected
65
     */
66
    protected $cPid = 0;
67
68
    /**
69
     * The extension key
70
     *
71
     * @var string
72
     * @access public
73
     */
74
    public static $extKey = 'dlf';
75
76
    /**
77
     * This holds the max results
78
     *
79
     * @var int
80
     * @access protected
81
     */
82
    protected $limit = 50000;
83
84
    /**
85
     * This holds the number of hits for last search
86
     *
87
     * @var int
88
     * @access protected
89
     */
90
    protected $numberOfHits = 0;
91
92
    /**
93
     * This holds the additional query parameters
94
     *
95
     * @var array
96
     * @access protected
97
     */
98
    protected $params = [];
99
100
    /**
101
     * Is the search instantiated successfully?
102
     *
103
     * @var bool
104
     * @access protected
105
     */
106
    protected $ready = false;
107
108
    /**
109
     * This holds the singleton search objects with their core as array key
110
     *
111
     * @var array (\Kitodo\Dlf\Common\Solr)
112
     * @access protected
113
     */
114
    protected static $registry = [];
115
116
    /**
117
     * This holds the Solr service object
118
     *
119
     * @var \Solarium\Client
120
     * @access protected
121
     */
122
    protected $service;
123
124
    /**
125
     * Add a new core to Apache Solr
126
     *
127
     * @access public
128
     *
129
     * @param string $core: The name of the new core. If empty, the next available core name is used.
130
     *
131
     * @return string The name of the new core
132
     */
133
    public static function createCore($core = '')
134
    {
135
        // Get next available core name if none given.
136
        if (empty($core)) {
137
            $core = 'dlfCore' . self::getNextCoreNumber();
138
        }
139
        // Get Solr service instance.
140
        $solr = self::getInstance($core);
141
        // Create new core if core with given name doesn't exist.
142
        if ($solr->ready) {
143
            // Core already exists.
144
            return $core;
145
        } else {
146
            // Core doesn't exist yet.
147
            $solrAdmin = self::getInstance();
148
            if ($solrAdmin->ready) {
149
                $query = $solrAdmin->service->createCoreAdmin();
150
                $action = $query->createCreate();
151
                $action->setConfigSet('dlf');
152
                $action->setCore($core);
153
                $action->setDataDir('data');
154
                $action->setInstanceDir($core);
155
                $query->setAction($action);
156
                try {
157
                    $response = $solrAdmin->service->coreAdmin($query);
158
                    if ($response->getWasSuccessful()) {
159
                        // Core successfully created.
160
                        return $core;
161
                    }
162
                } catch (\Exception $e) {
163
                    // Nothing to do here.
164
                }
165
            } else {
166
                $solr->logger->error('Apache Solr not available');
0 ignored issues
show
Bug introduced by
The method error() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

166
                $solr->logger->/** @scrutinizer ignore-call */ 
167
                               error('Apache Solr not available');

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
167
            }
168
        }
169
        return '';
170
    }
171
172
    /**
173
     * Escape all special characters in a query string
174
     *
175
     * @access public
176
     *
177
     * @param string $query: The query string
178
     *
179
     * @return string The escaped query string
180
     */
181
    public static function escapeQuery($query)
182
    {
183
        $helper = GeneralUtility::makeInstance(\Solarium\Core\Query\Helper::class);
184
        // Escape query phrase or term.
185
        if (preg_match('/^".*"$/', $query)) {
186
            return $helper->escapePhrase(trim($query, '"'));
187
        } else {
188
            // Using a modified escape function here to retain whitespace, '*' and '?' for search truncation.
189
            // @see https://github.com/solariumphp/solarium/blob/5.x/src/Core/Query/Helper.php#L70 for reference
190
            /* return $helper->escapeTerm($query); */
191
            return preg_replace('/(\+|-|&&|\|\||!|\(|\)|\{|}|\[|]|\^|"|~|:|\/|\\\)/', '\\\$1', $query);
192
        }
193
    }
194
195
    /**
196
     * Escape all special characters in a query string while retaining valid field queries
197
     *
198
     * @access public
199
     *
200
     * @param string $query: The query string
201
     * @param int $pid: The PID for the field configuration
202
     *
203
     * @return string The escaped query string
204
     */
205
    public static function escapeQueryKeepField($query, $pid)
206
    {
207
        // Is there a field query?
208
        if (preg_match('/^[[:alnum:]]+_[tu][su]i:\(?.*\)?$/', $query)) {
209
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
210
                ->getQueryBuilderForTable('tx_dlf_metadata');
211
212
            // Get all indexed fields.
213
            $fields = [];
214
            $result = $queryBuilder
215
                ->select(
216
                    'tx_dlf_metadata.index_name AS index_name',
217
                    'tx_dlf_metadata.index_tokenized AS index_tokenized',
218
                    'tx_dlf_metadata.index_stored AS index_stored'
219
                )
220
                ->from('tx_dlf_metadata')
221
                ->where(
222
                    $queryBuilder->expr()->eq('tx_dlf_metadata.index_indexed', 1),
223
                    $queryBuilder->expr()->eq('tx_dlf_metadata.pid', intval($pid)),
224
                    $queryBuilder->expr()->orX(
225
                        $queryBuilder->expr()->in('tx_dlf_metadata.sys_language_uid', [-1, 0]),
226
                        $queryBuilder->expr()->eq('tx_dlf_metadata.l18n_parent', 0)
227
                    ),
228
                    Helper::whereExpression('tx_dlf_metadata')
229
                )
230
                ->execute();
231
232
            while ($resArray = $result->fetch()) {
233
                $fields[] = $resArray['index_name'] . '_' . ($resArray['index_tokenized'] ? 't' : 'u') . ($resArray['index_stored'] ? 's' : 'u') . 'i';
234
            }
235
236
            // Check if queried field is valid.
237
            $splitQuery = explode(':', $query, 2);
238
            if (in_array($splitQuery[0], $fields)) {
239
                $query = $splitQuery[0] . ':(' . self::escapeQuery(trim($splitQuery[1], '()')) . ')';
240
            } else {
241
                $query = self::escapeQuery($query);
242
            }
243
        } else {
244
            $query = self::escapeQuery($query);
245
        }
246
        return $query;
247
    }
248
249
    /**
250
     * Get fields for index.
251
     *
252
     * @access public
253
     *
254
     * @return array fields
255
     */
256
    public static function getFields()
257
    {
258
        $conf = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf'][self::$extKey]);
259
260
        $fields = [];
261
        $fields['id'] = $conf['solrFieldId'];
262
        $fields['uid'] = $conf['solrFieldUid'];
263
        $fields['pid'] = $conf['solrFieldPid'];
264
        $fields['page'] = $conf['solrFieldPage'];
265
        $fields['partof'] = $conf['solrFieldPartof'];
266
        $fields['root'] = $conf['solrFieldRoot'];
267
        $fields['sid'] = $conf['solrFieldSid'];
268
        $fields['toplevel'] = $conf['solrFieldToplevel'];
269
        $fields['type'] = $conf['solrFieldType'];
270
        $fields['title'] = $conf['solrFieldTitle'];
271
        $fields['volume'] = $conf['solrFieldVolume'];
272
        $fields['thumbnail'] = $conf['solrFieldThumbnail'];
273
        $fields['default'] = $conf['solrFieldDefault'];
274
        $fields['timestamp'] = $conf['solrFieldTimestamp'];
275
        $fields['autocomplete'] = $conf['solrFieldAutocomplete'];
276
        $fields['fulltext'] = $conf['solrFieldFulltext'];
277
        $fields['record_id'] = $conf['solrFieldRecordId'];
278
        $fields['purl'] = $conf['solrFieldPurl'];
279
        $fields['urn'] = $conf['solrFieldUrn'];
280
        $fields['location'] = $conf['solrFieldLocation'];
281
        $fields['collection'] = $conf['solrFieldCollection'];
282
        $fields['license'] = $conf['solrFieldLicense'];
283
        $fields['terms'] = $conf['solrFieldTerms'];
284
        $fields['restrictions'] = $conf['solrFieldRestrictions'];
285
        $fields['geom'] = $conf['solrFieldGeom'];
286
287
        return $fields;
288
    }
289
290
    /**
291
     * This is a singleton class, thus instances must be created by this method
292
     *
293
     * @access public
294
     *
295
     * @param mixed $core: Name or UID of the core to load or null to get core admin endpoint
296
     *
297
     * @return \Kitodo\Dlf\Common\Solr Instance of this class
298
     */
299
    public static function getInstance($core = null)
300
    {
301
        $logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__);
302
303
        // Get core name if UID is given.
304
        if (MathUtility::canBeInterpretedAsInteger($core)) {
305
            $core = Helper::getIndexNameFromUid($core, 'tx_dlf_solrcores');
306
        }
307
        // Check if core is set or null.
308
        if (
309
            empty($core)
310
            && $core !== null
311
        ) {
312
            $logger->error('Invalid core UID or name given for Apache Solr');
313
        }
314
        if (!empty($core)) {
315
            // Check if there is an instance in the registry already.
316
            if (
317
                is_object(self::$registry[$core])
318
                && self::$registry[$core] instanceof self
319
            ) {
320
                // Return singleton instance if available.
321
                return self::$registry[$core];
322
            }
323
        }
324
        // Create new instance...
325
        $instance = new self($core);
326
        // ...and save it to registry.
327
        if (!empty($instance->core)) {
328
            self::$registry[$instance->core] = $instance;
329
        }
330
        return $instance;
331
    }
332
333
    /**
334
     * Get next unused Solr core number
335
     *
336
     * @access public
337
     *
338
     * @param int $number: Number to start with
339
     *
340
     * @return int First unused core number found
341
     */
342
    public static function getNextCoreNumber($number = 0)
343
    {
344
        $number = max(intval($number), 0);
345
        // Check if core already exists.
346
        $solr = self::getInstance('dlfCore' . $number);
347
        if (!$solr->ready) {
348
            return $number;
349
        } else {
350
            return self::getNextCoreNumber($number + 1);
351
        }
352
    }
353
354
    /**
355
     * Sets the connection information for Solr
356
     *
357
     * @access protected
358
     *
359
     * @return void
360
     */
361
    protected function loadSolrConnectionInfo()
362
    {
363
        if (empty($this->config)) {
364
            $config = [];
365
            // Extract extension configuration.
366
            $conf = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get(self::$extKey);
367
            // Derive Solr scheme
368
            $config['scheme'] = empty($conf['solrHttps']) ? 'http' : 'https';
369
            // Derive Solr host name.
370
            $config['host'] = ($conf['solrHost'] ? $conf['solrHost'] : '127.0.0.1');
371
            // Set username and password.
372
            $config['username'] = $conf['solrUser'];
373
            $config['password'] = $conf['solrPass'];
374
            // Set port if not set.
375
            $config['port'] = MathUtility::forceIntegerInRange($conf['solrPort'], 1, 65535, 8983);
376
            // Trim path of slashes and (re-)add trailing slash if path not empty.
377
            $config['path'] = trim($conf['solrPath'], '/');
378
            if (!empty($config['path'])) {
379
                $config['path'] .= '/';
380
            }
381
            // Add "/solr" API endpoint when using Solarium <5.x
382
                // Todo: Remove when dropping support for Solarium 4.x
383
            if (!\Solarium\Client::checkMinimal('5.0.0')) {
384
                $config['path'] .= 'solr/';
385
            }
386
            // Set connection timeout lower than PHP's max_execution_time.
387
            $max_execution_time = intval(ini_get('max_execution_time')) ?: 30;
388
            $config['timeout'] = MathUtility::forceIntegerInRange($conf['solrTimeout'], 1, $max_execution_time, 10);
389
            $this->config = $config;
390
        }
391
    }
392
393
    /**
394
     * Processes a search request.
395
     *
396
     * @access public
397
     *
398
     * @return \Kitodo\Dlf\Common\DocumentList The result list
399
     */
400
    public function search()
401
    {
402
        $toplevel = [];
403
        // Take over query parameters.
404
        $params = $this->params;
0 ignored issues
show
introduced by
The property params is declared write-only in Kitodo\Dlf\Common\Solr.
Loading history...
405
        $params['filterquery'] = isset($params['filterquery']) ? $params['filterquery'] : [];
406
        // Set some query parameters.
407
        $params['start'] = 0;
408
        $params['rows'] = 0;
409
        // Perform search to determine the total number of hits without fetching them.
410
        $selectQuery = $this->service->createSelect($params);
411
        $results = $this->service->select($selectQuery);
412
        $this->numberOfHits = $results->getNumFound();
0 ignored issues
show
Bug introduced by
The property numberOfHits is declared read-only in Kitodo\Dlf\Common\Solr.
Loading history...
413
        // Restore query parameters
414
        $params = $this->params;
415
        $params['filterquery'] = isset($params['filterquery']) ? $params['filterquery'] : [];
416
        // Restrict the fields to the required ones.
417
        $params['fields'] = 'uid,id';
418
        // Set filter query to just get toplevel documents.
419
        $params['filterquery'][] = ['query' => 'toplevel:true'];
420
        // Set join query to get all documents with the same uids.
421
        $params['query'] = '{!join from=uid to=uid}' . $params['query'];
422
        // Perform search to determine the total number of toplevel hits and fetch the required rows.
423
        $selectQuery = $this->service->createSelect($params);
424
        $results = $this->service->select($selectQuery);
425
        $numberOfToplevelHits = $results->getNumFound();
426
        // Process results.
427
        foreach ($results as $doc) {
428
            $toplevel[$doc->id] = [
429
                'u' => $doc->uid,
430
                'h' => '',
431
                's' => '',
432
                'p' => []
433
            ];
434
        }
435
        // Save list of documents.
436
        $list = GeneralUtility::makeInstance(DocumentList::class);
437
        $list->reset();
438
        $list->add(array_values($toplevel));
439
        // Set metadata for search.
440
        $list->metadata = [
441
            'label' => '',
442
            'description' => '',
443
            'options' => [
444
                'source' => 'search',
445
                'engine' => 'solr',
446
                'select' => $this->params['query'],
447
                'userid' => 0,
448
                'params' => $this->params,
449
                'core' => $this->core,
450
                'pid' => $this->cPid,
0 ignored issues
show
introduced by
The property cPid is declared write-only in Kitodo\Dlf\Common\Solr.
Loading history...
451
                'order' => 'score',
452
                'order.asc' => true,
453
                'numberOfHits' => $this->numberOfHits,
454
                'numberOfToplevelHits' => $numberOfToplevelHits
455
            ]
456
        ];
457
        return $list;
458
    }
459
460
    /**
461
     * Processes a search request and returns the raw Apache Solr Documents.
462
     *
463
     * @access public
464
     *
465
     * @param string $query: The search query
466
     * @param array $parameters: Additional search parameters
467
     *
468
     * @return array The Apache Solr Documents that were fetched
469
     */
470
    public function search_raw($query = '', $parameters = [])
471
    {
472
        // Set additional query parameters.
473
        $parameters['start'] = 0;
474
        $parameters['rows'] = $this->limit;
475
        // Set query.
476
        $parameters['query'] = $query;
477
        // Calculate cache identifier.
478
        $cacheIdentifier = Helper::digest($this->core . print_r(array_merge($this->params, $parameters), true));
0 ignored issues
show
Bug introduced by
Are you sure print_r(array_merge($thi...ms, $parameters), true) of type string|true can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

478
        $cacheIdentifier = Helper::digest($this->core . /** @scrutinizer ignore-type */ print_r(array_merge($this->params, $parameters), true));
Loading history...
introduced by
The property params is declared write-only in Kitodo\Dlf\Common\Solr.
Loading history...
479
        $cache = GeneralUtility::makeInstance(CacheManager::class)->getCache('tx_dlf_solr');
480
        $resultSet = [];
481
        if (($entry = $cache->get($cacheIdentifier)) === false) {
482
            $selectQuery = $this->service->createSelect(array_merge($this->params, $parameters));
483
            $result = $this->service->select($selectQuery);
484
            foreach ($result as $doc) {
485
                $resultSet[] = $doc;
486
            }
487
            // Save value in cache.
488
            $cache->set($cacheIdentifier, $resultSet);
489
        } else {
490
            // Return cache hit.
491
            $resultSet = $entry;
492
        }
493
        return $resultSet;
494
    }
495
496
    /**
497
     * This returns $this->core via __get()
498
     *
499
     * @access protected
500
     *
501
     * @return string|null The core name of the current query endpoint or null if core admin endpoint
502
     */
503
    protected function _getCore()
504
    {
505
        return $this->core;
506
    }
507
508
    /**
509
     * This returns $this->limit via __get()
510
     *
511
     * @access protected
512
     *
513
     * @return int The max number of results
514
     */
515
    protected function _getLimit()
516
    {
517
        return $this->limit;
518
    }
519
520
    /**
521
     * This returns $this->numberOfHits via __get()
522
     *
523
     * @access protected
524
     *
525
     * @return int Total number of hits for last search
526
     */
527
    protected function _getNumberOfHits()
528
    {
529
        return $this->numberOfHits;
530
    }
531
532
    /**
533
     * This returns $this->ready via __get()
534
     *
535
     * @access protected
536
     *
537
     * @return bool Is the search instantiated successfully?
538
     */
539
    protected function _getReady()
540
    {
541
        return $this->ready;
542
    }
543
544
    /**
545
     * This returns $this->service via __get()
546
     *
547
     * @access protected
548
     *
549
     * @return \Solarium\Client Apache Solr service object
550
     */
551
    protected function _getService()
552
    {
553
        return $this->service;
554
    }
555
556
    /**
557
     * This sets $this->cPid via __set()
558
     *
559
     * @access protected
560
     *
561
     * @param int $value: The new PID for the metadata definitions
562
     *
563
     * @return void
564
     */
565
    protected function _setCPid($value)
566
    {
567
        $this->cPid = max(intval($value), 0);
568
    }
569
570
    /**
571
     * This sets $this->limit via __set()
572
     *
573
     * @access protected
574
     *
575
     * @param int $value: The max number of results
576
     *
577
     * @return void
578
     */
579
    protected function _setLimit($value)
580
    {
581
        $this->limit = max(intval($value), 0);
582
    }
583
584
    /**
585
     * This sets $this->params via __set()
586
     *
587
     * @access protected
588
     *
589
     * @param array $value: The query parameters
590
     *
591
     * @return void
592
     */
593
    protected function _setParams(array $value)
594
    {
595
        $this->params = $value;
596
    }
597
598
    /**
599
     * This magic method is called each time an invisible property is referenced from the object
600
     *
601
     * @access public
602
     *
603
     * @param string $var: Name of variable to get
604
     *
605
     * @return mixed Value of $this->$var
606
     */
607
    public function __get($var)
608
    {
609
        $method = '_get' . ucfirst($var);
610
        if (
611
            !property_exists($this, $var)
612
            || !method_exists($this, $method)
613
        ) {
614
            $this->logger->warning('There is no getter function for property "' . $var . '"');
0 ignored issues
show
Bug introduced by
The method warning() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

614
            $this->logger->/** @scrutinizer ignore-call */ 
615
                           warning('There is no getter function for property "' . $var . '"');

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
615
            return;
616
        } else {
617
            return $this->$method();
618
        }
619
    }
620
621
    /**
622
     * This magic method is called each time an invisible property is checked for isset() or empty()
623
     *
624
     * @access public
625
     *
626
     * @param string $var: Name of variable to check
627
     *
628
     * @return bool true if variable is set and not empty, false otherwise
629
     */
630
    public function __isset($var)
631
    {
632
        return !empty($this->__get($var));
633
    }
634
635
    /**
636
     * This magic method is called each time an invisible property is referenced from the object
637
     *
638
     * @access public
639
     *
640
     * @param string $var: Name of variable to set
641
     * @param mixed $value: New value of variable
642
     *
643
     * @return void
644
     */
645
    public function __set($var, $value)
646
    {
647
        $method = '_set' . ucfirst($var);
648
        if (
649
            !property_exists($this, $var)
650
            || !method_exists($this, $method)
651
        ) {
652
            $this->logger->warning('There is no setter function for property "' . $var . '"');
653
        } else {
654
            $this->$method($value);
655
        }
656
    }
657
658
    /**
659
     * This is a singleton class, thus the constructor should be private/protected
660
     *
661
     * @access protected
662
     *
663
     * @param string|null $core: The name of the core to use or null for core admin endpoint
664
     *
665
     * @return void
666
     */
667
    protected function __construct($core)
668
    {
669
        // Get Solr connection parameters from configuration.
670
        $this->loadSolrConnectionInfo();
671
        // Configure connection adapter.
672
        $adapter = GeneralUtility::makeInstance(\Solarium\Core\Client\Adapter\Http::class);
673
            // Todo: When updating to TYPO3 >=10.x and Solarium >=6.x
674
            // the timeout must be set with the adapter instead of the
675
            // endpoint (see below).
676
            // $adapter->setTimeout($this->config['timeout']);
677
        // Configure event dispatcher.
678
            // Todo: When updating to TYPO3 >=10.x and Solarium >=6.x
679
            // we have to provide an PSR-14 Event Dispatcher instead of
680
            // "null".
681
            // $eventDispatcher = GeneralUtility::makeInstance(\TYPO3\CMS\Core\EventDispatcher\EventDispatcher::class);
682
        // Configure endpoint.
683
        $config = [
684
            'endpoint' => [
685
                'default' => [
686
                    'scheme' => $this->config['scheme'],
687
                    'host' => $this->config['host'],
688
                    'port' => $this->config['port'],
689
                    'path' => '/' . $this->config['path'],
690
                    'core' => $core,
691
                    'username' => $this->config['username'],
692
                    'password' => $this->config['password'],
693
                    'timeout' => $this->config['timeout'] // Remove when upgrading to Solarium 6.x
694
                ]
695
            ]
696
        ];
697
        // Instantiate Solarium\Client class.
698
        $this->service = GeneralUtility::makeInstance(\Solarium\Client::class, $config);
0 ignored issues
show
Bug introduced by
The property service is declared read-only in Kitodo\Dlf\Common\Solr.
Loading history...
699
        $this->service->setAdapter($adapter);
700
            // Todo: When updating to TYPO3 >=10.x and Solarium >=6.x
701
            // $adapter and $eventDispatcher are mandatory arguments
702
            // of the \Solarium\Client constructor.
703
            // $this->service = GeneralUtility::makeInstance(\Solarium\Client::class, $adapter, $eventDispatcher, $config);
704
        // Check if connection is established.
705
        $query = $this->service->createCoreAdmin();
706
        $action = $query->createStatus();
707
        if ($core !== null) {
708
            $action->setCore($core);
709
        }
710
        $query->setAction($action);
711
        try {
712
            $response = $this->service->coreAdmin($query);
713
            if ($response->getWasSuccessful()) {
714
                // Solr is reachable, but is the core as well?
715
                if ($core !== null) {
716
                    $result = $response->getStatusResult();
717
                    if (
718
                        $result instanceof \Solarium\QueryType\Server\CoreAdmin\Result\StatusResult
719
                        && $result->getUptime() > 0
720
                    ) {
721
                        // Set core name.
722
                        $this->core = $core;
0 ignored issues
show
Bug introduced by
The property core is declared read-only in Kitodo\Dlf\Common\Solr.
Loading history...
723
                    } else {
724
                        // Core not available.
725
                        return;
726
                    }
727
                }
728
                // Instantiation successful!
729
                $this->ready = true;
0 ignored issues
show
Bug introduced by
The property ready is declared read-only in Kitodo\Dlf\Common\Solr.
Loading history...
730
            }
731
        } catch (\Exception $e) {
732
            // Nothing to do here.
733
        }
734
    }
735
}
736