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 |
||
13 | class HostParser implements ParserInterface, RobotsTxtInterface |
||
14 | { |
||
15 | use UrlParser; |
||
16 | |||
17 | /** |
||
18 | * Base Uri |
||
19 | * @var string |
||
20 | */ |
||
21 | private $base; |
||
22 | |||
23 | /** |
||
24 | * Parent directive |
||
25 | * @var string|null |
||
26 | */ |
||
27 | private $parent; |
||
28 | |||
29 | /** |
||
30 | * Host array |
||
31 | * @var string[] |
||
32 | */ |
||
33 | private $host = []; |
||
34 | |||
35 | /** |
||
36 | * Host constructor. |
||
37 | * |
||
38 | * @param string $base |
||
39 | * @param string|null $parentDirective |
||
40 | */ |
||
41 | public function __construct($base, $parentDirective = null) |
||
46 | |||
47 | /** |
||
48 | * Add |
||
49 | * |
||
50 | * @param string $line |
||
51 | * @return bool |
||
52 | */ |
||
53 | public function add($line) |
||
54 | { |
||
55 | $host = $this->parse($line); |
||
56 | if ( |
||
57 | $host === false || |
||
58 | $line !== $host || |
||
59 | in_array($host, $this->host) |
||
60 | ) { |
||
61 | return false; |
||
62 | } |
||
63 | $this->host[] = $line; |
||
64 | return true; |
||
65 | } |
||
66 | |||
67 | /** |
||
68 | * Client |
||
69 | * |
||
70 | * @param string $line |
||
71 | * @return string|false |
||
72 | */ |
||
73 | private function parse($line) |
||
87 | |||
88 | /** |
||
89 | * Get URL parts |
||
90 | * |
||
91 | * @param string $url |
||
92 | * @return string[]|false |
||
93 | */ |
||
94 | private function getParts($url) |
||
102 | |||
103 | /** |
||
104 | * Client |
||
105 | * |
||
106 | * @return HostClient |
||
107 | */ |
||
108 | public function client() |
||
112 | |||
113 | /** |
||
114 | * Render |
||
115 | * |
||
116 | * @return string[] |
||
117 | */ |
||
118 | View Code Duplication | public function render() |
|
127 | } |
||
128 |
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.