Passed
Push — master ( 453a61...e3ace3 )
by Timo
04:17
created

Search::getNumberOfResults()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 4
ccs 0
cts 3
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2

1 Method

Rating   Name   Duplication   Size   Complexity  
A Search::getResultOffset() 0 3 1
1
<?php
2
namespace ApacheSolrForTypo3\Solr;
3
4
/***************************************************************
5
 *  Copyright notice
6
 *
7
 *  (c) 2009-2015 Ingo Renner <[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\Domain\Search\Query\Query;
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\System\Solr\SolrCommunicationException;
32
use ApacheSolrForTypo3\Solr\System\Solr\SolrConnection;
33
use Solarium\Exception\HttpException;
34
use TYPO3\CMS\Core\Utility\GeneralUtility;
35
36
/**
37
 * Class to handle solr search requests
38
 *
39
 * @author Ingo Renner <[email protected]>
40
 */
41
class Search
42
{
43
44
    /**
45
     * An instance of the Solr service
46
     *
47
     * @var SolrConnection
48
     */
49
    protected $solr = null;
50
51
    /**
52
     * The search query
53
     *
54
     * @var Query
55
     */
56
    protected $query = null;
57
58
    /**
59
     * The search response
60
     *
61
     * @var ResponseAdapter
62
     */
63
    protected $response = null;
64
65
    /**
66
     * @var TypoScriptConfiguration
67
     */
68
    protected $configuration;
69
70
    // TODO Override __clone to reset $response and $hasSearched
71
72
    /**
73
     * @var \ApacheSolrForTypo3\Solr\System\Logging\SolrLogManager
74
     */
75
    protected $logger = null;
76
77
    /**
78
     * Constructor
79
     *
80
     * @param SolrConnection $solrConnection The Solr connection to use for searching
81
     */
82 58
    public function __construct(SolrConnection $solrConnection = null)
83
    {
84 58
        $this->logger = GeneralUtility::makeInstance(SolrLogManager::class, /** @scrutinizer ignore-type */ __CLASS__);
85
86 58
        $this->solr = $solrConnection;
87
88 58
        if (is_null($solrConnection)) {
89
            /** @var $connectionManager ConnectionManager */
90 7
            $connectionManager = GeneralUtility::makeInstance(ConnectionManager::class);
91 7
            $this->solr = $connectionManager->getConnectionByPageId($GLOBALS['TSFE']->id, $GLOBALS['TSFE']->sys_language_uid);
92
        }
93
94 58
        $this->configuration = Util::getSolrConfiguration();
95 58
    }
96
97
    /**
98
     * Gets the Solr connection used by this search.
99
     *
100
     * @return SolrConnection Solr connection
101
     */
102
    public function getSolrConnection()
103
    {
104
        return $this->solr;
105
    }
106
107
    /**
108
     * Sets the Solr connection used by this search.
109
     *
110
     * Since ApacheSolrForTypo3\Solr\Search is a \TYPO3\CMS\Core\SingletonInterface, this is needed to
111
     * be able to switch between multiple cores/connections during
112
     * one request
113
     *
114
     * @param SolrConnection $solrConnection
115
     */
116
    public function setSolrConnection(SolrConnection $solrConnection)
117
    {
118
        $this->solr = $solrConnection;
119
    }
120
121
    /**
122
     * Executes a query against a Solr server.
123
     *
124
     * 1) Gets the query string
125
     * 2) Conducts the actual search
126
     * 3) Checks debug settings
127
     *
128
     * @param Query $query The query with keywords, filters, and so on.
129
     * @param int $offset Result offset for pagination.
130
     * @param int $limit Maximum number of results to return. If set to NULL, this value is taken from the query object.
131
     * @return ResponseAdapter Solr response
132
     * @throws \Exception
133
     */
134 52
    public function search(Query $query, $offset = 0, $limit = 10)
135
    {
136 52
        $this->query = $query;
137
138 52
        if (!empty($limit)) {
139 12
            $query->setRows($limit);
140
        }
141 52
        $query->setStart($offset);
142
143
        try {
144 52
            $response = $this->solr->getReadService()->search($query);
145 50
            if ($this->configuration->getLoggingQueryQueryString()) {
146
                $this->logger->log(SolrLogManager::INFO,
147
                    'Querying Solr, getting result',
148
                    [
149
                        'query string' => $query->getQuery(),
150
                        'query parameters' => $query->getRequestBuilder()->build($query)->getParams(),
151 50
                        'response' => json_decode($response->getRawResponse(), true)
152
                    ]
153
                );
154
            }
155 2
        }  catch (SolrCommunicationException $e) {
156 2
            if ($this->configuration->getLoggingExceptions()) {
157 2
                $this->logger->log(
158 2
                    SolrLogManager::ERROR,
159 2
                    'Exception while querying Solr',
160
                    [
161 2
                        'exception' => $e->__toString(),
162 2
                        'query' => (array)$query,
163 2
                        'offset' => $offset,
164 2
                        'limit' => $query->getRows()
165
                    ]
166
                );
167
            }
168
169 2
            throw $e;
170
        }
171
172 50
        $this->response = $response;
173
174 50
        return $this->response;
175
    }
176
177
    /**
178
     * Sends a ping to the solr server to see whether it is available.
179
     *
180
     * @param bool $useCache Set to true if the cache should be used.
181
     * @return bool Returns TRUE on successful ping.
182
     * @throws \Exception Throws an exception in case ping was not successful.
183
     */
184
    public function ping($useCache = true)
185
    {
186
        $solrAvailable = false;
187
188
        try {
189
            if (!$this->solr->getReadService()->ping($useCache)) {
190
                throw new \Exception('Solr Server not responding.', 1237475791);
191
            }
192
193
            $solrAvailable = true;
194
        } catch (\Exception $e) {
195
            if ($this->configuration->getLoggingExceptions()) {
196
                $this->logger->log(
197
                    SolrLogManager::ERROR,
198
                    'Exception while trying to ping the solr server',
199
                    [
200
                        $e->__toString()
201
                    ]
202
                );
203
            }
204
        }
205
206
        return $solrAvailable;
207
    }
208
209
    /**
210
     * Gets the query object.
211
     *
212
     * @return Query
213
     */
214 32
    public function getQuery()
215
    {
216 32
        return $this->query;
217
    }
218
219
    /**
220
     * Gets the Solr response
221
     *
222
     * @return ResponseAdapter
223
     */
224 27
    public function getResponse()
225
    {
226 27
        return $this->response;
227
    }
228
229
    public function getRawResponse()
230
    {
231
        return $this->response->getRawResponse();
232
    }
233
234 27
    public function getResponseHeader()
235
    {
236 27
        return $this->getResponse()->responseHeader;
237
    }
238
239 27
    public function getResponseBody()
240
    {
241 27
        return $this->getResponse()->response;
242
    }
243
244
    /**
245
     * Gets the time Solr took to execute the query and return the result.
246
     *
247
     * @return int Query time in milliseconds
248
     */
249 27
    public function getQueryTime()
250
    {
251 27
        return $this->getResponseHeader()->QTime;
252
    }
253
254
    /**
255
     * Gets the number of results per page.
256
     *
257
     * @return int Number of results per page
258
     */
259
    public function getResultsPerPage()
260
    {
261
        return $this->getResponseHeader()->params->rows;
262
    }
263
264
    /**
265
     * Gets the result offset.
266
     *
267
     * @return int Result offset
268
     */
269
    public function getResultOffset()
270
    {
271
        return $this->response->response->start;
272
    }
273
274
    public function getDebugResponse()
275
    {
276
        return $this->response->debug;
277
    }
278
279
    public function getHighlightedContent()
280
    {
281
        $highlightedContent = false;
282
283
        if ($this->response->highlighting) {
284
            $highlightedContent = $this->response->highlighting;
285
        }
286
287
        return $highlightedContent;
288
    }
289
}
290