Passed
Push — master ( 43d099...5c74fa )
by Arnold
02:29
created

iterable_reshape()   C

Complexity

Conditions 13
Paths 4

Size

Total Lines 44
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 13

Importance

Changes 0
Metric Value
cc 13
eloc 24
nc 4
nop 2
dl 0
loc 44
ccs 23
cts 23
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
2
3
declare(strict_types=1);
4
5
namespace Jasny;
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
function iterable_reshape(iterable $iterable, array $columns): \Generator
15
{
16
    $change = array_filter($columns, function ($keep) {
17 12
        return !is_bool($keep);
18 12
    });
19
20
    $remove = array_fill_keys(array_diff(array_keys(array_filter($columns, function ($keep) {
21 12
        return $keep !== true;
22 12
    })), array_values($columns)), null);
23
24
    $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
    $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