Conditions | 13 |
Paths | 4 |
Total Lines | 44 |
Code Lines | 24 |
Lines | 0 |
Ratio | 0 % |
Tests | 23 |
CRAP Score | 13 |
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 |
||
14 | function iterable_reshape(iterable $iterable, array $columns): \Generator |
||
15 | { |
||
16 | $change = array_filter($columns, function ($keep) { |
||
17 | 12 | return !is_bool($keep); |
|
18 | 12 | }); |
|
19 | |||
20 | $remove = array_fill_keys(array_diff(array_keys(array_filter($columns, function ($keep) { |
||
21 | 12 | return $keep !== true; |
|
22 | 12 | })), array_values($columns)), null); |
|
23 | |||
24 | $shapeArray = function (&$value) use ($change, $remove): void { |
||
25 | 7 | foreach ($change as $from => $to) { |
|
26 | 7 | if (isset($value[$from])) { |
|
27 | 7 | $value[$to] = $value[$from]; |
|
28 | } |
||
29 | } |
||
30 | |||
31 | 7 | foreach ($remove as $key => $null) { |
|
32 | 7 | if (isset($value[$key])) { |
|
33 | 7 | unset($value[$key]); |
|
34 | } |
||
35 | } |
||
36 | 12 | }; |
|
37 | |||
38 | $shapeObject = function ($value) use ($change, $remove): void { |
||
39 | 8 | foreach ($change as $from => $to) { |
|
40 | 8 | if (isset($value->$from)) { |
|
41 | 8 | $value->$to = $value->$from; |
|
42 | } |
||
43 | } |
||
44 | |||
45 | 8 | foreach ($remove as $key => $null) { |
|
46 | 8 | unset($value->$key); |
|
47 | } |
||
48 | 12 | }; |
|
49 | |||
50 | 12 | foreach ($iterable as $key => $value) { |
|
51 | 11 | if (is_array($value) || $value instanceof \ArrayAccess) { |
|
52 | 7 | $shapeArray($value); |
|
53 | 8 | } elseif (is_object($value) && !$value instanceof \DateTimeInterface) { |
|
54 | 8 | $shapeObject($value); |
|
55 | } |
||
56 | |||
57 | 11 | yield $key => $value; |
|
58 | } |
||
60 |