Passed
Push — master ( 24a186...7333d4 )
by Jean
03:20
created

InRule   A

Complexity

Total Complexity 36

Size/Duplication

Total Lines 238
Duplicated Lines 15.13 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 92.78%

Importance

Changes 0
Metric Value
dl 36
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
B addPossibilities() 6 36 9
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

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 50
    public function __construct($field, $possibilities, array $options=[])
28
    {
29 50
        if (! empty($options)) {
30 30
            $this->setOptions($options);
31 30
        }
32
33 50
        $this->field = $field;
34 50
        $this->addPossibilities( $possibilities );
35 50
    }
36
37
    /**
38
     * @return array
39
     */
40 54
    public function getPossibilities()
41
    {
42 54
        return array_values($this->native_possibilities);
43
    }
44
45
    /**
46
     * @param  mixed possibilities
47
     *
48
     * @return InRule $this
49
     */
50 51
    public function addPossibilities($possibilities)
51
    {
52 51 View Code Duplication
        if (    is_object($possibilities)
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...
53 51
            && $possibilities instanceof \IteratorAggregate
54 51
            && method_exists($possibilities, 'toArray')
55 51
        ) {
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 51
        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 51
        $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 51
        foreach ($possibilities as &$possibility) {
67 49
            if (is_scalar($possibility)) {
68 49
                $id = hash('crc32b', $possibility);
69 49
            }
70
            else {
71 1
                $id = hash('crc32b', serialize($possibility));
72
            }
73
74 49
            if ( ! isset($this->native_possibilities[ $id ])) {
75 49
                $this->native_possibilities[ $id ] = $possibility;
76 49
                $require_cache_flush               = true;
77 49
            }
78 51
        }
79
80 51
        if (isset($require_cache_flush)) {
81 49
            $this->flushCache();
82 49
        }
83
84 51
        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 14
    public function setPossibilities($possibilities)
105
    {
106 14
        $this->native_possibilities = [];
107 14
        $this->addPossibilities($possibilities);
108 14
        $this->flushCache();
109
110 14
        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 49
    protected function checkOperandAndExtractValue($operand)
129
    {
130 49
        if ( ! $operand instanceof AbstractAtomicRule) {
131 49
            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 22
    public function getOperands()
148
    {
149 22
        if ( ! empty($this->cache['operands'])) {
150 6
            return $this->cache['operands'];
151
        }
152
153 22
        $operands = [];
154 22
        foreach ($this->native_possibilities as $value) {
155 21
            $operands[] = new EqualRule($this->field, $value);
156 22
        }
157
158 22
        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 51
    public function getValues()
165
    {
166 51
        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 55 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 55
            'show_instance' => false,
178 55
        ];
179 55
        foreach ($default_options as $default_option => &$default_value) {
180 55
            if ( ! isset($options[ $default_option ])) {
181 55
                $options[ $default_option ] = $default_value;
182 55
            }
183 55
        }
184
185 55
        $class = get_class($this);
186
187 55
        if ( ! $options['show_instance'] && isset($this->cache['array'])) {
188 42
            return $this->cache['array'];
189
        }
190
191
        $array = [
192 46
            $this->getField(),
193 46
            $options['show_instance'] ? $this->getInstanceId() : $class::operator,
194 46
            $this->getValues(),
195 46
        ];
196
197 46
        if ( ! $options['show_instance']) {
198 46
            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 36
    public function isNormalizationAllowed(array $contextual_options)
225
    {
226 36
        if (null === ($threshold = $this->getOption('in.normalization_threshold', $contextual_options))) {
227
            return false;
228
        }
229
230 36
        return count($this->native_possibilities) <= $threshold;
231
    }
232
233
    /**
234
     * @return bool If the InRule can have a solution or not
235
     */
236 2
    public function hasSolution(array $contextual_options=[])
237
    {
238 2
        return ! empty($this->getPossibilities());
239
    }
240
241
    /**
242
     * There is no negations into an InRule
243
     */
244 20
    public function removeNegations(array $contextual_options)
245
    {
246 20
        return $this;
247
    }
248
249
    /**/
250
}
251