Completed
Pull Request — 2.1 (#1163)
by Greg
09:54
created

ArticleRepository::findByCriteria()   F

Complexity

Conditions 27
Paths 1536

Size

Total Lines 108

Duplication

Lines 33
Ratio 30.56 %

Importance

Changes 0
Metric Value
dl 33
loc 108
rs 0
c 0
b 0
f 0
cc 27
nc 1536
nop 3

How to fix   Long Method    Complexity   

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
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Superdesk Web Publisher ElasticSearch Bundle.
7
 *
8
 * Copyright 2017 Sourcefabric z.ú. and contributors.
9
 *
10
 * For the full copyright and license information, please see the
11
 * AUTHORS and LICENSE files distributed with this source code.
12
 *
13
 * @copyright 2017 Sourcefabric z.ú
14
 * @license http://www.superdesk.org/license
15
 */
16
17
namespace SWP\Bundle\ElasticSearchBundle\Repository;
18
19
use Elastica\Query;
20
use Elastica\Query\BoolQuery;
21
use Elastica\Query\MatchAll;
22
use Elastica\Query\MultiMatch;
23
use Elastica\Query\Nested;
24
use Elastica\Query\Range;
25
use Elastica\Query\Term;
26
use Elastica\QueryBuilder\DSL\Suggest;
27
use FOS\ElasticaBundle\Paginator\PaginatorAdapterInterface;
28
use FOS\ElasticaBundle\Repository;
29
use SWP\Bundle\ElasticSearchBundle\Criteria\Criteria;
30
use SWP\Bundle\ElasticSearchBundle\Loader\SearchResultLoader;
31
32
class ArticleRepository extends Repository
33
{
34
    public function findByCriteria(Criteria $criteria, array $extraFields = [], bool $searchByBody = false): PaginatorAdapterInterface
35
    {
36
        $fields = $criteria->getFilters()->getFields();
37
        $boolFilter = new BoolQuery();
38
39
        if (null !== $criteria->getTerm() && '' !== $criteria->getTerm()) {
40
            $searchBy = ['title', 'lead', 'keywords.name'];
41
42
            foreach ($extraFields as $extraField) {
43
                $searchBy[] = 'extra.'.$extraField;
44
            }
45
46
            if ($searchByBody) {
47
                $searchBy[] = 'body';
48
            }
49
50
            $priority = 1;
51
            foreach (array_reverse($searchBy) as $key => $field) {
52
                $searchBy[$key] = $field.'^'.$priority;
53
54
                ++$priority;
55
            }
56
57
            $query = new MultiMatch();
58
            $query->setQuery($criteria->getTerm());
59
            $query->setFields($searchBy);
60
            $query->setType(MultiMatch::TYPE_PHRASE);
61
            $boolFilter->addMust($query);
62
        } else {
63
            $boolFilter->addMust(new MatchAll());
64
        }
65
66 View Code Duplication
        if (null !== $fields->get('keywords') && !empty($fields->get('keywords'))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
67
            $bool = new BoolQuery();
68
            $bool->addFilter(new Query\Terms('keywords.name', $fields->get('keywords')));
69
            $nested = new Nested();
70
            $nested->setPath('keywords');
71
            $nested->setQuery($bool);
72
            $boolFilter->addMust($nested);
73
        }
74
75 View Code Duplication
        if (null !== $fields->get('authors') && !empty($fields->get('authors'))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
76
            $bool = new BoolQuery();
77
            foreach ($fields->get('authors') as $author) {
78
                $bool->addFilter(new Query\Match('authors.name', $author));
79
            }
80
81
            $nested = new Nested();
82
            $nested->setPath('authors');
83
            $nested->setQuery($bool);
84
            $boolFilter->addMust($nested);
85
        }
86
87 View Code Duplication
        if (null !== $fields->get('sources') && !empty($fields->get('sources'))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
88
            $nested = new Nested();
89
            $nested->setPath('sources');
90
            $boolQuery = new BoolQuery();
91
            $boolQuery->addMust(new Query\Terms('sources.name', $fields->get('sources')));
92
            $nested->setQuery($boolQuery);
93
            $boolFilter->addMust($nested);
94
        }
95
96 View Code Duplication
        if (null !== $fields->get('statuses') && !empty($fields->get('statuses'))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
97
            $boolFilter->addFilter(new Query\Terms('status', $fields->get('statuses')));
98
        }
99
100
        if (null !== $fields->get('metadata') && !empty($fields->get('metadata'))) {
101
            foreach ($fields->get('metadata') as $key => $values) {
102
                foreach ((array) $values as $value) {
103
                    $boolFilter->addFilter(new Query\Match($key, $value));
104
                }
105
            }
106
        }
107
108
        if (null !== $fields->get('tenantCode')) {
109
            $boolFilter->addFilter(new Term(['tenantCode' => $fields->get('tenantCode')]));
110
        }
111
112
        $bool = new BoolQuery();
113 View Code Duplication
        if (null !== $fields->get('routes') && !empty($fields->get('routes'))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
114
            $bool->addFilter(new Query\Terms('route.id', $fields->get('routes')));
115
        }
116
117
        if (null !== $fields->get('publishedAfter') || null !== $fields->get('publishedBefore')) {
118
            $boolFilter->addFilter(new Range(
119
                'publishedAt',
120
                [
121
                    'gte' => null !== $fields->get('publishedAfter') ? $fields->get('publishedAfter')->format('Y-m-d') : null,
122
                    'lte' => null !== $fields->get('publishedBefore') ? $fields->get('publishedBefore')->format('Y-m-d') : null,
123
                ]
124
            ));
125
126
            $boolFilter->addFilter(new \Elastica\Query\Term(['isPublishable' => true]));
127
        }
128
129
        if (!empty($bool->getParams())) {
130
            $boolFilter->addMust($bool);
131
        }
132
133
        $query = Query::create($boolFilter)
134
            ->addSort([
135
                $criteria->getOrder()->getField() => $criteria->getOrder()->getDirection(),
136
            ]);
137
138
        $query->setSize(SearchResultLoader::MAX_RESULTS);
139
140
        return $this->createPaginatorAdapter($query);
0 ignored issues
show
Documentation introduced by
$query is of type object<Elastica\Query>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
141
    }
142
143
144
    public function getSuggestedTerm(string $term): string
145
    {
146
        $suggestQuery = new Suggest();
147
        $suggestQuery->phrase('our_suggestion', '_all');
148
149
        $phraseMultiMatchQuery = new MultiMatch();
150
        $phraseMultiMatchQuery->setQuery($term);
151
        $phraseMultiMatchQuery->setFields('_all');
0 ignored issues
show
Documentation introduced by
'_all' is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
152
        $phraseMultiMatchQuery->setType(MultiMatch::TYPE_PHRASE);
153
        $phraseMultiMatchQuery->setParam('boost', 50);
154
155
        $query = new \Elastica\Query($phraseMultiMatchQuery);
156
        $suggest = new \Elastica\Suggest();
157
        $suggest->setParam(
158
            'phrase',
159
            [
160
                'text' => $term,
161
                'phrase' => ['field' => '_all']
162
            ]
163
        );
164
165
        $query->setSuggest($suggest);
166
167
        $adapter = $this->createPaginatorAdapter($query);
0 ignored issues
show
Documentation introduced by
$query is of type object<Elastica\Query>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
168
        $suggest = $adapter->getSuggests();
169
170
        return $suggest['phrase'][0]['options'][0]['text'] ?? '';
171
172
    }
173
}
174