RuleFilterer::validateRule()   F
last analyzed

Complexity

Conditions 29
Paths 128

Size

Total Lines 136

Duplication

Lines 31
Ratio 22.79 %

Code Coverage

Tests 81
CRAP Score 30.1163

Importance

Changes 0
Metric Value
cc 29
nc 128
nop 7
dl 31
loc 136
ccs 81
cts 91
cp 0.8901
crap 30.1163
rs 3.1466
c 0
b 0
f 0

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
 * RuleFilterer
4
 *
5
 * @package php-logical-filter
6
 * @author  Jean Claveau
7
 */
8
namespace JClaveau\LogicalFilter\Filterer;
9
10
use JClaveau\LogicalFilter\LogicalFilter;
11
use JClaveau\LogicalFilter\Rule\EqualRule;
12
use JClaveau\LogicalFilter\Rule\BelowRule;
13
use JClaveau\LogicalFilter\Rule\AboveRule;
14
use JClaveau\LogicalFilter\Rule\BelowOrEqualRule;
15
use JClaveau\LogicalFilter\Rule\AboveOrEqualRule;
16
use JClaveau\LogicalFilter\Rule\OrRule;
17
use JClaveau\LogicalFilter\Rule\AndRule;
18
use JClaveau\LogicalFilter\Rule\NotRule;
19
use JClaveau\LogicalFilter\Rule\NotEqualRule;
20
use JClaveau\LogicalFilter\Rule\AbstractOperationRule;
21
use JClaveau\LogicalFilter\Rule\AbstractRule;
22
use JClaveau\LogicalFilter\Rule\InRule;
23
use JClaveau\LogicalFilter\Rule\NotInRule;
24
use JClaveau\LogicalFilter\Rule\RegexpRule;
25
26
/**
27
 * This filterer is intended to validate Rules.
28
 *
29
 * Manipulating the rules of a logical filter is easier with another one.
30
 * This filterer is used for the functions of the exposed api like
31
 * removeRules().
32
 */
