Passed
Pull Request — master (#64)
by
unknown
03:05
created

AbstractSearchController   A

Complexity

Total Complexity 33

Size/Duplication

Total Lines 215
Duplicated Lines 0 %

Importance

Changes 8
Bugs 2 Features 2
Metric Value
c 8
b 2
f 2
dl 0
loc 215
rs 9.3999
wmc 33

7 Methods

Rating   Name   Duplication   Size   Complexity  
A searchFulltext() 0 17 2
C resultsFilter() 0 71 11
A escapeQuery() 0 12 1
C extendedSearch() 0 38 13
A formatDate() 0 5 1
A convertFormDate() 0 9 4
A getResultList() 0 7 1
1
<?php
2
namespace EWW\Dpf\Controller;
3
4
/*
5
 * This file is part of the TYPO3 CMS project.
6
 *
7
 * It is free software; you can redistribute it and/or modify it under
8
 * the terms of the GNU General Public License, either version 2
9
 * of the License, or any later version.
10
 *
11
 * For the full copyright and license information, please read the
12
 * LICENSE.txt file that was distributed with this source code.
13
 *
14
 * The TYPO3 project - inspiring people to share!
15
 */
16
17
use TYPO3\CMS\Core\Utility\GeneralUtility;
0 ignored issues
show
Bug introduced by
The type TYPO3\CMS\Core\Utility\GeneralUtility was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
18
19
abstract class AbstractSearchController extends \EWW\Dpf\Controller\AbstractController
20
{
21
    // search terms
22
    private static $terms   = ['_id', 'OWNER_ID', 'submitter', 'project'];
23
24
    // search matches
25
    private static $matches = ['title', 'abstract', 'author', 'language', 'tag', 'corporation', 'doctype', 'collections'];
26
27
    /**
28
     * get results from elastic search
29
     * @param  array $query elasticsearch search query
30
     * @return array        results
31
     */
32
    public function getResultList($query, $type)
33
    {
34
35
        $elasticSearch = new \EWW\Dpf\Services\ElasticSearch();
36
        $results = $elasticSearch->search($query, $type);
37
38
        return $results;
39
    }
40
41
    /**
42
     * prepare fulltext query
43
     * @param  string $searchString
44
     * @return array query
45
     */
46
    public function searchFulltext($searchString)
47
    {
48
        // don't return query if searchString is empty
49
        if (empty($searchString)) {
50
            return null;
51
        }
52
53
        $searchString = $this->escapeQuery(trim($searchString));
54
55
        $query['body']['query']['bool']['should'][0]['query_string']['query']                       = $searchString;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$query was never initialized. Although not strictly required by PHP, it is generally a good practice to add $query = array(); before regardless.
Loading history...
56
        $query['body']['query']['bool']['should'][1]['has_child']['query']['query_string']['query'] = $searchString;
57
        $query['body']['query']['bool']['minimum_should_match'] = "1"; // 1
58
        $query['body']['query']['bool']['should'][1]['has_child']['child_type'] = "datastream"; // 1
59
60
        $query = $this->resultsFilter($query, false);
61
62
        return $query;
63
64
    }
65
66
    /**
67
     * build array for elasticsearch
68
     * @return array Elasticsearch query array
69
     */
70
    public function extendedSearch($searchArray = array())
71
    {
72
73
        $query  = array();
74
        $filter = array();
75
        foreach ($searchArray as $key => $qry) {
76
            $qry = trim($qry);
77
78
            if (!empty($qry) && in_array($key, self::$matches)) {
79
80
                $query['body']['query']['bool']['must'][] = array('match' => array($key => $qry));
81
82
            } elseif (!empty($qry) && in_array($key, self::$terms)) {
83
84
                $query['body']['query']['bool']['must'][] = array('term' => array($key => $qry));
85
86
            } elseif (!empty($qry) && $key == 'from') {
87
88
                $dateTime = $this->convertFormDate($qry, false);
89
                $filter['gte'] = $dateTime->format('Y-m-d');
90
91
            } elseif (!empty($qry) && $key == 'till') {
92
93
                $dateTime = $this->convertFormDate($qry, true);
94
                $filter['lte'] = $dateTime->format('Y-m-d');
95
96
            }
97
        }
98
99
        if (isset($filter['gte']) || isset($filter['lte'])) {
100
101
            $query['body']['query']['bool']['must'][] = array('range' => array('distribution_date' => $filter));
102
103
        }
104
105
        $showDeleted = ($searchArray['showDeleted'] == 'true') ? true : false;
106
        $query = $this->resultsFilter($query, $showDeleted);
107
        return $query;
108
109
    }
110
111
    /**
112
     * build array for elasticsearch resultfilter
113
     * @param array Elasticsearch query array
0 ignored issues
show
Bug introduced by
The type EWW\Dpf\Controller\Elasticsearch was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
114
     * @return array Elasticsearch queryFilter array
115
     */
116
    public function resultsFilter($query, $showDeleted = false)
117
    {
118
119
        $queryFilter = array();
120
121
        // Frontend only
122
        $searchResultsFilter = $this->settings['searchResultsFilter'];
123
        if(!empty($searchResultsFilter)) {
124
125
            // add doctypes
126
            if($searchResultsFilter['doctype']) {
127
128
                $uids = \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $searchResultsFilter['doctype']);
129
                $documentTypeRepository = $this->documentTypeRepository;
130
                $documentTypes = array();
131
                foreach($uids as $uid) {
132
                    $documentType = $documentTypeRepository->findByUid($uid);
133
                    $documentTypes[] = $documentType->getName();
134
                };
135
                $searchResultsFilter['doctype'] = implode(',', $documentTypes);
136
            }
137
138
            // add date filter
139
            $dateFilter = array();
140
            if ($searchResultsFilter['from']) {
141
142
                $from     = date('d.m.Y', $searchResultsFilter['from']);
143
                $dateTime = $this->convertFormDate($from, false);
144
                $dateFilter['gte'] = $dateTime->format('Y-m-d');
145
                unset($searchResultsFilter['from']);
146
147
            }
148
149
            if ($searchResultsFilter['till']) {
150
151
                $till          = date('d.m.Y', $searchResultsFilter['till']);
152
                $dateTime = $this->convertFormDate($till, true);
153
                $dateFilter['lte'] = $dateTime->format('Y-m-d');
154
                unset($searchResultsFilter['till']);
155
156
            }
157
158
            if (isset($dateFilter['gte']) || isset($dateFilter['lte'])) {
159
160
                $queryFilter['body']['query']['bool']['must'][] = array('range' => array('distribution_date' => $dateFilter));
161
162
            }
163
164
            foreach ($searchResultsFilter as $key => $qry) {
165
166
                if(!empty($qry)) {
167
                    $queryFilter['body']['query']['bool']['must'][] = array('match' => array($key => $qry));
168
                }
169
170
            }
171
172
        }
173
174
        // document must be active
175
        if($showDeleted == false) {
176
177
            $queryFilter['body']['query']['bool']['must'][]['term']['STATE'] = 'A';
178
179
        };
180
181
        // add owner id
182
        $client = $this->clientRepository->findAll()->current();
183
        $queryFilter['body']['query']['bool']['must'][]['term']['OWNER_ID'] = $client->getOwnerId();
184
185
        $queryFilter = array_merge_recursive($queryFilter, $query);
186
        return $queryFilter;
187
    }
188
189
    /**
190
     * @param $date
191
     * @param bool $fillMax: fills missing values with the maximum possible date if true
192
     */
193
    public function convertFormDate($date, $fillMax = false)
194
    {
195
        if (strlen($dateString) == 4) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $dateString seems to be never defined.
Loading history...
196
            $year = $dateString;
197
            $month = $fillMax ? "12" : "01";
198
            $day = $fillMax ? "31" : "01";
199
            return new \DateTime("$year-$month-$day");
200
        } else {
201
            return $date = new \DateTime($dateString);
0 ignored issues
show
Unused Code introduced by
The assignment to $date is dead and can be removed.
Loading history...
202
        }
203
    }
204
205
    /**
206
     * escapes lucene reserved characters from string
207
     * @param $string
208
     * @return mixed
209
     */
210
    private function escapeQuery($string)
211
    {
212
        $luceneReservedCharacters = preg_quote('+-&|!(){}[]^"~?:\\');
213
        $string                   = preg_replace_callback(
214
            '/([' . $luceneReservedCharacters . '])/',
215
            function ($matches) {
216
                return '\\' . $matches[0];
217
            },
218
            $string
219
        );
220
221
        return $string;
222
    }
223
224
    /**
225
     * converts a date from dd.mm.yy to yyyy-dd-mm
226
     * @param $date
227
     * @return string
228
     */
229
    public function formatDate($date)
230
    {
231
        // convert date from dd.mm.yyy to yyyy-dd-mm
232
        $date = explode(".", $date);
233
        return $date[2] . '-' . $date[1] . '-' . $date[0];
234
    }
235
}
236