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 RoutingNormalizer |
||
6 | { |
||
7 | /** |
||
8 | * Normalizes string and array declarations into associative array. |
||
9 | * |
||
10 | * @param string|array $declaration |
||
11 | * |
||
12 | * @return array |
||
|
|||
13 | */ |
||
14 | public function normalizeDeclaration($declaration) |
||
15 | { |
||
16 | if (is_string($declaration)) { |
||
17 | return $this->normalizeString($declaration); |
||
18 | } |
||
19 | |||
20 | // Normalize numerically indexed array |
||
21 | if (array_keys($declaration) === array_keys(array_values($declaration))) { |
||
22 | return $this->normalizeArray($declaration); |
||
23 | } |
||
24 | |||
25 | View Code Duplication | if (isset($declaration['arguments']) && !is_array($declaration['arguments'])) { |
|
26 | throw new \InvalidArgumentException('The "arguments" parameter should be an array of arguments.'); |
||
27 | } |
||
28 | |||
29 | // Adds default value to associative array |
||
30 | return array_merge(['method' => null, 'required' => true, 'arguments' => []], $declaration); |
||
31 | } |
||
32 | |||
33 | private function normalizeString($declaration) |
||
34 | { |
||
35 | $service = $declaration; |
||
36 | $method = null; |
||
37 | |||
38 | View Code Duplication | if (strpos($declaration, ':') !== false) { |
|
39 | list($service, $method) = explode(':', $declaration); |
||
40 | } |
||
41 | |||
42 | return [ |
||
43 | 'service' => $service, |
||
44 | 'method' => $method, |
||
45 | 'arguments' => [], |
||
46 | 'required' => true, |
||
47 | ]; |
||
48 | } |
||
49 | |||
50 | private function normalizeArray($declaration) |
||
70 | } |
||
71 |
This check looks for the generic type
array
as a return type and suggests a more specific type. This type is inferred from the actual code.