Passed
Push — master ( 30aafa...d3e80f )
by Timo
04:19
created

AbstractSolrService::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 3
crap 1
1
<?php
2
namespace ApacheSolrForTypo3\Solr\System\Solr\Service;
3
4
/***************************************************************
5
 *  Copyright notice
6
 *
7
 *  (c) 2009-2017 Timo Hund <[email protected]>
8
 *  All rights reserved
9
 *
10
 *  This script is part of the TYPO3 project. The TYPO3 project is
11
 *  free software; you can redistribute it and/or modify
12
 *  it under the terms of the GNU General Public License as published by
13
 *  the Free Software Foundation; either version 3 of the License, or
14
 *  (at your option) any later version.
15
 *
16
 *  The GNU General Public License can be found at
17
 *  http://www.gnu.org/copyleft/gpl.html.
18
 *
19
 *  This script is distributed in the hope that it will be useful,
20
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 *  GNU General Public License for more details.
23
 *
24
 *  This copyright notice MUST APPEAR in all copies of the script!
25
 ***************************************************************/
26
27
use ApacheSolrForTypo3\Solr\PingFailedException;
28
use ApacheSolrForTypo3\Solr\System\Configuration\TypoScriptConfiguration;
29
use ApacheSolrForTypo3\Solr\System\Logging\SolrLogManager;
30
use ApacheSolrForTypo3\Solr\System\Solr\ResponseAdapter;
31
use ApacheSolrForTypo3\Solr\Util;
32
33
use Solarium\Client;
34
use Solarium\Core\Client\Endpoint;
35
use Solarium\Core\Client\Request;
36
use Solarium\Core\Query\QueryInterface;
37
use Solarium\Exception\HttpException;
38
use TYPO3\CMS\Core\Utility\GeneralUtility;
39
40
abstract class AbstractSolrService {
41
42
    /**
43
     * @var array
44
     */
45
    protected static $pingCache = [];
46
47
    /**
48
     * @var TypoScriptConfiguration
49
     */
50
    protected $configuration;
51
52
    /**
53
     * @var \ApacheSolrForTypo3\Solr\System\Logging\SolrLogManager
54
     */
55
    protected $logger = null;
56
57
    /**
58
     * @var Client
59
     */
60
    protected $client = null;
61
62
    /**
63
     * SolrReadService constructor.
64
     */
65 132
    public function __construct(Client $client, $typoScriptConfiguration = null, $logManager = null)
66
    {
67 132
        $this->client = $client;
68 132
        $this->configuration = $typoScriptConfiguration ?? Util::getSolrConfiguration();
69 132
        $this->logger = $logManager ?? GeneralUtility::makeInstance(SolrLogManager::class, /** @scrutinizer ignore-type */ __CLASS__);
70 132
    }
71
72
    /**
73
     * Returns the path to the core solr path + core path.
74
     *
75
     * @return string
76
     */
77
    public function getCorePath()
78
    {
79
        $endpoint = $this->getPrimaryEndpoint();
80
        return is_null($endpoint) ? '' : $endpoint->getPath() .'/'. $endpoint->getCore();
81
    }
82
83
    /**
84
     * Return a valid http URL given this server's host, port and path and a provided servlet name
85
     *
86
     * @param string $servlet
87
     * @param array $params
88
     * @return string
89
     */
90
    protected function _constructUrl($servlet, $params = [])
91
    {
92
        $queryString = count($params) ? '?' . http_build_query($params, null, '&') : '';
93
        return $this->__toString() . $servlet . $queryString;
94
    }
95
96
    /**
97
     * Creates a string representation of the Solr connection. Specifically
98
     * will return the Solr URL.
99
     *
100
     * @return string The Solr URL.
101
     */
102
    public function __toString()
103
    {
104
        $endpoint = $this->getPrimaryEndpoint();
105
        if (!$endpoint instanceof Endpoint) {
106
            return '';
107
        }
108
109
        return  $endpoint->getScheme(). '://' . $endpoint->getHost() . ':' . $endpoint->getPort() . $endpoint->getPath() . '/' . $endpoint->getCore() . '/';
110
    }
111
112
    /**
113
     * @return Endpoint|null
114
     */
115
    public function getPrimaryEndpoint()
116
    {
117
        return is_array($this->client->getEndpoints()) ? reset($this->client->getEndpoints()) : null;
0 ignored issues
show
introduced by
The condition is_array($this->client->getEndpoints()) is always true.
Loading history...
118
    }
119
120
    /**
121
     * Central method for making a get operation against this Solr Server
122
     *
123
     * @param string $url
124 2
     * @return ResponseAdapter
125
     */
126 2
    protected function _sendRawGet($url)
127 2
    {
128
        return $this->_sendRawRequest($url, Request::METHOD_GET);
129
    }
130
131
    /**
132
     * Central method for making a HTTP DELETE operation against the Solr server
133
     *
134
     * @param string $url
135
     * @return ResponseAdapter
136
     */
137
    protected function _sendRawDelete($url)
138
    {
139
        return $this->_sendRawRequest($url, Request::METHOD_DELETE);
140
    }
141
142
    /**
143
     * Central method for making a post operation against this Solr Server
144
     *
145
     * @param string $url
146
     * @param string $rawPost
147
     * @param string $contentType
148
     * @return ResponseAdapter
149
     */
150
    protected function _sendRawPost($url, $rawPost, $contentType = 'text/xml; charset=UTF-8')
151
    {
152
        $initializeRequest = function(Request $request) use ($rawPost, $contentType) {
153
            $request->setRawData($rawPost);
154
            $request->addHeader('Content-Type: ' . $contentType);
155
            return $request;
156
        };
157
158
        return $this->_sendRawRequest($url, Request::METHOD_POST, $rawPost, $initializeRequest);
159
    }
160
161
    /**
162
     * Method that performs an http request with the solarium client.
163 21
     *
164
     * @param string $url
165 21
     * @param string $method
166 21
     * @param string $body
167
     * @param \Closure $initializeRequest
168
     * @return ResponseAdapter
169
     */
170
    protected function _sendRawRequest($url, $method = Request::METHOD_GET, $body = '', \Closure $initializeRequest = null)
171
    {
172
        $logSeverity = SolrLogManager::INFO;
173
        $exception = null;
174
175 93
        try {
176
            $request = $this->buildSolariumRequestFromUrl($url, $method);
177 93
178 93
            if($initializeRequest !== null) {
179 2
                $request = $initializeRequest($request);
180
            }
181
182 91
            $response = $this->executeRequest($request);
183
        } catch (HttpException $exception) {
184
            $logSeverity = SolrLogManager::ERROR;
185
            $response = new ResponseAdapter($exception->getBody(), $exception->getCode(), $exception->getMessage());
186
        }
187
188 98
        if ($this->configuration->getLoggingQueryRawPost() || $response->getHttpStatus() != 200) {
189
            $message = 'Querying Solr using '.$method;
190 98
            $this->writeLog($logSeverity, $message, $url, $response, $exception, $body);
191
        }
192
193
        return $response;
194
    }
195
196
    /**
197
     * Build the log data and writes the message to the log
198
     *
199 16
     * @param integer $logSeverity
200
     * @param string $message
201 16
     * @param string $url
202
     * @param ResponseAdapter $solrResponse
203
     * @param \Exception $exception
204
     * @param string $contentSend
205
     */
206
    protected function writeLog($logSeverity, $message, $url, $solrResponse, $exception = null, $contentSend = '')
207
    {
208
        $logData = $this->buildLogDataFromResponse($solrResponse, $exception, $url, $contentSend);
209
        $this->logger->log($logSeverity, $message, $logData);
210 4
    }
211
212 4
    /**
213
     * Parses the solr information to build data for the logger.
214
     *
215
     * @param ResponseAdapter $solrResponse
216
     * @param \Exception $e
217
     * @param string $url
218
     * @param string $contentSend
219
     * @return array
220
     */
221
    protected function buildLogDataFromResponse(ResponseAdapter $solrResponse, \Exception $e = null, $url = '', $contentSend = '')
222
    {
223
        $logData = ['query url' => $url, 'response' => (array)$solrResponse];
224
225 4
        if ($contentSend !== '') {
226 4
            $logData['content'] = $contentSend;
227 4
        }
228 4
229 4
        if (!empty($e)) {
230
            $logData['exception'] = $e->__toString();
231 4
            return $logData;
232
        } else {
233
            // trigger data parsing
234
            $solrResponse->response;
235
            $logData['response data'] = print_r($solrResponse, true);
236
            return $logData;
237
        }
238
    }
239
240
    /**
241
     * Call the /admin/ping servlet, can be used to quickly tell if a connection to the
242
     * server is available.
243 16
     *
244
     * Simply overrides the SolrPhpClient implementation, changing ping from a
245 16
     * HEAD to a GET request, see http://forge.typo3.org/issues/44167
246 16
     *
247
     * Also does not report the time, see https://forge.typo3.org/issues/64551
248
     *
249 16
     * @param boolean $useCache indicates if the ping result should be cached in the instance or not
250
     * @return bool TRUE if Solr can be reached, FALSE if not
251 16
     */
252 4
    public function ping($useCache = true)
253
    {
254
        try {
255 16
            $httpResponse = $this->performPingRequest($useCache);
256 3
        } catch (HttpException $exception) {
257 3
            return false;
258 3
        }
259
260
        return ($httpResponse->getHttpStatus() === 200);
261 16
    }
262 3
263 3
    /**
264
     * Call the /admin/ping servlet, can be used to get the runtime of a ping request.
265
     *
266 16
     * @param boolean $useCache indicates if the ping result should be cached in the instance or not
267
     * @return double runtime in milliseconds
268
     * @throws \ApacheSolrForTypo3\Solr\PingFailedException
269
     */
270
    public function getPingRoundTripRuntime($useCache = true)
271
    {
272
        try {
273
            $start = $this->getMilliseconds();
274
            $httpResponse = $this->performPingRequest($useCache);
275
            $end = $this->getMilliseconds();
276
        } catch (HttpException $e) {
277
            $message = 'Solr ping failed with unexpected response code: ' . $e->getCode();
278
            /** @var $exception \ApacheSolrForTypo3\Solr\PingFailedException */
279 3
            $exception = GeneralUtility::makeInstance(PingFailedException::class, /** @scrutinizer ignore-type */ $message);
280
            throw $exception;
281 3
        }
282 3
283 3
        if ($httpResponse->getHttpStatus() !== 200) {
284
            $message = 'Solr ping failed with unexpected response code: ' . $httpResponse->getHttpStatus();
285
            /** @var $exception \ApacheSolrForTypo3\Solr\PingFailedException */
286
            $exception = GeneralUtility::makeInstance(PingFailedException::class, /** @scrutinizer ignore-type */ $message);
287
            throw $exception;
288
        }
289
290
        return $end - $start;
291
    }
292
293
    /**
294 3
     * Performs a ping request and returns the result.
295
     *
296 3
     * @param boolean $useCache indicates if the ping result should be cached in the instance or not
297
     * @return ResponseAdapter
298 3
     */
299
    protected function performPingRequest($useCache = true)
300
    {
301
        $cacheKey = (string)($this);
302 3
        if ($useCache && isset(static::$pingCache[$cacheKey])) {
303 3
            return static::$pingCache[$cacheKey];
304 3
        }
305
306
        $pingQuery = $this->client->createPing();
307
        $pingResult = $this->createAndExecuteRequest($pingQuery);
308
309
        if ($useCache) {
310
            static::$pingCache[$cacheKey] = $pingResult;
311
        }
312
313
        return $pingResult;
314
    }
315
316
    /**
317
     * Returns the current time in milliseconds.
318
     *
319
     * @return double
320
     */
321
    protected function getMilliseconds()
322
    {
323
        return GeneralUtility::milliseconds();
324
    }
325 74
326
    /**
327
     * @param QueryInterface $query
328 74
     * @return ResponseAdapter
329
     */
330
    protected function createAndExecuteRequest(QueryInterface $query): ResponseAdapter
331
    {
332
        $request = $this->client->createRequest($query);
333 74
        return $this->executeRequest($request);
334
    }
335
336
    /**
337
     * @param $request
338
     * @return ResponseAdapter
339
     */
340
    protected function executeRequest($request): ResponseAdapter
341
    {
342
        $result = $this->client->executeRequest($request);
343 3
        return new ResponseAdapter($result->getBody(), $result->getStatusCode(), $result->getStatusMessage());
344
    }
345
346 3
    /**
347 3
     * @param string $url
348 2
     * @param string $httpMethod
349 1
     * @return Request
350 1
     */
351
    protected function buildSolariumRequestFromUrl($url, $httpMethod = Request::METHOD_GET): Request
352 1
    {
353 1
        $params = [];
354
        parse_str(parse_url($url, PHP_URL_QUERY), $params);
355
356 2
        $path = parse_url($url, PHP_URL_PATH);
357
        $endpoint = $this->getPrimaryEndpoint();
358
        $coreBasePath = $endpoint->getPath() . '/' . $endpoint->getCore() . '/';
359
        $handler = str_replace($coreBasePath, '', $path);
360
361
        $request = new Request();
362
        $request->setMethod($httpMethod);
363 2
        $request->setParams($params);
364
        $request->setHandler($handler);
365
        return $request;
366
    }
367
}