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 |
||
27 | class FindEncoding implements BuilderAwareInterface, LoggerAwareInterface, FileModifierInterface |
||
28 | { |
||
29 | use ProcessTrait; |
||
30 | use OptionalLoggerTrait; |
||
31 | |||
32 | /** |
||
33 | * Find the Encoding of a specified file |
||
34 | * |
||
35 | * @param LocalFileNodeInterface $file |
||
36 | * |
||
37 | * @return null|string |
||
38 | * @throws ProcessFailedException |
||
39 | */ |
||
40 | 6 | public function getEncoding(LocalFileNodeInterface $file) |
|
41 | { |
||
42 | 6 | $cmd = "file --brief --uncompress --mime {$file->getPath()}"; |
|
43 | |||
44 | 6 | $process = $this->getProcess($cmd); |
|
45 | 6 | $process->mustRun(); |
|
46 | |||
47 | 5 | $result = $process->getOutput(); |
|
48 | 5 | if (preg_match('/charset=([^\s]+)/i', $result, $matches)) { |
|
49 | 4 | $this->log(LogLevel::DEBUG, "Found the encoding for '{file}' as '{encoding}'", [ |
|
50 | 4 | 'file' => $file, |
|
51 | 4 | 'encoding' => $matches[1], |
|
52 | ]); |
||
53 | 4 | return $matches[1]; |
|
54 | } |
||
55 | 1 | return null; |
|
56 | } |
||
57 | |||
58 | /** |
||
59 | * Can this file be modified by this modifier |
||
60 | * |
||
61 | * @param FileNodeInterface $file |
||
62 | * |
||
63 | * @return bool |
||
64 | */ |
||
65 | 3 | public function canModify(FileNodeInterface $file) |
|
70 | |||
71 | /** |
||
72 | * Modify the file |
||
73 | * |
||
74 | * @param FileNodeInterface $file |
||
75 | * @param array $options |
||
76 | * |
||
77 | * @return FileNodeInterface |
||
78 | * @throws InvalidArgumentException |
||
79 | */ |
||
80 | 2 | View Code Duplication | public function modify(FileNodeInterface $file, array $options = []) |
92 | } |
||
93 |
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.