InRule   A
last analyzed

Complexity

Total Complexity 36

Size/Duplication

Total Lines 238
Duplicated Lines 12.61 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 92.78%

Importance

Changes 0
Metric Value
dl 30
loc 238
ccs 90
cts 97
cp 0.9278
rs 9.52
c 0
b 0
f 0
wmc 36
lcom 1
cbo 3

14 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 2
A getPossibilities() 0 4 1
A addOperand() 0 6 1
A setPossibilities() 0 8 1
A setOperands() 0 6 1
A checkOperandAndExtractValue() 0 15 4
A getOperands() 0 13 3
A getValues() 0 4 1
B toArray() 30 30 7
A toString() 0 14 2
A isNormalizationAllowed() 0 8 2
A hasSolution() 0 4 1
A removeNegations() 0 4 1
B addPossibilities() 0 36 9

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * InRule
4
 *
5
 * @package php-logical-filter
6
 * @author  Jean Claveau
7
 */
8
namespace JClaveau\LogicalFilter\Rule;
9
10
/**
11
 * This class represents a rule that expect a value to belong to a list of others.
12
 */
13
class InRule extends OrRule
14
{
15
    use Trait_RuleWithField;
16
17
    /** @var string operator */
18
    const operator = 'in';
19
20
    /** @var array $native_possibilities */
21
    protected $native_possibilities = [];
22
23
    /**
24
     * @param string $field         The field to apply the rule on.
25
     * @param mixed  $possibilities The values the field can belong to.
26
     */
27 81
    public function __construct($field, $possibilities, array $options=[])
28
    {
29 81
        if (! empty($options)) {
30 53
            $this->setOptions($options);
31 53
        }
32
33 81
        $this->field = $field;
34 81
        $this->addPossibilities( $possibilities );
35 81
    }
36
37
    /**
38
     * @return array
39
     */
40 78
    public function getPossibilities()
41
    {
42 78
        return array_values($this->native_possibilities);
43
    }
44
45
    /**
46
     * @param  mixed possibilities
47
     *
48
     * @return InRule $this
49
     */
50 81
    public function addPossibilities($possibilities)
51
    {
52 81
        if (    is_object($possibilities)
53 81
            && $possibilities instanceof \IteratorAggregate
54 81
            && method_exists($possibilities, 'toArray')
55 81
        ) {
56 2
            $possibilities = $possibilities->toArray();
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $possibilities. This often makes code more readable.
Loading history...
57 2
        }
58
59 81
        if ( ! is_array($possibilities)) {
60
            $possibilities = [$possibilities];
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $possibilities. This often makes code more readable.
Loading history...
61
        }
62
63 81
        $possibilities = array_map([$this, 'checkOperandAndExtractValue'], $possibilities);
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $possibilities. This often makes code more readable.
Loading history...
64
65
        // unique possibilities
66 81
        foreach ($possibilities as &$possibility) {
67 78
            if (is_scalar($possibility)) {
68 78
                $id = hash('crc32b', $possibility);
69 78
            }
70
            else {
71 8
                $id = hash('crc32b', serialize($possibility));
72
            }
73
74 78
            if ( ! isset($this->native_possibilities[ $id ])) {
75 78
                $this->native_possibilities[ $id ] = $possibility;
76 78
                $require_cache_flush               = true;
77 78
            }
78 81
        }
79
80 81
        if (isset($require_cache_flush)) {
81 78
            $this->flushCache();
82 78
        }
83
84 81
        return $this;
85
    }
86
87
    /**
88
     * @param  array possibilities
89
     *
90
     * @return InRule $this
91
     */
92
    public function addOperand( AbstractRule $operand )
93
    {
94
        $this->addPossibilities([$operand->getValue()]);
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 getValue() does only exist in the following sub-classes of JClaveau\LogicalFilter\Rule\AbstractRule: JClaveau\LogicalFilter\Rule\EqualRule, JClaveau\LogicalFilter\Rule\NotEqualRule. 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...
95
96
        return $this;
97
    }
98
99
    /**
100
     * @param  mixed possibilities
101
     *
102
     * @return InRule $this
103
     */
104 17
    public function setPossibilities($possibilities)
105
    {
106 17
        $this->native_possibilities = [];
107 17
        $this->addPossibilities($possibilities);
108 17
        $this->flushCache();
109
110 17
        return $this;
111
    }
112
113
    /**
114
     * @param  array possibilities
115
     *
116
     * @return InRule $this
117
     */
118 5
    public function setOperands(array $operands)
119
    {
120 5
        $this->addPossibilities($operands);
121
122 4
        return $this;
123
    }
124
125
    /**
126
     *
127
     */
128 78
    protected function checkOperandAndExtractValue($operand)
129
    {
130 78
        if ( ! $operand instanceof AbstractAtomicRule) {
131 78
            return $operand;
132
        }
133
134 6
        if ( ! ($operand instanceof EqualRule && $operand->getField() == $this->field) ) {
135 2
            throw new \InvalidArgumentException(
136
                "Trying to set an invalid operand of an InRule: "
137 2
                .var_export($operand, true)
138 2
            );
139
        }
140
141 5
        return $operand->getValue();
142
    }
143
144
    /**
145
     * @return InRule $this
146
     */
147 25
    public function getOperands()
148
    {
149 25
        if ( ! empty($this->cache['operands'])) {
150 6
            return $this->cache['operands'];
151
        }
152
153 25
        $operands = [];
154 25
        foreach ($this->native_possibilities as $value) {
155 24
            $operands[] = new EqualRule($this->field, $value);
156 25
        }
157
158 25
        return $this->cache['operands'] = $operands;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->cache['operands'] = $operands; (array) is incompatible with the return type documented by JClaveau\LogicalFilter\Rule\InRule::getOperands of type JClaveau\LogicalFilter\Rule\InRule.

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...
159
    }
160
161
    /**
162
     * @return array
163
     */
164 77
    public function getValues()
165
    {
166 77
        return $this->getPossibilities();
167
    }
168
169
    /**
170
     * @param array $options   + show_instance=false Display the operator of the rule or its instance id
171
     *
172
     * @return array
173
     */
174 77 View Code Duplication
    public function toArray(array $options=[])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
175
    {
176
        $default_options = [
177 77
            'show_instance' => false,
178 77
        ];
179 77
        foreach ($default_options as $default_option => &$default_value) {
180 77
            if ( ! isset($options[ $default_option ])) {
181 77
                $options[ $default_option ] = $default_value;
182 77
            }
183 77
        }
184
185 77
        $class = get_class($this);
186
187 77
        if ( ! $options['show_instance'] && isset($this->cache['array'])) {
188 48
            return $this->cache['array'];
189
        }
190
191
        $array = [
192 77
            $this->getField(),
193 77
            $options['show_instance'] ? $this->getInstanceId() : $class::operator,
194 77
            $this->getValues(),
195 77
        ];
196
197 77
        if ( ! $options['show_instance']) {
198 77
            return $this->cache['array'] = $array;
199
        }
200
        else {
201
            return $array;
202
        }
203
    }
204
205
    /**
206
     */
207 1
    public function toString(array $options=[])
208
    {
209 1
        if (isset($this->cache['string'])) {
210 1
            return $this->cache['string'];
211
        }
212
213 1
        $operator = self::operator;
214
215 1
        $stringified_possibilities = '[' . implode(', ', array_map(function($possibility) {
216 1
            return var_export($possibility, true);
217 1
        }, $this->getPossibilities()) ) .']';
218
219 1
        return $this->cache['string'] = "['{$this->getField()}', '$operator', $stringified_possibilities]";
220
    }
221
222
    /**
223
     */
224 44
    public function isNormalizationAllowed(array $contextual_options)
225
    {
226 44
        if (null === ($threshold = $this->getOption('in.normalization_threshold', $contextual_options))) {
227
            return false;
228
        }
229
230 44
        return count($this->native_possibilities) <= $threshold;
231
    }
232
233
    /**
234
     * @return bool If the InRule can have a solution or not
235
     */
236 3
    public function hasSolution(array $contextual_options=[])
237
    {
238 3
        return ! empty($this->getPossibilities());
239
    }
240
241
    /**
242
     * There is no negations into an InRule
243
     */
244 32
    public function removeNegations(array $contextual_options)
245
    {
246 32
        return $this;
247
    }
248
249
    /**/
250
}
251