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 |
||
7 | class YouTubeProvider extends AbstractOembedProvider implements ProviderInterface |
||
8 | { |
||
9 | const URL_OEMBED = 'http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=%s&format=json'; |
||
10 | const URL_IMAGE_MAX_RES = 'https://i.ytimg.com/vi/%s/maxresdefault.jpg'; |
||
11 | const URL_IMAGE_HQ = 'https://i.ytimg.com/vi/%s/hqdefault.jpg'; |
||
12 | |||
13 | /** |
||
14 | * @param string $id |
||
15 | * @return string |
||
16 | */ |
||
17 | 2 | public function getOembedUrl($id) |
|
21 | |||
22 | /** |
||
23 | * @param string $id |
||
24 | * @return string |
||
25 | */ |
||
26 | 1 | public function getImageUrl($id) |
|
36 | |||
37 | /** |
||
38 | * @param $value |
||
39 | * @return string |
||
40 | * @throws \Exception |
||
41 | */ |
||
42 | 6 | public function parseProviderReference($value) |
|
43 | { |
||
44 | 6 | View Code Duplication | if (strpos($value, 'youtube.com')) { |
|
|||
45 | 4 | $url = parse_url($value); |
|
46 | 4 | if (empty($url['query'])) { |
|
47 | 1 | throw new InvalidProviderUrlException('Youtube'); |
|
48 | } |
||
49 | 3 | parse_str($url['query'], $params); |
|
50 | 3 | if (empty($params['v'])) { |
|
51 | 1 | throw new InvalidProviderUrlException('Youtube'); |
|
52 | } |
||
53 | |||
54 | 2 | return $params['v']; |
|
55 | } |
||
56 | |||
57 | 4 | View Code Duplication | if (strpos($value, 'youtu.be')) { |
58 | 2 | $url = parse_url($value); |
|
59 | 2 | if (empty($url['path']) || empty(trim($url['path'], '/'))) { |
|
60 | 1 | throw new InvalidProviderUrlException('Youtube'); |
|
61 | } |
||
62 | 1 | $id = trim($url['path'], '/'); |
|
63 | |||
64 | 1 | return $id; |
|
65 | } |
||
66 | |||
67 | 3 | return $value; |
|
68 | } |
||
69 | |||
70 | /** |
||
71 | * @return string |
||
72 | */ |
||
73 | 12 | public function getIcon() |
|
77 | |||
78 | /** |
||
79 | * @return string |
||
80 | */ |
||
81 | 13 | public function getName() |
|
85 | |||
86 | /** |
||
87 | * @return string |
||
88 | */ |
||
89 | 2 | public function getType() |
|
93 | |||
94 | /** |
||
95 | * @return string |
||
96 | */ |
||
97 | 1 | public function getEmbedTemplate() |
|
101 | } |
||
102 |
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.