NotRule::negateOperand()   F
last analyzed

Complexity

Conditions 20
Paths 81

Size

Total Lines 136

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 87
CRAP Score 20.0045

Importance

Changes 0
Metric Value
cc 20
nc 81
nop 1
dl 0
loc 136
ccs 87
cts 89
cp 0.9775
crap 20.0045
rs 3.3333
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
namespace JClaveau\LogicalFilter\Rule;
3
4
/**
5
 * Logical negation:
6
 * @see https://en.wikipedia.org/wiki/Negation
7
 */
8
class NotRule extends AbstractOperationRule
9
{
10
    /** @var string operator */
11
    const operator = 'not';
12
13
    /**
14
     */
15 62
    public function __construct( AbstractRule $operand=null, array $options=[] )
16
    {
17 62
        if ( ! empty($options)) {
18 34
            $this->setOptions($options);
19 34
        }
20
21
        // Negation has only one operand. If more is required, group them
22
        // into an AndRule
23 62
        if ($operand) {
24 42
            $this->addOperand($operand);
25 42
        }
26 62
    }
27
28
    /**
29
     */
30 33
    public function isNormalizationAllowed(array $current_simplification_options=[])
31
    {
32 33
        $operand = $this->getOperandAt(0);
33
34 33
        return null !== $operand;
35
    }
36
37
    /**
38
     * Transforms all composite rules in the tree of operands into
39
     * atomic rules.
40
     *
41
     * @todo use get_class instead of instanceof to avoid order issue
42
     *       in the conditions.
43
     *
44
     * @param  array
45
     * @return AbstractRule
46
     */
47 37
    public function negateOperand(array $current_simplification_options)
48
    {
49 37
        if ( ! $this->isNormalizationAllowed($current_simplification_options)) {
50 27
            return $this;
51
        }
52
53 17
        $operand = $this->getOperandAt(0);
54
55 17
        if (method_exists($operand, 'getField')) {
56 14
            $field = $operand->getField();
57
58 14
            if ($operand instanceof AboveRule) {
59 5
                $new_rule = new OrRule([
60 5
                    new BelowRule($field, $operand->getLowerLimit()),
61 5
                    new EqualRule($field, $operand->getLowerLimit()),
62 5
                ]);
63 5
            }
64 12
            elseif ($operand instanceof BelowRule) {
65
                // ! (v >  a) : v <= a : (v < a || a = v)
66 4
                $new_rule = new OrRule([
67 4
                    new AboveRule($field, $operand->getUpperLimit()),
68 4
                    new EqualRule($field, $operand->getUpperLimit()),
69 4
                ]);
70 4
            }
71 11
            elseif ($operand instanceof EqualRule && null === $operand->getValue()) {
72 2
                $new_rule = new NotEqualRule($field, null);
73 2
            }
74 10
            elseif ($operand instanceof EqualRule) {
75
                // ! (v =  a) : (v < a) || (v > a)
76 9
                if ($this->getOption('not_equal.normalization', $current_simplification_options)) {
77 6
                    $new_rule = new OrRule([
78 6
                        new AboveRule($field, $operand->getValue()),
79 6
                        new BelowRule($field, $operand->getValue()),
80 6
                    ]);
81 6
                }
82
                else {
83 4
                    $new_rule = new NotEqualRule( $field, $operand->getValue() );
84
                }
85 9
            }
86 6
            elseif ($operand instanceof NotEqualRule) {
87
                $new_rule = new EqualRule( $field, $operand->getValue() );
88
            }
89 14
        }
90
91 17
        if ($operand instanceof AndRule) {
92
            // @see https://github.com/jclaveau/php-logical-filter/issues/40
93
            // ! (B && A) : (!B && A) || (B && !A) || (!B && !A)
94
            // ! (A && B && C) :
95
            //    (!A && !B && !C)
96
            // || (!A && B && C) || (!A && !B && C) || (!A && B && !C)
97
            // || (A && !B && C) || (!A && !B && C) || (A && !B && !C)
98
            // || (A && B && !C) || (!A && B && !C) || (A && !B && !C)
99
100
            // We combine all possibilities of rules and themselves negated
101 2
            $new_rule       = new OrRule;
102 2
            $child_operands = $operand->getOperands();
103
104 2
            $current_operand               = array_shift($child_operands);
105 2
            $current_operand_possibilities = new OrRule([
106 2
                new AndRule([
107 2
                    $current_operand->copy(),
108 2
                ]),
109 2
                new AndRule([
110 2
                    new NotRule($current_operand->copy()),
111 2
                ]),
112 2
            ]);
113
114
            // for every remaining operand, we duplicate the already made
115
            // combinations and add on half of them !$next_operand
116
            // and $next_operand on the other half
117 2
            while ($next_operand = array_shift($child_operands)) {
118 2
                $next_operand_possibilities = $current_operand_possibilities->copy();
119
120 2
                $tmp = [];
121 2
                foreach ($current_operand_possibilities->getOperands() as $current_operand_possibility) {
122 2
                    $tmp[] = $current_operand_possibility->addOperand( $next_operand->copy() );
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class JClaveau\LogicalFilter\Rule\AbstractRule as the method addOperand() does only exist in the following sub-classes of JClaveau\LogicalFilter\Rule\AbstractRule: JClaveau\LogicalFilter\Rule\AboveOrEqualRule, JClaveau\LogicalFilter\Rule\AbstractOperationRule, JClaveau\LogicalFilter\Rule\AndRule, JClaveau\LogicalFilter\Rule\BelowOrEqualRule, JClaveau\LogicalFilter\Rule\BetweenOrEqualBothRule, JClaveau\LogicalFilter\R...BetweenOrEqualLowerRule, JClaveau\LogicalFilter\R...BetweenOrEqualUpperRule, JClaveau\LogicalFilter\Rule\BetweenRule, JClaveau\LogicalFilter\Rule\InRule, JClaveau\LogicalFilter\Rule\NotEqualRule, JClaveau\LogicalFilter\Rule\NotInRule, JClaveau\LogicalFilter\Rule\NotRule, JClaveau\LogicalFilter\Rule\OrRule. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

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

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
123 2
                }
124 2
                $current_operand_possibilities->setOperands($tmp);
125
126 2
                foreach ($next_operand_possibilities->getOperands() as $next_operand_possibility) {
127 2
                    $current_operand_possibilities->addOperand(
128 2
                        $next_operand_possibility->addOperand( new NotRule($next_operand->copy()) )
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class JClaveau\LogicalFilter\Rule\AbstractRule as the method addOperand() does only exist in the following sub-classes of JClaveau\LogicalFilter\Rule\AbstractRule: JClaveau\LogicalFilter\Rule\AboveOrEqualRule, JClaveau\LogicalFilter\Rule\AbstractOperationRule, JClaveau\LogicalFilter\Rule\AndRule, JClaveau\LogicalFilter\Rule\BelowOrEqualRule, JClaveau\LogicalFilter\Rule\BetweenOrEqualBothRule, JClaveau\LogicalFilter\R...BetweenOrEqualLowerRule, JClaveau\LogicalFilter\R...BetweenOrEqualUpperRule, JClaveau\LogicalFilter\Rule\BetweenRule, JClaveau\LogicalFilter\Rule\InRule, JClaveau\LogicalFilter\Rule\NotEqualRule, JClaveau\LogicalFilter\Rule\NotInRule, JClaveau\LogicalFilter\Rule\NotRule, JClaveau\LogicalFilter\Rule\OrRule. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

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

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
129 2
                    );
130 2
                }
131 2
            }
132
133
            // We remove the only possibility where no rule is negated
134 2
            $combinations = $current_operand_possibilities->getOperands();
135 2
            array_shift($combinations); // The first rule contains no negation
136 2
            $new_rule->setOperands( $combinations )
137
                // ->dump(true)
138
                ;
139 2
        }
140 16
        elseif ($operand instanceof OrRule) {
141
142
            // $operand->dump(true);
143
            if (     $operand instanceof InRule
144 7
                && ! $operand->isNormalizationAllowed($current_simplification_options)
145 7
            ) {
146
                // ['not', ['field', 'in', [2, 3]]] <=> ['field', '!in', [2, 3]]
147 1
                $new_rule = new NotInRule(
148 1
                    $operand->getField(),
149 1
                    $operand->getPossibilities()
150 1
                );
151 1
            }
152
            else {
153
                // ! (A || B) : !A && !B
154
                // ! (A || B || C || D) : !A && !B && !C && !D
155 7
                $new_rule = new AndRule;
156 7
                foreach ($operand->getOperands() as $sub_operand) {
157 7
                    $negation = new NotRule;
158 7
                    $negation = $negation->setOperandsOrReplaceByOperation(
159 7
                        [$sub_operand->copy()],
160
                        $current_simplification_options
161 7
                    );
162 7
                    $new_rule->addOperand( $negation );
163 7
                }
164
            }
165
            // $new_rule->dump(!true);
166 7
        }
167 15
        elseif ($operand instanceof NotRule) {
168
            // ! (  !  a) : a
169 1
            $new_rule = $operand->getOperandAt(0);
170 1
        }
171
172 17
        if ( ! isset($new_rule)) {
173 1
            throw new \LogicException(
174 1
                'Removing NotRule(' . var_export($operand, true) . ') '
175 1
                . ' not implemented'
176 1
            );
177
        }
178
179
        // $new_rule->dump(!true);
180
181 16
        return $new_rule;
182
    }
183
184
    /**
185
     * @todo   Todo remove this method while refactoring the Class tree
186
     *
187
     * @return NotRule
188
     */
189 30
    public function rootifyDisjunctions($simplification_options)
190
    {
191 30
        if ( ! $this->isNormalizationAllowed($simplification_options)) {
192 30
            return $this;
193
        }
194
195
        $this->moveSimplificationStepForward( self::rootify_disjunctions, $simplification_options );
196
197
        // not implemented
198
199
        return $this;
200
    }
201
202
    /**
203
     * Not rules can only have one operand.
204
     *
205
     * @return $this
206
     */
207 37
    public function unifyAtomicOperands($simplification_strategy_step = false, array $contextual_options)
208
    {
209 37
        if ( ! $this->isNormalizationAllowed($contextual_options)) {
210 33
            return $this;
211
        }
212
213 14
        if ($simplification_strategy_step) {
214
            $this->moveSimplificationStepForward( self::unify_atomic_operands, $contextual_options );
215
        }
216
217 14
        return $this;
218
    }
219
220
    /**
221
     * @param array $options   + show_instance=false Display the operator of the rule or its instance id
222
     *
223
     * @return array
224
     */
225 28
    public function toArray(array $options=[])
226
    {
227
        $default_options = [
228 28
            'show_instance' => false,
229 28
            'semantic'      => false,
230 28
        ];
231 28
        foreach ($default_options as $default_option => &$default_value) {
232 28
            if ( ! isset($options[ $default_option ])) {
233 28
                $options[ $default_option ] = $default_value;
234 28
            }
235 28
        }
236
237 28
        if ( ! $options['show_instance'] && isset($this->cache['array'])) {
238 3
            return $this->cache['array'];
239
        }
240
241
        $array = [
242 28
            $options['show_instance'] ? $this->getInstanceId() : self::operator,
243 28
            $this->getOperandAt(0) ? $this->getOperandAt(0)->toArray($options) : false,
244 28
        ];
245
246
        // TODO make a dedicated cache entry for semantic array?
247 28
        if ( ! $options['show_instance'] && ! $options['semantic']) {
248 15
            return $this->cache['array'] = $array;
249
        }
250
        else {
251 28
            return $array;
252
        }
253
    }
254
255
    /**
256
     */
257 1
    public function toString(array $options=[])
258
    {
259 1
        $operator = self::operator;
260 1
        if ( ! $this->operands) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->operands of type JClaveau\LogicalFilter\Rule\AbstractRule[] 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...
261
            return "['{$operator}']";
262
        }
263
264 1
        $indent_unit = isset($options['indent_unit']) ? $options['indent_unit'] : '';
265 1
        $line_break  = $indent_unit ? "\n" : '';
266
267 1
        $out = "['{$operator}',"
268
            . $line_break
269 1
            . ($indent_unit ? : ' ')
270 1
            . str_replace($line_break, $line_break.$indent_unit, $this->getOperandAt(0)->toString($options))
271 1
            . ','
272 1
            . $line_break
273 1
            . ']'
274 1
            ;
275
276 1
        return $out;
277
    }
