Conditions | 16 |
Paths | 45 |
Total Lines | 59 |
Code Lines | 37 |
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 /** @noinspection PhpVariableVariableInspection */ |
||
17 | function iterable_unwind(iterable $iterable, $column, $mapKey = null, bool $preserveKeys = false): \Generator |
||
18 | { |
||
19 | $counter = 0; |
||
20 | |||
21 | $setArray = function ($element, $value, $key) use ($column, $mapKey) { |
||
22 | return array_merge($element, [$column => $value], $mapKey === null ? [] : [$mapKey => $key]); |
||
23 | }; |
||
24 | |||
25 | $setArrayAccess = function ($element, $value, $key) use ($column, $mapKey) { |
||
26 | $copy = clone $element; |
||
27 | |||
28 | $copy[$column] = $value; |
||
29 | if ($mapKey !== null) { |
||
30 | $copy[$mapKey] = $key; |
||
31 | } |
||
32 | |||
33 | return $copy; |
||
34 | }; |
||
35 | |||
36 | $setObject = function ($element, $value, $key) use ($column, $mapKey) { |
||
37 | $copy = clone $element; |
||
38 | |||
39 | $copy->$column = $value; |
||
|
|||
40 | if ($mapKey !== null) { |
||
41 | $copy->$mapKey = $key; |
||
42 | } |
||
43 | |||
44 | return $copy; |
||
45 | }; |
||
46 | |||
47 | foreach ($iterable as $topKey => $element) { |
||
48 | $set = null; |
||
49 | $iterated = false; |
||
50 | |||
51 | if (is_array($element)) { |
||
52 | $value = $element[$column] ?? null; |
||
53 | $set = $setArray; |
||
54 | } elseif ($element instanceof \ArrayAccess) { |
||
55 | $value = $element[$column] ?? null; |
||
56 | $set = $setArrayAccess; |
||
57 | } elseif (is_object($element) && !$element instanceof \DateTimeInterface) { |
||
58 | $value = $element->$column ?? null; |
||
59 | $set = $setObject; |
||
60 | } else { |
||
61 | $value = null; |
||
62 | } |
||
63 | |||
64 | if (!is_iterable($value) || $set === null) { |
||
65 | yield ($preserveKeys ? $topKey : $counter++) => $element; |
||
66 | continue; |
||
67 | } |
||
68 | |||
69 | foreach ($value as $key => $item) { |
||
70 | $iterated = true; |
||
71 | yield ($preserveKeys ? $topKey : $counter++) => $set($element, $item, $key); |
||
72 | } |
||
73 | |||
74 | if (!$iterated) { |
||
75 | yield ($preserveKeys ? $topKey : $counter++) => $set($element, null, null); |
||
76 | } |
||
79 |