| 1 | <?php /** @noinspection PhpVariableVariableInspection */ |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace Improved; |
||
| 6 | |||
| 7 | /** |
||
| 8 | * Project each element of an iterator to an associated (or numeric) array. |
||
| 9 | * |
||
| 10 | * @param iterable $iterable |
||
| 11 | * @param array $mapping |
||
| 12 | * @return \Generator |
||
| 13 | */ |
||
| 14 | 12 | function iterable_project(iterable $iterable, array $mapping): \Generator |
|
|
0 ignored issues
–
show
introduced
by
Loading history...
|
|||
| 15 | { |
||
| 16 | 11 | foreach ($iterable as $key => $value) { |
|
| 17 | 10 | $projected = []; |
|
| 18 | |||
| 19 | 10 | if (is_array($value) || $value instanceof \ArrayAccess) { |
|
| 20 | 7 | foreach ($mapping as $to => $from) { |
|
| 21 | 7 | $projected[$to] = $value[$from] ?? null; |
|
| 22 | } |
||
| 23 | 7 | } elseif (is_object($value) && !$value instanceof \DateTimeInterface) { |
|
| 24 | 7 | foreach ($mapping as $to => $from) { |
|
| 25 | 7 | $projected[$to] = $value->$from ?? null; |
|
| 26 | } |
||
| 27 | } else { |
||
| 28 | 1 | $projected = array_fill_keys(array_keys($mapping), null); |
|
| 29 | } |
||
| 30 | |||
| 31 | 10 | yield $key => $projected; |
|
| 32 | } |
||
| 33 | } |
||
| 34 |