Passed
Pull Request — master (#105)
by Alexander
05:13
created

SearchInDocument::main()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 70
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 42
c 0
b 0
f 0
nc 4
nop 1
dl 0
loc 70
rs 8.6257

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Eid;
14
15
use Kitodo\Dlf\Common\Helper;
16
use Kitodo\Dlf\Common\Solr;
17
use Kitodo\Dlf\Common\SolrSearchResult\ResultDocument;
18
use Psr\Http\Message\ResponseInterface;
19
use Psr\Http\Message\ServerRequestInterface;
20
use TYPO3\CMS\Core\Http\Response;
21
use TYPO3\CMS\Core\Utility\GeneralUtility;
22
23
/**
24
 * eID search in document for plugin 'Search' of the 'dlf' extension
25
 *
26
 * @author Alexander Bigga <[email protected]>
27
 * @package TYPO3
28
 * @subpackage dlf
29
 * @access public
30
 */
31
class SearchInDocument
32
{
33
    /**
34
     * The main method of the eID script
35
     *
36
     * @param ServerRequestInterface $request
37
     * @return ResponseInterface JSON response of search suggestions
38
     */
39
    public function main(ServerRequestInterface $request)
40
    {
41
        $output = [
42
            'documents' => [],
43
            'numFound' => 0
44
        ];
45
        // Get input parameters and decrypt core name.
46
        $parameters = $request->getParsedBody();
47
        if ($parameters === null) {
48
            throw new \InvalidArgumentException('No parameters passed!', 1632322297);
49
        }
50
        $encrypted = (string) $parameters['encrypted'];
51
        $start = intval($parameters['start']);
52
        if (empty($encrypted)) {
53
            throw new \InvalidArgumentException('No valid parameter passed!', 1580585079);
54
        }
55
56
        $core = Helper::decrypt($encrypted);
57
58
        // Perform Solr query.
59
        $solr = Solr::getInstance($core);
60
        $fields = Solr::getFields();
61
62
        if ($solr->ready) {
63
            $query = $solr->service->createSelect();
64
            $query->setFields([$fields['id'], $fields['uid'], $fields['page']]);
65
            $query->setQuery($this->getQuery($fields, $parameters));
66
            $query->setStart($start)->setRows(20);
67
            $query->addSort($fields['page'], $query::SORT_ASC);
68
            $query->getHighlighting();
69
            $solrRequest = $solr->service->createRequest($query);
70
71
            // it is necessary to add the custom parameters to the request
72
            // because query object doesn't allow custom parameters
73
74
            // field for which highlighting is going to be performed,
75
            // is required if you want to have OCR highlighting
76
            $solrRequest->addParam('hl.ocr.fl', $fields['fulltext']);
77
            // return the coordinates of highlighted search as absolute coordinates
78
            $solrRequest->addParam('hl.ocr.absoluteHighlights', 'on');
79
            // max amount of snippets for a single page
80
            $solrRequest->addParam('hl.snippets', 40);
81
            // we store the fulltext on page level and can disable this option
82
            $solrRequest->addParam('hl.ocr.trackPages', 'off');
83
84
            $response = $solr->service->executeRequest($solrRequest);
85
            $result = $solr->service->createResult($query, $response);
86
            /** @scrutinizer ignore-call */
87
            $output['numFound'] = $result->getNumFound();
88
            $data = $result->getData();
89
            $highlighting = $data['ocrHighlighting'];
90
91
            foreach ($result as $record) {
92
                $resultDocument = new ResultDocument($record, $highlighting, $fields);
93
94
                $document = [
95
                    'id' => $resultDocument->getId(),
96
                    'uid' => !empty($resultDocument->getUid()) ? $resultDocument->getUid() : $parameters['uid'],
97
                    'page' => $resultDocument->getPage(),
98
                    'snippet' => $resultDocument->getSnippets(),
99
                    'highlight' => $resultDocument->getHighlightsIds()
100
                ];
101
                $output['documents'][] = $document;
102
            }
103
        }
104
        // Create response object.
105
        /** @var Response $response */
106
        $response = GeneralUtility::makeInstance(Response::class);
107
        $response->getBody()->write(json_encode($output));
108
        return $response;
109
    }
110
111
    /**
112
     * Build SOLR query for given fields and parameters.
113
     *
114
     * @access private
115
     *
116
     * @param array $fields array of SOLR index fields
117
     * @param array|object $parameters parsed from request body
118
     *
119
     * @return string SOLR query
120
     */
121
    private function getQuery($fields, $parameters)
122
    {
123
        return $fields['fulltext'] . ':(' . Solr::escapeQuery((string) $parameters['q']) . ') AND ' . $fields['uid'] . ':' . $this->getUid($parameters['uid']);
124
    }
125
126
    /**
127
     * Check if uid is number, if yes convert it to int,
128
     * otherwise leave uid not changed.
129
     *
130
     * @access private
131
     *
132
     * @param string $uid of the document
133
     *
134
     * @return int|string uid of the document
135
     */
136
    private function getUid($uid)
137
    {
138
        return is_numeric($uid) ? intval($uid) : $uid;
139
    }
140
}
141