iterable_to_array()   B
last analyzed

Complexity

Conditions 7
Paths 8

Size

Total Lines 20
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 7

Importance

Changes 0
Metric Value
cc 7
eloc 14
c 0
b 0
f 0
nc 8
nop 2
dl 0
loc 20
ccs 12
cts 12
cp 1
crap 7
rs 8.8333
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Improved;
6
7
use Improved\IteratorPipeline\Pipeline;
8
9
/**
10
 * Convert any iterable to an array.
11
 *
12
 * @param iterable  $iterable
13
 * @param bool|null $preserveKeys  NULL means don't care
14
 * @return array
15
 */
16
function iterable_to_array(iterable $iterable, ?bool $preserveKeys = null): array
0 ignored issues
show
introduced by
Function Improved\iterable_to_array() has parameter $iterable with no value type specified in iterable type iterable.
Loading history...
introduced by
Function Improved\iterable_to_array() return type has no value type specified in iterable type array.
Loading history...
17
{
18
    switch (true) {
19 21
        case is_array($iterable):
20 3
            break;
21 18
        case !$iterable instanceof Pipeline && method_exists($iterable, 'toArray'):
22 3
            $iterable = $iterable->toArray();
23 3
            break;
24 15
        case method_exists($iterable, 'getArrayCopy'):
25
            /** @var \ArrayObject $iterable  Duck typing */
26 6
            $iterable = $iterable->getArrayCopy();
0 ignored issues
show
introduced by
PHPDoc tag @var for variable $iterable contains generic class ArrayObject but does not specify its types: TKey, TValue
Loading history...
27 6
            break;
28
29 9
        case $iterable instanceof \IteratorAggregate:
30 3
            return iterable_to_array($iterable->getIterator(), $preserveKeys); // recursion
31
        default:
32 9
            return iterator_to_array($iterable, $preserveKeys === true);
33
    }
34
35 12
    return $preserveKeys === false ? array_values($iterable) : $iterable;
36
}
37