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 |
||
18 | class Xml implements Loadable { |
||
19 | |||
20 | use Supports\Libxml; |
||
21 | |||
22 | const LIBXML_OPTIONS = 'libxml'; |
||
23 | |||
24 | /** |
||
25 | * @return string[] |
||
26 | */ |
||
27 | 12 | public function getSupported() { |
|
30 | |||
31 | /** |
||
32 | * @see Loadable::load |
||
33 | * @param string $source |
||
34 | * @param string $contentType |
||
35 | * @param array|\Traversable|Options $options |
||
36 | * @return Document|Result|NULL |
||
37 | */ |
||
38 | 6 | public function load($source, $contentType, $options = []) { |
|
39 | 6 | if ($this->supports($contentType)) { |
|
40 | 5 | return (new Libxml\Errors())->capture( |
|
41 | View Code Duplication | function() use ($source, $contentType, $options) { |
|
|
|||
42 | 5 | $document = new Document(); |
|
43 | 5 | $document->preserveWhiteSpace = FALSE; |
|
44 | 5 | $settings = $this->getOptions($options); |
|
45 | 5 | $settings->isAllowed($sourceType = $settings->getSourceType($source)); |
|
46 | switch ($sourceType) { |
||
47 | 5 | case Options::IS_FILE : |
|
48 | 2 | $document->load($source, $settings[Options::LIBXML_OPTIONS]); |
|
49 | 2 | break; |
|
50 | 3 | case Options::IS_STRING : |
|
51 | 3 | default : |
|
52 | 3 | $document->loadXML($source, $settings[Options::LIBXML_OPTIONS]); |
|
53 | 3 | } |
|
54 | 5 | return $document; |
|
55 | } |
||
56 | 5 | ); |
|
57 | } |
||
58 | 1 | return NULL; |
|
59 | } |
||
60 | |||
61 | /** |
||
62 | * @see LoadableFragment::loadFragment |
||
63 | * @param string $source |
||
64 | * @param string $contentType |
||
65 | * @param array|\Traversable|Options $options |
||
66 | * @return DocumentFragment|NULL |
||
67 | */ |
||
68 | 4 | public function loadFragment($source, $contentType, $options = []) { |
|
81 | } |
||
82 | } |
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.