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 XmlBuilder |
||
| 19 | { |
||
| 20 | /** |
||
| 21 | * static class |
||
| 22 | */ |
||
| 23 | private function __construct() {} |
||
| 24 | |||
| 25 | /** |
||
| 26 | * Creates a DOMDocument |
||
| 27 | * |
||
| 28 | * @param array $specs |
||
| 29 | * |
||
| 30 | * @return \DOMDocument |
||
| 31 | */ |
||
| 32 | 1 | public static function createDocument(array $specs) |
|
| 40 | |||
| 41 | /** |
||
| 42 | * Creates a XML string |
||
| 43 | * |
||
| 44 | * @param array $specs |
||
| 45 | * |
||
| 46 | * @return string |
||
| 47 | */ |
||
| 48 | 1 | public static function createXml(array $specs) |
|
| 53 | |||
| 54 | /** |
||
| 55 | * Builds the DOMDocument. |
||
| 56 | * |
||
| 57 | * Format of specs: |
||
| 58 | * |
||
| 59 | * |
||
| 60 | * [ |
||
| 61 | * 'node' => 'textNode', #create the node 'node' with textNode 'textNode' (=> <node>textNode</node>) |
||
| 62 | * ':node' => 'cdataNode', #create the node 'node' with CDATA (=> <node><![CDATA[cdataNode]]></node>) |
||
| 63 | * '@attr' => 'value', # adds an attribute to the node (=> <node attr="value">) |
||
| 64 | * 'node' => [ # Add multiple nodes when provide enumerated array |
||
| 65 | * [ 'subNode' => [ |
||
| 66 | * [ '@attr' => 'value', |
||
| 67 | * 'text', # Creates a textNode and append it to current node |
||
| 68 | * ], |
||
| 69 | * [ '@attr' => 'value', |
||
| 70 | * ':cdata' # Create a cdata node and append it to current node |
||
| 71 | * ] |
||
| 72 | * ], |
||
| 73 | * [ |
||
| 74 | * '@attr' => popel', |
||
| 75 | * 'subSubNode' => [ |
||
| 76 | * ] |
||
| 77 | * ], |
||
| 78 | * 'single' => [ |
||
| 79 | * 'maybe some text', |
||
| 80 | * 'child' => 'text', |
||
| 81 | * 'some more text', |
||
| 82 | * ], |
||
| 83 | * ] |
||
| 84 | * |
||
| 85 | * @param \DOMDocument|\DOMElement $node |
||
| 86 | * @param array $specs |
||
| 87 | */ |
||
| 88 | 1 | private static function build($node, array $specs) |
|
| 134 | } |
||
| 135 |
It seems like the method you are trying to call exists only in some of the possible types.
Let’s take a look at an example:
Available Fixes
Add an additional type-check:
Only allow a single type to be passed if the variable comes from a parameter: