Completed
Push — legacy ( c3f933 )
by Simonas
95:41
created

QueryEndpoint::convertToBool()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 10
rs 9.4285
cc 2
eloc 5
nc 2
nop 0
1
<?php
2
3
/*
4
 * This file is part of the ONGR package.
5
 *
6
 * (c) NFQ Technologies UAB <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace ONGR\ElasticsearchBundle\DSL\SearchEndpoint;
13
14
use ONGR\ElasticsearchBundle\DSL\BuilderInterface;
15
use ONGR\ElasticsearchBundle\DSL\ParametersTrait;
16
use ONGR\ElasticsearchBundle\DSL\Query\BoolQuery;
17
use ONGR\ElasticsearchBundle\DSL\Query\FilteredQuery;
18
use ONGR\ElasticsearchBundle\Serializer\Normalizer\OrderedNormalizerInterface;
19
use Symfony\Component\OptionsResolver\OptionsResolver;
20
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
21
22
/**
23
 * Search query dsl endpoint.
24
 */
25
class QueryEndpoint extends AbstractSearchEndpoint implements OrderedNormalizerInterface
26
{
27
    use ParametersTrait;
28
29
    /**
30
     * @var BuilderInterface|BoolQuery
31
     */
32
    private $query;
33
34
    /**
35
     * @var OptionsResolver
36
     */
37
    private $resolver;
38
39
    /**
40
     * Instantiates resolver.
41
     */
42
    public function __construct()
43
    {
44
        $this->resolver = new OptionsResolver();
45
        $this->configureResolver($this->resolver);
46
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51
    public function addBuilder(BuilderInterface $builder, $parameters = [])
52
    {
53
        if (!$this->query && !(array_key_exists('bool_type', $parameters) && !empty($parameters['bool_type']))) {
54
            $this->setBuilder($builder);
55
        } else {
56
            $parameters = $this->resolver->resolve(array_filter($parameters));
57
            $this->isBool() ? : $this->convertToBool();
58
            $this->query->add($builder, $parameters['bool_type']);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface ONGR\ElasticsearchBundle\DSL\BuilderInterface as the method add() does only exist in the following implementations of said interface: ONGR\ElasticsearchBundle\DSL\Bool\Bool, ONGR\ElasticsearchBundle\DSL\Filter\AndFilter, ONGR\ElasticsearchBundle\DSL\Filter\BoolFilter, ONGR\ElasticsearchBundle\DSL\Filter\OrFilter, ONGR\ElasticsearchBundle\DSL\Highlight\Highlight, ONGR\ElasticsearchBundle\DSL\Query\BoolQuery.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
59
        }
60
61
        return $this;
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67
    public function normalize(NormalizerInterface $normalizer, $format = null, array $context = [])
68
    {
69
        $isRelevant = false;
70
71
        if ($this->hasReference('filtered_query')) {
72
            /** @var FilteredQuery $query */
73
            $query = $this->getReference('filtered_query');
74
            if ($this->getBuilder()) {
75
                $query->setQuery($this->getBuilder());
76
            }
77
            $this->setBuilder($query);
78
            $isRelevant = true;
79
        }
80
81
        if ($this->getBuilder()) {
82
            if (method_exists($this->getBuilder(), 'setParameters') && count($this->getParameters()) > 0) {
83
                $this
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface ONGR\ElasticsearchBundle\DSL\BuilderInterface as the method setParameters() does only exist in the following implementations of said interface: ONGR\ElasticsearchBundle...ion\AbstractAggregation, ONGR\ElasticsearchBundle...regation\AvgAggregation, ONGR\ElasticsearchBundle...\CardinalityAggregation, ONGR\ElasticsearchBundle...ion\ChildrenAggregation, ONGR\ElasticsearchBundle...on\DateRangeAggregation, ONGR\ElasticsearchBundle...xtendedStatsAggregation, ONGR\ElasticsearchBundle...ation\FilterAggregation, ONGR\ElasticsearchBundle...tion\FiltersAggregation, ONGR\ElasticsearchBundle...on\GeoBoundsAggregation, ONGR\ElasticsearchBundle...\GeoDistanceAggregation, ONGR\ElasticsearchBundle...\GeoHashGridAggregation, ONGR\ElasticsearchBundle...ation\GlobalAggregation, ONGR\ElasticsearchBundle...on\HistogramAggregation, ONGR\ElasticsearchBundle...on\Ipv4RangeAggregation, ONGR\ElasticsearchBundle...regation\MaxAggregation, ONGR\ElasticsearchBundle...regation\MinAggregation, ONGR\ElasticsearchBundle...tion\MissingAggregation, ONGR\ElasticsearchBundle...ation\NestedAggregation, ONGR\ElasticsearchBundle...centileRanksAggregation, ONGR\ElasticsearchBundle...\PercentilesAggregation, ONGR\ElasticsearchBundle...gation\RangeAggregation, ONGR\ElasticsearchBundle...everseNestedAggregation, ONGR\ElasticsearchBundle...gation\StatsAggregation, ONGR\ElasticsearchBundle...regation\SumAggregation, ONGR\ElasticsearchBundle...gation\TermsAggregation, ONGR\ElasticsearchBundle...tion\TopHitsAggregation, ONGR\ElasticsearchBundle...n\ValueCountAggregation, ONGR\ElasticsearchBundle\DSL\Bool\Bool, ONGR\ElasticsearchBundle\DSL\Filter\AndFilter, ONGR\ElasticsearchBundle\DSL\Filter\BoolFilter, ONGR\ElasticsearchBundle...er\GeoBoundingBoxFilter, ONGR\ElasticsearchBundle...ilter\GeoDistanceFilter, ONGR\ElasticsearchBundle...\GeoDistanceRangeFilter, ONGR\ElasticsearchBundle...Filter\GeoPolygonFilter, ONGR\ElasticsearchBundle\DSL\Filter\GeoShapeFilter, ONGR\ElasticsearchBundle...ilter\GeohashCellFilter, ONGR\ElasticsearchBundle\DSL\Filter\HasChildFilter, ONGR\ElasticsearchBundle...\Filter\HasParentFilter, ONGR\ElasticsearchBundle\DSL\Filter\IdsFilter, ONGR\ElasticsearchBundle\DSL\Filter\MissingFilter, ONGR\ElasticsearchBundle\DSL\Filter\NestedFilter, ONGR\ElasticsearchBundle\DSL\Filter\NotFilter, ONGR\ElasticsearchBundle\DSL\Filter\OrFilter, ONGR\ElasticsearchBundle\DSL\Filter\PrefixFilter, ONGR\ElasticsearchBundle\DSL\Filter\QueryFilter, ONGR\ElasticsearchBundle\DSL\Filter\RangeFilter, ONGR\ElasticsearchBundle\DSL\Filter\RegexpFilter, ONGR\ElasticsearchBundle\DSL\Filter\ScriptFilter, ONGR\ElasticsearchBundle\DSL\Filter\TermFilter, ONGR\ElasticsearchBundle\DSL\Filter\TermsFilter, ONGR\ElasticsearchBundle\DSL\Query\BoolQuery, ONGR\ElasticsearchBundle...\Query\CommonTermsQuery, ONGR\ElasticsearchBundle...uery\ConstantScoreQuery, ONGR\ElasticsearchBundle\DSL\Query\DisMaxQuery, ONGR\ElasticsearchBundle\DSL\Query\FilteredQuery, ONGR\ElasticsearchBundle...uery\FunctionScoreQuery, ONGR\ElasticsearchBundle...FuzzyLikeThisFieldQuery, ONGR\ElasticsearchBundle...uery\FuzzyLikeThisQuery, ONGR\ElasticsearchBundle\DSL\Query\FuzzyQuery, ONGR\ElasticsearchBundle\DSL\Query\HasChildQuery, ONGR\ElasticsearchBundle\DSL\Query\HasParentQuery, ONGR\ElasticsearchBundle\DSL\Query\IdsQuery, ONGR\ElasticsearchBundle\DSL\Query\MatchAllQuery, ONGR\ElasticsearchBundle\DSL\Query\MatchQuery, ONGR\ElasticsearchBundle...Query\MoreLikeThisQuery, ONGR\ElasticsearchBundle\DSL\Query\MultiMatchQuery, ONGR\ElasticsearchBundle\DSL\Query\PrefixQuery, ONGR\ElasticsearchBundle...\Query\QueryStringQuery, ONGR\ElasticsearchBundle\DSL\Query\RangeQuery, ONGR\ElasticsearchBundle\DSL\Query\RegexpQuery, ONGR\ElasticsearchBundle...\SimpleQueryStringQuery, ONGR\ElasticsearchBundle...ery\Span\SpanFirstQuery, ONGR\ElasticsearchBundle...Span\SpanMultiTermQuery, ONGR\ElasticsearchBundle...uery\Span\SpanNearQuery, ONGR\ElasticsearchBundle...Query\Span\SpanNotQuery, ONGR\ElasticsearchBundle...\Query\Span\SpanOrQuery, ONGR\ElasticsearchBundle...uery\Span\SpanTermQuery, ONGR\ElasticsearchBundle\DSL\Query\TermQuery, ONGR\ElasticsearchBundle\DSL\Query\TermsQuery, ONGR\ElasticsearchBundle\DSL\Query\WildcardQuery.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
84
                    ->getBuilder()
85
                    ->setParameters($this->processArray($this->getBuilder()->getParameters()));
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface ONGR\ElasticsearchBundle\DSL\BuilderInterface as the method getParameters() does only exist in the following implementations of said interface: ONGR\ElasticsearchBundle...ion\AbstractAggregation, ONGR\ElasticsearchBundle...regation\AvgAggregation, ONGR\ElasticsearchBundle...\CardinalityAggregation, ONGR\ElasticsearchBundle...ion\ChildrenAggregation, ONGR\ElasticsearchBundle...on\DateRangeAggregation, ONGR\ElasticsearchBundle...xtendedStatsAggregation, ONGR\ElasticsearchBundle...ation\FilterAggregation, ONGR\ElasticsearchBundle...tion\FiltersAggregation, ONGR\ElasticsearchBundle...on\GeoBoundsAggregation, ONGR\ElasticsearchBundle...\GeoDistanceAggregation, ONGR\ElasticsearchBundle...\GeoHashGridAggregation, ONGR\ElasticsearchBundle...ation\GlobalAggregation, ONGR\ElasticsearchBundle...on\HistogramAggregation, ONGR\ElasticsearchBundle...on\Ipv4RangeAggregation, ONGR\ElasticsearchBundle...regation\MaxAggregation, ONGR\ElasticsearchBundle...regation\MinAggregation, ONGR\ElasticsearchBundle...tion\MissingAggregation, ONGR\ElasticsearchBundle...ation\NestedAggregation, ONGR\ElasticsearchBundle...centileRanksAggregation, ONGR\ElasticsearchBundle...\PercentilesAggregation, ONGR\ElasticsearchBundle...gation\RangeAggregation, ONGR\ElasticsearchBundle...everseNestedAggregation, ONGR\ElasticsearchBundle...gation\StatsAggregation, ONGR\ElasticsearchBundle...regation\SumAggregation, ONGR\ElasticsearchBundle...gation\TermsAggregation, ONGR\ElasticsearchBundle...tion\TopHitsAggregation, ONGR\ElasticsearchBundle...n\ValueCountAggregation, ONGR\ElasticsearchBundle\DSL\Bool\Bool, ONGR\ElasticsearchBundle\DSL\Filter\AndFilter, ONGR\ElasticsearchBundle\DSL\Filter\BoolFilter, ONGR\ElasticsearchBundle...er\GeoBoundingBoxFilter, ONGR\ElasticsearchBundle...ilter\GeoDistanceFilter, ONGR\ElasticsearchBundle...\GeoDistanceRangeFilter, ONGR\ElasticsearchBundle...Filter\GeoPolygonFilter, ONGR\ElasticsearchBundle\DSL\Filter\GeoShapeFilter, ONGR\ElasticsearchBundle...ilter\GeohashCellFilter, ONGR\ElasticsearchBundle\DSL\Filter\HasChildFilter, ONGR\ElasticsearchBundle...\Filter\HasParentFilter, ONGR\ElasticsearchBundle\DSL\Filter\IdsFilter, ONGR\ElasticsearchBundle\DSL\Filter\MissingFilter, ONGR\ElasticsearchBundle\DSL\Filter\NestedFilter, ONGR\ElasticsearchBundle\DSL\Filter\NotFilter, ONGR\ElasticsearchBundle\DSL\Filter\OrFilter, ONGR\ElasticsearchBundle\DSL\Filter\PrefixFilter, ONGR\ElasticsearchBundle\DSL\Filter\QueryFilter, ONGR\ElasticsearchBundle\DSL\Filter\RangeFilter, ONGR\ElasticsearchBundle\DSL\Filter\RegexpFilter, ONGR\ElasticsearchBundle\DSL\Filter\ScriptFilter, ONGR\ElasticsearchBundle\DSL\Filter\TermFilter, ONGR\ElasticsearchBundle\DSL\Filter\TermsFilter, ONGR\ElasticsearchBundle\DSL\Query\BoolQuery, ONGR\ElasticsearchBundle...\Query\CommonTermsQuery, ONGR\ElasticsearchBundle...uery\ConstantScoreQuery, ONGR\ElasticsearchBundle\DSL\Query\DisMaxQuery, ONGR\ElasticsearchBundle\DSL\Query\FilteredQuery, ONGR\ElasticsearchBundle...uery\FunctionScoreQuery, ONGR\ElasticsearchBundle...FuzzyLikeThisFieldQuery, ONGR\ElasticsearchBundle...uery\FuzzyLikeThisQuery, ONGR\ElasticsearchBundle\DSL\Query\FuzzyQuery, ONGR\ElasticsearchBundle\DSL\Query\HasChildQuery, ONGR\ElasticsearchBundle\DSL\Query\HasParentQuery, ONGR\ElasticsearchBundle\DSL\Query\IdsQuery, ONGR\ElasticsearchBundle\DSL\Query\MatchAllQuery, ONGR\ElasticsearchBundle\DSL\Query\MatchQuery, ONGR\ElasticsearchBundle...Query\MoreLikeThisQuery, ONGR\ElasticsearchBundle\DSL\Query\MultiMatchQuery, ONGR\ElasticsearchBundle\DSL\Query\PrefixQuery, ONGR\ElasticsearchBundle...\Query\QueryStringQuery, ONGR\ElasticsearchBundle\DSL\Query\RangeQuery, ONGR\ElasticsearchBundle\DSL\Query\RegexpQuery, ONGR\ElasticsearchBundle...\SimpleQueryStringQuery, ONGR\ElasticsearchBundle...ery\Span\SpanFirstQuery, ONGR\ElasticsearchBundle...Span\SpanMultiTermQuery, ONGR\ElasticsearchBundle...uery\Span\SpanNearQuery, ONGR\ElasticsearchBundle...Query\Span\SpanNotQuery, ONGR\ElasticsearchBundle...\Query\Span\SpanOrQuery, ONGR\ElasticsearchBundle...uery\Span\SpanTermQuery, ONGR\ElasticsearchBundle\DSL\Query\TermQuery, ONGR\ElasticsearchBundle\DSL\Query\TermsQuery, ONGR\ElasticsearchBundle\DSL\Query\WildcardQuery.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
86
            }
87
88
            $isRelevant = true;
89
        }
90
91
        return $isRelevant ? [$this->getBuilder()->getType() => $this->getBuilder()->toArray()] : null;
92
    }
93
94
    /**
95
     * {@inheritdoc}
96
     */
97
    public function getOrder()
98
    {
99
        return 2;
100
    }
101
102
    /**
103
     * {@inheritdoc}
104
     */
105
    public function getBuilder()
106
    {
107
        return $this->query;
108
    }
109
110
    /**
111
     * Sets builder.
112
     *
113
     * @param BuilderInterface $builder
114
     */
115
    protected function setBuilder(BuilderInterface $builder)
116
    {
117
        $this->query = $builder;
118
    }
119
120
    /**
121
     * Default properties for query.
122
     *
123
     * @param OptionsResolver $resolver
124
     */
125
    protected function configureResolver(OptionsResolver $resolver)
126
    {
127
        $resolver
128
            ->setDefaults(
129
                ['bool_type' => BoolQuery::MUST]
130
            );
131
    }
132
133
    /**
134
     * Returns true if query is bool.
135
     *
136
     * @return bool
137
     */
138
    protected function isBool()
139
    {
140
        return $this->getBuilder() instanceof BoolQuery;
141
    }
142
143
    /**
144
     * Returns bool instance for this endpoint case.
145
     *
146
     * @return BoolQuery
147
     */
148
    protected function getBoolInstance()
149
    {
150
        return new BoolQuery();
151
    }
152
153
    /**
154
     * Converts query to bool.
155
     */
156
    private function convertToBool()
157
    {
158
        $bool = $this->getBoolInstance();
159
160
        if ($this->query !== null) {
161
            $bool->add($this->query);
162
        }
163
164
        $this->query = $bool;
165
    }
166
}
167