Scrutinizer GitHub App not installed

We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.

Install GitHub App

GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Pull Request — master (#624)
by Alexander
08:38
created

Solr::search_raw()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 15
c 0
b 0
f 0
dl 0
loc 24
rs 9.7666
cc 3
nc 2
nop 2
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');
1 ignored issue
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
        $conf = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf'][self::$extKey]);
258
259
        $fields = [];
260
        $fields['id'] = $conf['solrFieldId'];
261
        $fields['uid'] = $conf['solrFieldUid'];
262
        $fields['pid'] = $conf['solrFieldPid'];
263
        $fields['page'] = $conf['solrFieldPage'];
264
        $fields['partof'] = $conf['solrFieldPartof'];
265
        $fields['root'] = $conf['solrFieldRoot'];
266
        $fields['sid'] = $conf['solrFieldSid'];
267
        $fields['toplevel'] = $conf['solrFieldToplevel'];
268
        $fields['type'] = $conf['solrFieldType'];
269
        $fields['title'] = $conf['solrFieldTitle'];
270
        $fields['volume'] = $conf['solrFieldVolume'];
271
        $fields['thumbnail'] = $conf['solrFieldThumbnail'];
272
        $fields['default'] = $conf['solrFieldDefault'];
273
        $fields['timestamp'] = $conf['solrFieldTimestamp'];
274
        $fields['autocomplete'] = $conf['solrFieldAutocomplete'];
275
        $fields['fulltext'] = $conf['solrFieldFulltext'];
276
        $fields['record_id'] = $conf['solrFieldRecordId'];
277
        $fields['purl'] = $conf['solrFieldPurl'];
278
        $fields['urn'] = $conf['solrFieldUrn'];
279
        $fields['location'] = $conf['solrFieldLocation'];
280
        $fields['collection'] = $conf['solrFieldCollection'];
281
        $fields['license'] = $conf['solrFieldLicense'];
282
        $fields['terms'] = $conf['solrFieldTerms'];
283
        $fields['restrictions'] = $conf['solrFieldRestrictions'];
284
        $fields['geom'] = $conf['solrFieldGeom'];
285
286
        return $fields;
287
    }
288
289
    /**
290
     * This is a singleton class, thus instances must be created by this method
291
     *
292
     * @access public
293
     *
294
     * @param mixed $core: Name or UID of the core to load or null to get core admin endpoint
295
     *
296
     * @return \Kitodo\Dlf\Common\Solr Instance of this class
297
     */
298
    public static function getInstance($core = null)
299
    {
300
        $logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__);
301
302
        // Get core name if UID is given.
303
        if (MathUtility::canBeInterpretedAsInteger($core)) {
304
            $core = Helper::getIndexNameFromUid($core, 'tx_dlf_solrcores');
305
        }
306
        // Check if core is set or null.
307
        if (
308
            empty($core)
309
            && $core !== null
310
        ) {
311
            $logger->error('Invalid core UID or name given for Apache Solr');
312
        }
313
        if (!empty($core)) {
314
            // Check if there is an instance in the registry already.
315
            if (
316
                is_object(self::$registry[$core])
317
                && self::$registry[$core] instanceof self
318
            ) {
319
                // Return singleton instance if available.
320
                return self::$registry[$core];
321
            }
322
        }
323
        // Create new instance...
324
        $instance = new self($core);
325
        // ...and save it to registry.
326
        if (!empty($instance->core)) {
327
            self::$registry[$instance->core] = $instance;
328
        }
329
        return $instance;
330
    }
331
332
    /**
333
     * Get next unused Solr core number
334
     *
335
     * @access public
336
     *
337
     * @param int $number: Number to start with
338
     *
339
     * @return int First unused core number found
340
     */
341
    public static function getNextCoreNumber($number = 0)
342
    {
343
        $number = max(intval($number), 0);
344
        // Check if core already exists.
345
        $solr = self::getInstance('dlfCore' . $number);
346
        if (!$solr->ready) {
347
            return $number;
348
        } else {
349
            return self::getNextCoreNumber($number + 1);
350
        }
351
    }
352
353
    /**
354
     * Sets the connection information for Solr
355
     *
356
     * @access protected
357
     *
358
     * @return void
359
     */
360
    protected function loadSolrConnectionInfo()
