iterable_project()   B
last analyzed

Complexity

Conditions 8
Paths 4

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 8

Importance

Changes 0
Metric Value
cc 8
eloc 11
nc 4
nop 2
dl 0
loc 18
rs 8.4444
c 0
b 0
f 0
ccs 11
cts 11
cp 1
crap 8
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
Function Improved\iterable_project() has parameter $iterable with no value type specified in iterable type iterable.
Loading history...
introduced by
Function Improved\iterable_project() has parameter $mapping with no value type specified in iterable type array.
Loading history...
introduced by
Function Improved\iterable_project() return type has no value type specified in iterable type Generator.
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