Passed
Pull Request — master (#135)
by
unknown
07:45
created

SearchController::doubletCheckAction()   B

Complexity

Conditions 8
Paths 40

Size

Total Lines 74
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 31
nc 40
nop 1
dl 0
loc 74
rs 8.1795
c 0
b 0
f 0

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
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 EWW\Dpf\Domain\Model\Document;
18
use EWW\Dpf\Services\Transfer\DocumentTransferManager;
19
use EWW\Dpf\Services\Transfer\FedoraRepository;
20
use EWW\Dpf\Services\Transfer\ElasticsearchRepository;
21
use EWW\Dpf\Services\ElasticSearch;
22
use EWW\Dpf\Helper\ElasticsearchMapper;
23
use EWW\Dpf\Exceptions\DPFExceptionInterface;
24
25
/**
26
 * SearchController
27
 */
28
class SearchController extends \EWW\Dpf\Controller\AbstractSearchController
29
{
30
31
    /**
32
     * documentRepository
33
     *
34
     * @var \EWW\Dpf\Domain\Repository\DocumentRepository
35
     * @inject
36
     */
37
    protected $documentRepository = null;
38
39
    /**
40
     * clientRepository
41
     *
42
     * @var \EWW\Dpf\Domain\Repository\ClientRepository
43
     * @inject
44
     */
45
    protected $clientRepository = null;
46
47
    const RESULT_COUNT      = 50;
48
    const NEXT_RESULT_COUNT = 50;
49
50
    /**
51
     * action list
52
     *
53
     * @return void
54
     */
55
    public function listAction()
56
    {
57
        $objectIdentifiers = $this->documentRepository->getObjectIdentifiers();
58
59
        $args          = $this->request->getArguments();
60
61
        // assign result list from elastic search
62
        $this->view->assign('searchList', $args['results']);
63
        $this->view->assign('alreadyImported', $objectIdentifiers);
64
        $this->view->assign('resultCount', self::RESULT_COUNT);
65
        $this->view->assign('query', $args['query']);
66
    }
67
68
    /**
69
     * get next search results
70
     * @return array ElasticSearch results
71
     */
72
    public function nextResultsAction()
73
    {
74
        try {
75
            $sessionVars = $GLOBALS["BE_USER"]->getSessionData("tx_dpf");
76
            if (!$sessionVars['resultCount']) {
77
                // set number of results in session
78
                $sessionVars['resultCount'] = self::NEXT_RESULT_COUNT;
79
            } else {
80
                $resultCount                = $sessionVars['resultCount'];
81
                $sessionVars['resultCount'] = $resultCount + self::NEXT_RESULT_COUNT;
82
            }
83
            $GLOBALS['BE_USER']->setAndSaveSessionData('tx_dpf', $sessionVars);
84
85
            $query = $sessionVars['query'];
86
87
            $type = 'object';
88
89
            $query['body']['from'] = $sessionVars['resultCount'];
90
            $query['body']['size'] = self::NEXT_RESULT_COUNT;
91
92
            $results = $this->getResultList($query, $type);
93
94
            $this->view->assign('resultList', $results);
95
            $this->view->assign('alreadyImported', array());
96
        } catch (\Exception $exception) {
97
            $severity = \TYPO3\CMS\Core\Messaging\AbstractMessage::ERROR;
98
99
            if ($exception instanceof DPFExceptionInterface) {
100
                $key = $exception->messageLanguageKey();
101
            } else {
102
                $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:error.unexpected';
103
            }
104
105
            $message = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate($key, 'dpf');
106
107
            $this->addFlashMessage(
108
                $message,
109
                '',
110
                $severity,
111
                true
112
            );
113
        }
114
115
    }
116
117
    /**
118
     * extended search action
119
     */
120
    public function extendedSearchAction()
121
    {
122
        // show extended search template
123
        $objectIdentifiers = $this->documentRepository->getObjectIdentifiers();
124
125
        $args          = $this->request->getArguments();
126
127
        // assign result list from elastic search
128
        $this->view->assign('searchList', $args['results']);
129
        $this->view->assign('alreadyImported', $objectIdentifiers);
130
        $this->view->assign('resultCount', self::RESULT_COUNT);
131
132
        $this->view->assign('query', $args['query']);
133
134
    }
135
136
    /**
137
     * gets a list of latest documents
138
     */
139
    public function latestAction()
140
    {
141
        try {
142
            $query = $this->searchLatest();
143
144
            // set type local vs object
145
            $type = 'object';
146
147
            $results = $this->getResultList($query, $type);
148
        } catch (\Exception $exception) {
149
            $severity = \TYPO3\CMS\Core\Messaging\AbstractMessage::ERROR;
150
151
            if ($exception instanceof DPFExceptionInterface) {
152
                $key = $exception->messageLanguageKey();
153
            } else {
154
                $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:error.unexpected';
155
            }
156
157
            $message = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate($key, 'dpf');
158
159
            $this->addFlashMessage(
160
                $message,
161
                '',
162
                $severity,
163
                true
164
            );
165
166
        }
167
168
        $this->forward("list", null, null, array('results' => $results));
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $results does not seem to be defined for all execution paths leading up to this point.
Loading history...
169
    }
170
171
    /**
172
     * action search
173
     * @return void
174
     */
175
    public function searchAction()
176
    {
177
        try {
178
            // perform search action
179
            $args = $this->request->getArguments();
180
181
            // reset session pagination
182
            $sessionVars = $GLOBALS['BE_USER']->getSessionData('tx_dpf');
183
            $sessionVars['resultCount'] = self::RESULT_COUNT;
184
            $GLOBALS['BE_USER']->setAndSaveSessionData('tx_dpf', $sessionVars);
185
186
            $extSearch = ($args['query']['extSearch']) ? true : false;
187
188
            // set sorting
189
            if ($extSearch) {
190
                unset($args['query']['extSearch']);
191
                // extended search
192
                $query = $this->extendedSearch($args['query']);
193
194
            } else {
195
                $query = $this->searchFulltext($args['query']['fulltext']);
196
            }
197
198
            // save search query
199
            if ($query) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $query of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
200
                $query['body']['from'] = '0';
201
                $query['body']['size'] = '' . self::RESULT_COUNT . '';
202
                $sessionVars = $GLOBALS["BE_USER"]->getSessionData("tx_dpf");
203
                $sessionVars['query'] = $query;
204
                $GLOBALS['BE_USER']->setAndSaveSessionData('tx_dpf', $sessionVars);
205
            } else {
206
                $sessionVars = $GLOBALS['BE_USER']->getSessionData('tx_dpf');
207
                $query = $sessionVars['query'];
208
            }
209
210
            // set type local vs object
211
            $type = 'object';
212
213
            $results = $this->getResultList($query, $type);
214
        } catch (\Exception $exception) {
215
            $severity = \TYPO3\CMS\Core\Messaging\AbstractMessage::ERROR;
216
217
            if ($exception instanceof DPFExceptionInterface) {
218
                $key = $exception->messageLanguageKey();
219
            } else {
220
                $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:error.unexpected';
221
            }
222
223
            $message = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate($key, 'dpf');
224
225
            $this->addFlashMessage(
226
                $message,
227
                '',
228
                $severity,
229
                true
230
            );
231
        }
232
233
        if ($extSearch) {
234
            // redirect to extended search view
235
            $this->forward("extendedSearch", null, null, array('results' => $results, 'query' => $args['query']));
236
        } else {
237
            // redirect to list view
238
            $this->forward("list", null, null, array('results' => $results, 'query' => $args['query']));
239
        }
240
    }
241
242
    /**
243
     * action import
244
     *
245
     * @param  string $documentObjectIdentifier
246
     * @param  string $objectState
247
     * @return void
248
     */
249
    public function importAction($documentObjectIdentifier, $objectState)
0 ignored issues
show
Unused Code introduced by
The parameter $objectState is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

249
    public function importAction($documentObjectIdentifier, /** @scrutinizer ignore-unused */ $objectState)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
250
    {
251
        $documentTransferManager = $this->objectManager->get(DocumentTransferManager::class);
252
        $remoteRepository        = $this->objectManager->get(FedoraRepository::class);
253
        $documentTransferManager->setRemoteRepository($remoteRepository);
254
255
        $args[] = $documentObjectIdentifier;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$args was never initialized. Although not strictly required by PHP, it is generally a good practice to add $args = array(); before regardless.
Loading history...
256
257
        try {
258
            if ($documentTransferManager->retrieve($documentObjectIdentifier)) {
259
                $key      = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:document_retrieve.success';
260
                $severity = \TYPO3\CMS\Core\Messaging\AbstractMessage::OK;
261
            }
262
        } catch (\Exception $exception) {
263
            $severity = \TYPO3\CMS\Core\Messaging\AbstractMessage::ERROR;
264
265
            if ($exception instanceof DPFExceptionInterface) {
266
                $key = $exception->messageLanguageKey();
267
            } else {
268
                $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:error.unexpected';
269
            }
270
        }
271
272
        // Show success or failure of the action in a flash message
273
274
        $message = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate($key, 'dpf');
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $key does not seem to be defined for all execution paths leading up to this point.
Loading history...
275
276
        $this->addFlashMessage(
277
            $message,
278
            '',
279
            $severity,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $severity does not seem to be defined for all execution paths leading up to this point.
Loading history...
280
            true
281
        );
282
283
        $this->forward('updateIndex', null, null, array('documentObjectIdentifier' => $documentObjectIdentifier));
284
    }
285
286
    /**
287
     *
288
     * @param  string $documentObjectIdentifier
289
     * @return void
290
     */
291
    public function updateIndexAction($documentObjectIdentifier)
292
    {
293
        $document = $this->documentRepository->findByObjectIdentifier($documentObjectIdentifier);
0 ignored issues
show
Bug introduced by
The method findByObjectIdentifier() does not exist on EWW\Dpf\Domain\Repository\DocumentRepository. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

293
        /** @scrutinizer ignore-call */ 
294
        $document = $this->documentRepository->findByObjectIdentifier($documentObjectIdentifier);
Loading history...
294
295
        if (is_a($document, Document::class)) {
0 ignored issues
show
Bug introduced by
It seems like $document can also be of type array; however, parameter $object of is_a() does only seem to accept object|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

295
        if (is_a(/** @scrutinizer ignore-type */ $document, Document::class)) {
Loading history...
296
            $elasticsearchRepository = $this->objectManager->get(ElasticsearchRepository::class);
297
            $elasticsearchMapper     = $this->objectManager->get(ElasticsearchMapper::class);
298
            $json                    = $elasticsearchMapper->getElasticsearchJson($document);
299
            // send document to index
300
            $elasticsearchRepository->add($document, $json);
301
        }
302
303
        $this->redirect('search');
304
    }
305
306
    /**
307
     * action doubletCheck
308
     *
309
     * @param  \EWW\Dpf\Domain\Model\Document $document
310
     * @return void
311
     */
312
    public function doubletCheckAction(\EWW\Dpf\Domain\Model\Document $document)
313
    {
314
        try {
315
            $elasticSearch = $this->objectManager->get(ElasticSearch::class);
316
317
            $client = $this->clientRepository->findAll()->current();
318
319
            // es source fields
320
            // title
321
            // abstract
322
            // author
323
            // language
324
            // publisher
325
            // publisher_place
326
            // distributor
327
            // distributor_place
328
            // distributor_date
329
            // classification
330
            // tag
331
            // identifier
332
            // submitter
333
            // project
334
335
            // is doublet existing?
336
            $query['body']['query']['bool']['must'][]['match']['title'] = $document->getTitle();
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...
337
338
            // set owner id
339
            $query['body']['query']['bool']['must'][]['term']['OWNER_ID'] = $client->getOwnerId();
340
341
            $results = $elasticSearch->search($query, '');
342
343
            $searchList = array();
344
345
            // filter out identical document from the search result list
346
            foreach ($results['hits'] as $entry) {
347
348
                if ($document->getObjectIdentifier() && ($document->getObjectIdentifier() === $entry['_source']['PID'])) {
349
                    continue;
350
                }
351
352
                $entryIdentifier = $entry['_source']['_dissemination']['_content']['identifier'][0];
353
                if (is_numeric($entryIdentifier) && $document->getUid() == $entryIdentifier) {
354
                    continue;
355
                }
356
357
                $searchList[] = $entry;
358
            }
359
360
361
            $objectIdentifiers = $this->documentRepository->getObjectIdentifiers();
362
363
            $this->view->assign('document', $document);
364
            $this->view->assign('searchList', $searchList);
365
            $this->view->assign('alreadyImported', $objectIdentifiers);
366
367
        } catch (\Exception $exception) {
368
            $severity = \TYPO3\CMS\Core\Messaging\AbstractMessage::ERROR;
369
370
            if ($exception instanceof DPFExceptionInterface) {
371
                $key = $exception->messageLanguageKey();
372
            } else {
373
                $key = 'LLL:EXT:dpf/Resources/Private/Language/locallang.xlf:error.unexpected';
374
            }
375
376
            $message = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate($key, 'dpf');
377
378
            $this->addFlashMessage(
379
                $message,
380
                '',
381
                $severity,
382
                true
383
            );
384
385
            $this->redirect('list', 'Document', null);
386
        }
387
388
    }
389
390
    /**
391
     * returns the query to get latest documents
392
     * @return mixed
393
     */
394
    public function searchLatest()
395
    {
396
        $client = $this->clientRepository->findAll()->current();
397
398
        // get the latest documents /CREATED_DATE
399
        $query['body']['sort'] = array('CREATED_DATE' => array('order' => 'desc'));
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...
400
401
        // add owner id
402
        $query['body']['query']['bool']['must']['term']['OWNER_ID'] = $client->getOwnerId(); // qucosa
403
404
        $query['body']['query']['bool']['should'][0]['query_string']['query']                       = '*';
405
        $query['body']['query']['bool']['should'][1]['has_child']['query']['query_string']['query'] = '*';
406
407
        $query['body']['query']['bool']['minimum_should_match'] = "1"; // 1
408
409
        $query['body']['query']['bool']['should'][1]['has_child']['child_type'] = "datastream"; // 1
410
411
        return $query;
412
    }
413
414
}
415