Conditions | 13 |
Paths | 16 |
Total Lines | 60 |
Code Lines | 28 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | <?php |
||
30 | public function addArrayAsChildren(array $array, SimpleXMLElement $xmlElement, $ignoreEmptyElements = true) |
||
31 | { |
||
32 | // Keep an array of children that are added to $xmlElement |
||
33 | $children = []; |
||
34 | |||
35 | // Add each element of the array as a child to $xmlElement |
||
36 | foreach ($array as $key => $value) { |
||
37 | // Ignore empty array elements |
||
38 | if ($this->isEmpty($value) && $ignoreEmptyElements) { |
||
39 | continue; |
||
40 | } |
||
41 | |||
42 | // Specifies attributes as a key/value array |
||
43 | if ($key === '@attributes') { |
||
44 | if (!is_array($value)) { |
||
45 | throw new Exception('@attributes must be an array'); |
||
46 | } |
||
47 | |||
48 | foreach ($value as $attributeName => $attributeValue) { |
||
49 | $xmlElement->addAttribute($attributeName, htmlspecialchars($attributeValue)); |
||
50 | } |
||
51 | |||
52 | continue; |
||
53 | } |
||
54 | |||
55 | // Special case to be able to set the value of an element to a string if the attribute is also being set, |
||
56 | // without this a child element would be created instead. |
||
57 | // The really hacky part is that setting the 0 key element overrides the value (it doesn't normally exist). |
||
58 | if ($key === '@value') { |
||
59 | if (!is_scalar($value)) { |
||
60 | throw new Exception('@value must be a scalar'); |
||
61 | } |
||
62 | |||
63 | $xmlElement[0] = htmlspecialchars($value); |
||
64 | continue; |
||
65 | } |
||
66 | |||
67 | // Make a recursive call if the element is an array. |
||
68 | // If the array is numeric then there are multiple of the same element. |
||
69 | if (is_array($value)) { |
||
70 | $useSubArray = key($value) === 0; |
||
71 | $subValues = $useSubArray ? $value : [$value]; |
||
72 | |||
73 | $subChildren = []; |
||
74 | foreach ($subValues as $subValue) { |
||
75 | $subChild = $xmlElement->addChild($key); |
||
76 | $this->addArrayAsChildren($subValue, $subChild, $ignoreEmptyElements); |
||
77 | $subChildren[] = $subChild; |
||
78 | } |
||
79 | |||
80 | $children[$key] = $useSubArray ? $subChildren : $subChildren[0]; |
||
81 | continue; |
||
82 | } |
||
83 | |||
84 | // Encode the value correctly |
||
85 | $value = htmlspecialchars($value); |
||
86 | $children[$key] = $xmlElement->addChild($key, $value); |
||
87 | } |
||
88 | |||
89 | return $children; |
||
|
|||
90 | } |
||
129 |