361
    {
362
        if (empty($this->config)) {
363
            $config = [];
364
            // Extract extension configuration.
365
            $conf = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get(self::$extKey);
366
            // Derive Solr scheme
367
            $config['scheme'] = empty($conf['solrHttps']) ? 'http' : 'https';
368
            // Derive Solr host name.
369
            $config['host'] = ($conf['solrHost'] ? $conf['solrHost'] : '127.0.0.1');
370
            // Set username and password.
371
            $config['username'] = $conf['solrUser'];
372
            $config['password'] = $conf['solrPass'];
373
            // Set port if not set.
374
            $config['port'] = MathUtility::forceIntegerInRange($conf['solrPort'], 1, 65535, 8983);
375
            // Trim path of slashes and (re-)add trailing slash if path not empty.
376
            $config['path'] = trim($conf['solrPath'], '/');
377
            if (!empty($config['path'])) {
378
                $config['path'] .= '/';
379
            }
380
            // Add "/solr" API endpoint when using Solarium <5.x
381
                // Todo: Remove when dropping support for Solarium 4.x
382
            if (!\Solarium\Client::checkMinimal('5.0.0')) {
383
                $config['path'] .= 'solr/';
384
            }
385
            // Set connection timeout lower than PHP's max_execution_time.
386
            $max_execution_time = intval(ini_get('max_execution_time')) ?: 30;
387
            $config['timeout'] = MathUtility::forceIntegerInRange($conf['solrTimeout'], 1, $max_execution_time, 10);
388
            $this->config = $config;
389
        }
390
    }
391
392
    /**
393
     * Processes a search request.
394
     *
395
     * @access public
396
     *
397
     * @return \Kitodo\Dlf\Common\DocumentList The result list
398
     */
399
    public function search()
400
    {
401
        $toplevel = [];
402
        // Take over query parameters.
403
        $params = $this->params;
404
        $params['filterquery'] = isset($params['filterquery']) ? $params['filterquery'] : [];
405
        // Set some query parameters.
406
        $params['start'] = 0;
407
        $params['rows'] = 0;
408
        // Perform search to determine the total number of hits without fetching them.
409
        $selectQuery = $this->service->createSelect($params);
410
        $results = $this->service->select($selectQuery);
411
        $this->numberOfHits = $results->getNumFound();
412
        // Restore query parameters
413
        $params = $this->params;
414
        $params['filterquery'] = isset($params['filterquery']) ? $params['filterquery'] : [];
415
        // Restrict the fields to the required ones.
416
        $params['fields'] = 'uid,id';
417
        // Set filter query to just get toplevel documents.
418
        $params['filterquery'][] = ['query' => 'toplevel:true'];
419
        // Set join query to get all documents with the same uids.
420
        $params['query'] = '{!join from=uid to=uid}' . $params['query'];
421
        // Perform search to determine the total number of toplevel hits and fetch the required rows.
422
        $selectQuery = $this->service->createSelect($params);
423
        $results = $this->service->select($selectQuery);
424
        $numberOfToplevelHits = $results->getNumFound();
425
        // Process results.
426
        foreach ($results as $doc) {
427
            $toplevel[$doc->id] = [
428
                'u' => $doc->uid,
429
                'h' => '',
430
                's' => '',
431
                'p' => []
432
            ];
433
        }
434
        // Save list of documents.
435
        $list = GeneralUtility::makeInstance(DocumentList::class);
436
        $list->reset();
437
        $list->add(array_values($toplevel));
438
        // Set metadata for search.
439
        $list->metadata = [
440
            'label' => '',
441
            'description' => '',
442
            'options' => [
443
                'source' => 'search',
444
                'engine' => 'solr',
445
                'select' => $this->params['query'],
446
                'userid' => 0,
447
                'params' => $this->params,
448
                'core' => $this->core,
449
                'pid' => $this->cPid,
450
                'order' => 'score',
451
                'order.asc' => true,
452
                'numberOfHits' => $this->numberOfHits,
453
                'numberOfToplevelHits' => $numberOfToplevelHits
454
            ]
455
        ];
456
        return $list;
457
    }
458
459
    /**
460
     * Processes a search request and returns the raw Apache Solr Documents.
461
     *
462
     * @access public
463
     *
464
     * @param string $query: The search query
465
     * @param array $parameters: Additional search parameters
466
     *
467
     * @return array The Apache Solr Documents that were fetched
468
     */
469
    public function search_raw($query = '', $parameters = [])
470
    {
471
        // Set additional query parameters.
472
        $parameters['start'] = 0;
473
        $parameters['rows'] = $this->limit;
474
        // Set query.
475
        $parameters['query'] = $query;
476
        // Calculate cache identifier.
477
        $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

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

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