1 | <?php /** @noinspection PhpVariableVariableInspection */ |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace Improved; |
||
6 | |||
7 | /** |
||
8 | * Reshape each element of an iterator, adding or removing properties or keys. |
||
9 | * |
||
10 | * @param iterable $iterable |
||
11 | * @param array $columns Columns to show or hide |
||
12 | * @return \Generator |
||
13 | */ |
||
14 | 13 | function iterable_reshape(iterable $iterable, array $columns): \Generator |
|
0 ignored issues
–
show
introduced
by
![]() |
|||
15 | { |
||
16 | 12 | $change = array_filter($columns, function ($keep) { |
|
0 ignored issues
–
show
|
|||
17 | 12 | return !is_bool($keep); |
|
18 | 12 | }); |
|
19 | |||
20 | 12 | $remove = array_fill_keys(array_diff(array_keys(array_filter($columns, function ($keep) { |
|
0 ignored issues
–
show
|
|||
21 | 12 | return $keep !== true; |
|
22 | 12 | })), array_values($columns)), null); |
|
23 | |||
24 | 12 | $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 | 12 | $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 | } |
||
59 | } |
||
60 |