Failed Conditions
Push — master ( ace980...e1d93b )
by Arnold
05:21
created

iterable_column()   C

Complexity

Conditions 13
Paths 13

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 182

Importance

Changes 0
Metric Value
cc 13
eloc 11
nc 13
nop 3
dl 0
loc 15
ccs 0
cts 10
cp 0
crap 182
rs 6.6166
c 0
b 0
f 0

How to fix   Complexity   

Long Method

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:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Jasny;
6
7
/**
8
 * Get a key and/or value of each element of the iterable.
9
 *
10
 * The elements need to be objects or arrays.
11
 * For scalar elements or if the property/index doesn't exist, the value and/or key will be null.
12
 *
13
 * @param iterable $iterable
14
 * @param mixed|null $valueColumn  Value property/index, null for complete value
15
 * @param mixed|null $keyColumn    Key property/index, null to keep current keys
16
 * @return \Generator
17
 */
18
function iterable_column(iterable $iterable, $valueColumn, $keyColumn = null): \Generator
19
{
20
    foreach ($iterable as $key => $value) {
21
        if (is_array($value) || (is_object($value) && $value instanceof \ArrayAccess)) {
22
            $key = isset($keyColumn) ? ($value[$keyColumn] ?? null) : $key;
23
            $value = isset($valueColumn) ? ($value[$valueColumn] ?? null) : $value;
24
        } elseif (is_object($value) && !$value instanceof \DateTimeInterface) {
25
            $key = isset($keyColumn) ? ($value->$keyColumn ?? null) : $key;
26
            $value = isset($valueColumn) ? ($value->$valueColumn ?? null) : $value;
27
        } else {
28
            $key = isset($keyColumn) ? null : $key;
29
            $value = isset($valueColumn) ? null : $value;
30
        }
31
32
        yield $key => $value;
33
    }
34
}
35