278
279
    /**
280
     * This method is meant to be used during simplification that would
281
     * need to change the class of the current instance by a normal one.
282
     *
283
     * @param  AbstractRule[] $new_operands
284
     * @param  array          $contextual_options
285
     * @return OrRule The current instance (of or or subclass) or a new OrRule
286
     */
287 14
    public function setOperandsOrReplaceByOperation(array $new_operands, array $contextual_options)
288
    {
289 14
        if (count($new_operands) > 1) {
290 1
            foreach ($new_operands as &$new_operand) {
291 1
                if ($new_operand instanceof AbstractRule) {
292 1
                    $new_operand = $new_operand->toString();
293 1
                }
294 1
            }
295
296 1
            throw new \InvalidArgumentException(
297
                "Negations can handle only one operand instead of: \n"
298 1
                .var_export($new_operands, true)
299 1
            );
300
        }
301
302 14
        $new_operand = reset($new_operands);
303
        // $new_operand->dump();
304
305 14
        if ($new_operand instanceof NotRule) {
306 1
            $operands = $new_operand->getOperands();
307 1
            return reset( $operands );
0 ignored issues
show
Comprehensibility Best Practice introduced by
The expression reset($operands); of type JClaveau\LogicalFilter\Rule\AbstractRule|false adds false to the return on line 307 which is incompatible with the return type documented by JClaveau\LogicalFilter\R...ndsOrReplaceByOperation of type JClaveau\LogicalFilter\Rule\OrRule. It seems like you forgot to handle an error condition.
Loading history...
308
        }
309 14
        elseif ($new_operand instanceof EqualRule && ! $this->getOption('not_equal.normalization', $contextual_options)) {
310 5
            return new NotEqualRule( $new_operand->getField(), $new_operand->getValue(), $this->options );
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \JClaveau\Log...lue(), $this->options); (JClaveau\LogicalFilter\Rule\NotEqualRule) is incompatible with the return type documented by JClaveau\LogicalFilter\R...ndsOrReplaceByOperation of type JClaveau\LogicalFilter\Rule\OrRule.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
311
        }