33
class RuleFilterer extends Filterer
34
{
35
    const this        = 'instance';
36
    const field       = 'field';
37
    const operator    = 'operator';
38
    const value       = 'value';
39
    const depth       = 'depth';
40
    const children    = 'children';
41
    const description = 'description';
42
    const path        = 'path';
43
44
    /** @var array $handled_properties */
45
    protected static $handled_properties = [
46
        self::field,
47
        self::operator,
48
        self::value,
49
        self::depth,
50
        self::description,
51
        self::children,
52
        self::path,
53
    ];
54
55
    /**
56
     * Retrieves the children of the current rule to seek during the
57
     * recursive scanning of the rule tree.
58
     *
59
     * @return array
0 ignored issues
show
Documentation introduced by
Should the return type not be array|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
60
     */
61 45
    public function getChildren($row) // strict issue if forcing  AbstractRule with php 5.6 here
62
    {
63 45
        if ($row instanceof InRule) {
64
            // We do not need to parse the EqualRule operands of InRules
65
            // as they all share the same field
66 3
            return [];
67
        }
68
69 45
        if ($row instanceof AbstractOperationRule) {
70 43
            return $row->getOperands();
71
        }
72 43
    }
73
74
    /**
75
     * Provides the updated rule to replace the scanned one during rule
76
     * scanning.
77
     *
78
     * @param  AbstractRule $row
79
     * @param  $filtered_children
80
     *
81
     * @return AbstractRule
82
     */
83 39
    public function setChildren(&$row, $filtered_children) // strict issue if forcing  AbstractRule with php 5.6 here
84
    {
85 39
        if ($row instanceof AbstractOperationRule) {
86 39
            return $row->setOperandsOrReplaceByOperation($filtered_children, []); // no simplification options?
0 ignored issues
show
Bug introduced by
The method setOperandsOrReplaceByOperation() does not exist on JClaveau\LogicalFilter\Rule\AbstractOperationRule. Did you maybe mean setOperands()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
87
        }
88
    }
89
90
    /**
91
     * For each rule of the scanned rule tree this method validates its
92
     * matching against the filtering logical filter.
93
     *
94
     * @param  string       $field
95
     * @param  string       $operator
96
     * @param  mixed        $value
97
     * @param  AbstractRule $value
98
     * @param  array        $path
99
     * @param  mixed        $all_operands
100
     * @param  array        $options
101
     *
102
     * @return  + true if the rule validates
0 ignored issues
show
Documentation introduced by
The doc-type + could not be parsed: Unknown type name "+" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
103
     *          + false if not
104
     *          + null if the matchin has no sens (like filktering by field on an operation rule)
105
     */
106 44
    public function validateRule($field, $operator, $value, $rule, array $path, $all_operands, $options)
107
    {
108 44
        if (   ! empty($options[ Filterer::leaves_only ])
109 44
            && in_array( get_class($rule), [OrRule::class, AndRule::class, NotRule::class] )
110 44
        ) {
111
            // Rules concerning the "field of a rule" have nbo sens on
112
            // operation rules
113 4
            return null;
114
        }
115
116 44
        if (self::field === $field) {
117 35
            if (! method_exists($rule, 'getField')) {
118
                // if (in_array( get_class($rule), [AndRule::class, OrRule::class]))
119 27
                return null; // The filter cannot be applied to this rule
120
            }
121
122
            try {
123 35
                $value_to_validate = $rule->getField();
124
            }
125 35
            catch (\LogicException $e) {
126
                // This is due to NotInRule.
127
                // TODO replace it by a TrueRule in this case
128
                return  null;
129
            }
130 35
        }
131 40
        elseif (self::operator === $field) {
132 26
            $value_to_validate = $rule::operator;
133 26
        }
134 26
        elseif (self::value === $field) {
135 18
            $description = $rule->toArray();
136
137 18
            if (    3 === count($description)
138 18
                && is_string($description[0])
139 18
                && is_string($description[1]) ) {
140 18
                $value_to_validate = $description[2];
141 18
            }
142
            else {
143 18
                return null; // The filter cannot be applied to this rule
144
            }
145 18
        }
146 8
        elseif (self::description === $field) {
147 1
            $value_to_validate = $rule->toArray();
148 1
        }
149 7
        elseif (self::depth === $field) {
150
            // original $depth is lost once the filter is simplified
151 1
            throw new \InvalidArgumentException('Depth rule suppport not implemented');
152
        }
153 6
        elseif (self::path === $field) {
154
            // TODO the description of its parents
155 1
            throw new \InvalidArgumentException('Path rule suppport not implemented');
156
        }
157 5
        elseif (self::children === $field) {
158 4
            if (! method_exists($rule, 'getOperands')) {
159 1
                return null; // The filter cannot be applied to this rule
160
            }
161 4
            $value_to_validate = count($rule->getOperands());
162 4
        }
163
        else {
164 1
            throw new \InvalidArgumentException(
165
                "Rule filters must belong to ["
166 1
                . implode(', ', static::$handled_properties)
167 1
                ."] contrary to : ".var_export($field, true)
168 1
            );
169
        }
170
171 41
        if (EqualRule::operator === $operator) {
172 26 View Code Duplication
            if (null === $value) {
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...
173 1
                $out = is_null($value_to_validate);
174 1
            }
175
            else {
176
                // TODO support strict comparisons
177 26
                $out = $value_to_validate == $value;
178
            }
179 26
        }
180 29
        elseif (InRule::operator === $operator) {
181 13
            $out = in_array($value_to_validate, $value);
182 13
        }
183 16
        elseif (BelowRule::operator === $operator) {
184 3
            $out = $value_to_validate < $value;
185 3
        }
186 15
        elseif (AboveRule::operator === $operator) {
187 4
            $out = $value_to_validate > $value;
188 4
        }
189 12
        elseif (BelowOrEqualRule::operator === $operator) {
190 3
            $out = $value_to_validate <= $value;
191 3
        }
192 10
        elseif (AboveOrEqualRule::operator === $operator) {
193 3
            $out = $value_to_validate >= $value;
194 3
        }
195 7 View Code Duplication
        elseif (RegexpRule::operator === $operator) {
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...
196
            try {
197
                // TODO support optionnal parameters (offest mainly) ?
198 2
                $out = preg_match($value, $value_to_validate);
199
            }
200 2
            catch (\Exception $e) {
201
                // The documentation of preg_match() is wrong and preg_last_error()
202
                // is useless as preg_match returns 0 instead of false
203
                // and then throws an exception with PHP 5.6
204 1
                throw new \InvalidArgumentException(
205 1
                    "PCRE error ".var_export($e->getMessage(), true).
206 1
                    " while applying the regexp ".var_export($value, true)." to "
207 1
                    .var_export($value_to_validate, true)
208 1
                );
209
            }
210
211 1
            $out = (bool) $out;
212 1
        }
213 5
        elseif (NotEqualRule::operator === $operator) {
214 4 View Code Duplication
            if (null === $value) {
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...
215 1
                $out = ! is_null($value_to_validate);
216 1
            }
217
            else {
218 3
                $out = $value != $value_to_validate;
219
            }
220 4
        }
221 1
        elseif (NotInRule::operator === $operator) {
222 1
            $out = ! in_array($value_to_validate, $value);
223 1
        }
224
        else {
225
            throw new \InvalidArgumentException(
226
                "Unhandled operator: " . $operator
227
            );
228
        }
229
230 40
        if (! empty($options['debug'])) {
231
            var_dump(
232
                "$field, $operator, " . var_export($value, true)
233
                 . ' ||  '. $value_to_validate . ' => ' . var_export($out, true)
234
                 . "\n" . get_class($rule)
235
                 . "\n" . var_export($options, true)
236
            );
237
            // $rule->dump();
238
        }
239
240 40
        return $out;
241
    }
242
243
    /**
244
     * Type checkings before calling apply.
245
     *
246
     * @param LogicalFilter      $filter
247
     * @param array|AbstractRule $ruleTree_to_filter
248
     * @param array              $options leaves_only | debug
249
     */
250 47
    public function apply(LogicalFilter $filter, $ruleTree_to_filter, $options=[])
251
    {
252 47
        if (! $ruleTree_to_filter) {
253 1
            return $ruleTree_to_filter;
254
        }
255
256 46
        if ($ruleTree_to_filter instanceof AbstractRule) {
257 45
            $ruleTree_to_filter = [$ruleTree_to_filter];
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $ruleTree_to_filter. This often makes code more readable.
Loading history...
258 45
        }
259
260 46
        if (! is_array($ruleTree_to_filter)) {
261 1
            throw new \InvalidArgumentException(
262
                "\$ruleTree_to_filter must be an array or an AbstractRule "
263 1
                ."instead of: " . var_export($ruleTree_to_filter, true)
264 1
            );
265
        }
266
267
        // Produces "Only variables should be passed by reference" on Travis
268 45
        $result = parent::apply($filter, $ruleTree_to_filter, $options);
0 ignored issues
show
Documentation introduced by
$ruleTree_to_filter is of type array, but the function expects a object<JClaveau\LogicalFilter\Filterer\Iterable>.

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...
269
270 40
        return reset($result);
271
    }
272
273
    /**/
274
}
275