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 |
||
5 | class Rule |
||
6 | { |
||
7 | const TYPE_OBJECT = 'object'; |
||
8 | |||
9 | const TYPE_SCALAR = 'scalar'; |
||
10 | |||
11 | const TYPE_CUSTOM = 'custom-validator'; |
||
12 | |||
13 | private static $avalableRuleTypes = [ |
||
14 | self::TYPE_OBJECT, |
||
15 | self::TYPE_SCALAR, |
||
16 | self::TYPE_CUSTOM, |
||
17 | ]; |
||
18 | |||
19 | private $rule; |
||
20 | |||
21 | private function __construct(array $rule) |
||
22 | { |
||
23 | $this->rule = $rule; |
||
24 | } |
||
25 | |||
26 | public static function fromArray(array $rule) |
||
27 | { |
||
28 | if ([] === $rule) { |
||
29 | throw new \LogicException( |
||
30 | 'rule type is not defined' |
||
31 | ); |
||
32 | } |
||
33 | |||
34 | return new self($rule); |
||
35 | } |
||
36 | |||
37 | View Code Duplication | public function ensureRuleNameIsValid() |
|
47 | |||
48 | public function asArray() : array |
||
49 | { |
||
50 | return $this->rule; |
||
51 | } |
||
52 | |||
53 | public function isValid() |
||
54 | { |
||
55 | return in_array(key($this->rule), static::$avalableRuleTypes); |
||
56 | } |
||
57 | |||
58 | public function is($type) |
||
59 | { |
||
60 | return key($this->rule) === $type; |
||
61 | } |
||
62 | |||
63 | public function isNot($type) |
||
64 | { |
||
65 | return !$this->is($type); |
||
66 | } |
||
67 | |||
68 | public function isCustom() |
||
69 | { |
||
70 | return $this->is(Rule::TYPE_CUSTOM); |
||
71 | } |
||
72 | |||
73 | public function isNotCustom() |
||
74 | { |
||
75 | return !$this->isCustom(); |
||
76 | } |
||
77 | |||
78 | public function isNotMail() |
||
79 | { |
||
80 | return 'email' != $this->getValue(); |
||
81 | } |
||
82 | |||
83 | public function getRuleType() |
||
84 | { |
||
85 | return key($this->rule); |
||
86 | } |
||
87 | |||
88 | public function isObject() |
||
89 | { |
||
90 | return isset($this->rule[self::TYPE_OBJECT]); |
||
91 | } |
||
92 | |||
93 | public function getObjectType() |
||
94 | { |
||
95 | return $this->rule['object']; |
||
96 | } |
||
97 | |||
98 | public function getValue() |
||
99 | { |
||
100 | return current($this->rule); |
||
101 | } |
||
102 | |||
103 | View Code Duplication | public function getExpectedType() |
|
113 | |||
114 | public function isValueNotAnObject() |
||
115 | { |
||
116 | return 'array' !== $this->getValue(); |
||
117 | } |
||
118 | } |
||
119 |
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.