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 |
||
26 | class FindCompression implements BuilderAwareInterface, LoggerAwareInterface, FileModifierInterface |
||
27 | { |
||
28 | use ProcessTrait; |
||
29 | use OptionalLoggerTrait; |
||
30 | |||
31 | /** |
||
32 | * @var CompressionFactory |
||
33 | */ |
||
34 | private $factory; |
||
35 | |||
36 | /** |
||
37 | * FindCompression constructor. |
||
38 | * |
||
39 | * @param CompressionFactory $factory |
||
40 | */ |
||
41 | 8 | public function __construct(CompressionFactory $factory) |
|
45 | |||
46 | /** |
||
47 | * Find the compression of a file |
||
48 | * |
||
49 | * @param LocalFileNodeInterface $file |
||
50 | * |
||
51 | * @return string |
||
52 | */ |
||
53 | 6 | public function getCompression(LocalFileNodeInterface $file) |
|
54 | { |
||
55 | 6 | $cmd = "file --brief --uncompress --mime {$file->getPath()}"; |
|
56 | |||
57 | 6 | $process = $this->getProcess($cmd); |
|
58 | 6 | $process->mustRun(); |
|
59 | |||
60 | 5 | $result = $process->getOutput(); |
|
61 | 5 | if (preg_match('/compressed-encoding=application\/(?:x-)?(.+?);/i', $result, $matches)) { |
|
62 | 4 | if ($this->factory->isCompression($matches[1])) { |
|
63 | 3 | $this->log(LogLevel::DEBUG, "Found the compression for '{file}' as '{compression}'", [ |
|
64 | 3 | 'file' => $file, |
|
65 | 3 | 'compression' => $matches[1], |
|
66 | ]); |
||
67 | 3 | return $matches[1]; |
|
68 | } |
||
69 | 1 | return CompressionFactory::TYPE_UNKNOWN; |
|
70 | } |
||
71 | 1 | return CompressionFactory::TYPE_NONE; |
|
72 | } |
||
73 | |||
74 | /** |
||
75 | * Can this file be modified by this modifier |
||
76 | * |
||
77 | * @param FileNodeInterface $file |
||
78 | * |
||
79 | * @return bool |
||
80 | */ |
||
81 | 3 | public function canModify(FileNodeInterface $file) |
|
86 | |||
87 | /** |
||
88 | * Modify the file |
||
89 | * |
||
90 | * @param FileNodeInterface $file |
||
91 | * @param array $options |
||
92 | * |
||
93 | * @return FileNodeInterface |
||
94 | */ |
||
95 | 2 | View Code Duplication | public function modify(FileNodeInterface $file, array $options = []) |
105 | } |
||
106 |
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.