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 Resource |
||
6 | { |
||
7 | public static $prefix = 'urn'; |
||
8 | |||
9 | /** |
||
10 | * @var array |
||
11 | */ |
||
12 | private $resources; |
||
13 | |||
14 | /** |
||
15 | * @param array|string $resources |
||
16 | */ |
||
17 | 24 | View Code Duplication | public function __construct($resources) |
|
|||
18 | { |
||
19 | 24 | if ( ! is_array($resources)) { |
|
20 | 23 | $resources = (array)$resources; |
|
21 | } |
||
22 | |||
23 | 24 | foreach ($resources as $resource) { |
|
24 | 24 | if ($resource === '*') { |
|
25 | 2 | continue; |
|
26 | } |
||
27 | |||
28 | 22 | if (strpos($resource, self::$prefix . ':') !== 0) { |
|
29 | 22 | throw new \InvalidArgumentException('Invalid resource "' . $resource . '".'); |
|
30 | } |
||
31 | } |
||
32 | |||
33 | 23 | $this->resources = $resources; |
|
34 | 23 | } |
|
35 | |||
36 | /** |
||
37 | * @return array |
||
38 | */ |
||
39 | public function getResources() |
||
43 | |||
44 | /** |
||
45 | * @return array |
||
46 | */ |
||
47 | 17 | public function getResourcesCompiled(array $variables = []) |
|
58 | |||
59 | /** |
||
60 | * @param string $requestedResource |
||
61 | * @return bool |
||
62 | */ |
||
63 | 17 | public function matches($requestedResource, array $variables = []) |
|
78 | |||
79 | /** |
||
80 | * @param array $variables |
||
81 | * @return array |
||
82 | */ |
||
83 | 17 | private function mapVariables(array $variables) |
|
91 | |||
92 | /** |
||
93 | * @param string $resource |
||
94 | * @param array $variables |
||
95 | * @return string |
||
96 | */ |
||
97 | 17 | private function replaceVariables($resource, array $variables) |
|
101 | |||
102 | /** |
||
103 | * @param string $resource |
||
104 | * @return string |
||
105 | */ |
||
106 | 17 | private function replaceWildcard($resource) |
|
110 | } |
||
111 |
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.