312 11
        elseif ($new_operand instanceof InRule && ! $this->getOption('not_in.normalization', $contextual_options)) {
313 2
            return new NotInRule( $new_operand->getField(), $new_operand->getPossibilities(), $this->options );
0 ignored issues
show
Unused Code introduced by
The call to NotInRule::__construct() has too many arguments starting with $this->options.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
Bug Best Practice introduced by
The return type of return new \JClaveau\Log...ies(), $this->options); (JClaveau\LogicalFilter\Rule\NotInRule) is incompatible with the return type documented by JClaveau\LogicalFilter\R...ndsOrReplaceByOperation of type JClaveau\LogicalFilter\Rule\OrRule.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
314
        }
315
316
        // Don't use addOperand here to allow inheritance for optimizations (e.g. NotInRule)
317 10
        $out = $this->setOperands($new_operands);
318
319
        return $out
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $out; (JClaveau\LogicalFilter\Rule\NotRule) is incompatible with the return type documented by JClaveau\LogicalFilter\R...ndsOrReplaceByOperation of type JClaveau\LogicalFilter\Rule\OrRule.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
320
            // ->dump()
321 10
            ;
322
    }
323
324
    /**
325
     *
326
     */
327 1
    public function hasSolution(array $contextual_options=[])
328
    {
329 1
        $operand = $this->getOperandAt(0);
330
331 1
        return $operand instanceof AbstractAtomicRule ? ! $operand->hasSolution($contextual_options) : true;
332
    }
333
334
    /**/
335
}
336