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 |
||
11 | final class FallbackNormalizerContainer implements NormalizerContainerInterface |
||
12 | { |
||
13 | private $default; |
||
14 | private $handlers = []; |
||
15 | private $interfaces = []; |
||
16 | private $aliases = []; |
||
17 | |||
18 | 20 | View Code Duplication | public function add($class, callable $handler) |
|
|||
19 | { |
||
20 | 20 | if(class_exists($class)) { |
|
21 | 16 | $this->aliases[$class] = $class; |
|
22 | 16 | $this->handlers[$class] = $handler; |
|
23 | 4 | } elseif(interface_exists($class)) { |
|
24 | 3 | $this->aliases[$class] = $class; |
|
25 | 3 | $this->interfaces[$class] = $handler; |
|
26 | } else { |
||
27 | 1 | throw ClassNotFoundException::fromClass($class); |
|
28 | } |
||
29 | 19 | } |
|
30 | |||
31 | 2 | View Code Duplication | public function addAlias($alias, $class) |
32 | { |
||
33 | 2 | $handler = $this->getHandler($class); |
|
34 | |||
35 | 1 | $this->handlers[$alias] = $handler; |
|
36 | 1 | $this->aliases[$alias] = $this->aliases[$class]; |
|
37 | 1 | } |
|
38 | |||
39 | 18 | public function getHandler($class) |
|
40 | { |
||
41 | 18 | if(isset($this->handlers[$class])) { |
|
42 | 13 | return $this->handlers[$class]; |
|
43 | } |
||
44 | |||
45 | 8 | $parents = array_intersect(array_keys($this->handlers), class_parents($class)); |
|
46 | 8 | if($parents) { |
|
47 | 2 | return $this->handlers[array_pop($parents)]; |
|
48 | } |
||
49 | |||
50 | 6 | $interfaces = array_intersect(array_keys($this->interfaces), array_values(class_implements($class))); |
|
51 | 6 | View Code Duplication | if($interfaces) { |
52 | 3 | if(\count($interfaces) > 1) { |
|
53 | 1 | throw NormalizerConflictException::fromClass($class, $interfaces); |
|
54 | } |
||
55 | |||
56 | 2 | return $this->interfaces[array_shift($interfaces)]; |
|
57 | } |
||
58 | |||
59 | 3 | if(null === $this->default) { |
|
60 | 2 | throw NormalizerNotFoundException::fromClass($class); |
|
61 | } |
||
62 | |||
63 | 1 | return $this->default; |
|
64 | } |
||
65 | |||
66 | 2 | public function setDefault(callable $handler) |
|
70 | |||
71 | 1 | public function hasDefault() |
|
75 | |||
76 | 1 | public function getDefault() |
|
80 | } |
||
81 |
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.