iterable_column()   C
last analyzed

Complexity

Conditions 13
Paths 13

Size

Total Lines 19
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 13

Importance

Changes 0
Metric Value
cc 13
eloc 15
nc 13
nop 3
dl 0
loc 19
ccs 14
cts 14
cp 1
crap 13
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 /** @noinspection PhpVariableVariableInspection */
2
3
declare(strict_types=1);
4
5
namespace Improved;
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 24
function iterable_column(iterable $iterable, $valueColumn, $keyColumn = null): \Generator
0 ignored issues
show
introduced by
Function Improved\iterable_column() has parameter $iterable with no value type specified in iterable type iterable.
Loading history...
introduced by
Function Improved\iterable_column() return type has no value type specified in iterable type Generator.
Loading history...
19
{
20 23
    foreach ($iterable as $key => $value) {
21
        switch (true) {
22 22
            case is_array($value) || (is_object($value) && $value instanceof \ArrayAccess):
23 15
                $key = isset($keyColumn) ? ($value[$keyColumn] ?? null) : $key;
24 15
                $value = isset($valueColumn) ? ($value[$valueColumn] ?? null) : $value;
25 15
                break;
26 15
            case is_object($value) && !$value instanceof \DateTimeInterface:
27 15
                $key = isset($keyColumn) ? ($value->$keyColumn ?? null) : $key;
28 15
                $value = isset($valueColumn) ? ($value->$valueColumn ?? null) : $value;
29 15
                break;
30
            default:
31 1
                $key = isset($keyColumn) ? null : $key;
32 1
                $value = isset($valueColumn) ? null : $value;
33 1
                break;
34
        }
35
36 22
        yield $key => $value;
37
    }
38
}
39