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 |
||
21 | final class Uri |
||
22 | { |
||
23 | /** |
||
24 | * Parses a URI. |
||
25 | * |
||
26 | * The returned array contains the following keys: |
||
27 | * |
||
28 | * * "scheme": The scheme part before the "://"; |
||
29 | * * "path": The path part after the "://". |
||
30 | * |
||
31 | * The URI must fulfill a few constraints: |
||
32 | * |
||
33 | * * the scheme must consist of alphabetic characters only; |
||
34 | * * the scheme may be omitted. Then "://" must be omitted too; |
||
35 | * * the path must not be empty; |
||
36 | * * the path must start with a forward slash ("/"). |
||
37 | * |
||
38 | * If any of these constraints is not fulfilled, an |
||
39 | * {@link InvalidUriException} is thrown. |
||
40 | * |
||
41 | * @param string $uri A URI string. |
||
42 | * |
||
43 | * @return string[] The parts of the URI. |
||
44 | * |
||
45 | * @throws InvalidUriException If the URI is invalid. |
||
46 | */ |
||
47 | 42 | public static function parse($uri) |
|
48 | { |
||
49 | 42 | View Code Duplication | if (!is_string($uri)) { |
50 | 3 | throw new InvalidUriException(sprintf( |
|
51 | 3 | 'The URI must be a string, but is a %s.', |
|
52 | 3 | is_object($uri) ? get_class($uri) : gettype($uri) |
|
53 | )); |
||
54 | } |
||
55 | |||
56 | 39 | if (false !== ($pos = strpos($uri, '://'))) { |
|
57 | 35 | $parts = array(substr($uri, 0, $pos), substr($uri, $pos + 3)); |
|
58 | |||
59 | 35 | if (!ctype_alnum($parts[0])) { |
|
60 | 3 | throw new InvalidUriException(sprintf( |
|
61 | 'The URI "%s" is invalid. The scheme should consist of '. |
||
62 | 3 | 'alphabetic characters only.', |
|
63 | $uri |
||
64 | )); |
||
65 | } |
||
66 | |||
67 | 32 | View Code Duplication | if (!ctype_alpha($parts[0][0])) { |
68 | 1 | throw new InvalidUriException(sprintf( |
|
69 | 32 | 'The URI "%s" is invalid. The scheme should start with a letter.', |
|
70 | $uri |
||
71 | )); |
||
72 | } |
||
73 | } else { |
||
74 | 4 | $parts = array('', $uri); |
|
75 | } |
||
76 | |||
77 | 35 | if ('' === $parts[1]) { |
|
78 | 1 | throw new InvalidUriException(sprintf( |
|
79 | 1 | 'The URI "%s" is invalid. The path should not be empty.', |
|
80 | $uri |
||
81 | )); |
||
82 | } |
||
83 | |||
84 | 34 | View Code Duplication | if ('/' !== $parts[1][0]) { |
85 | 2 | throw new InvalidUriException(sprintf( |
|
86 | 'The URI "%s" is invalid. The path should start with a '. |
||
87 | 2 | 'forward slash ("/").', |
|
88 | $uri |
||
89 | )); |
||
90 | } |
||
91 | |||
92 | return array( |
||
93 | 32 | 'scheme' => $parts[0], |
|
94 | 32 | 'path' => $parts[1], |
|
95 | ); |
||
96 | } |
||
97 | |||
98 | private function __construct() |
||
101 | } |
||
102 |