Completed
Push — master ( e4da97...0d3405 )
by Luke
06:48 queued 01:32
created

functions.php ➔ to_array()   B

Complexity

Conditions 8
Paths 8

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 8

Importance

Changes 0
Metric Value
cc 8
eloc 14
nc 8
nop 2
dl 0
loc 21
ccs 14
cts 14
cp 1
crap 8
rs 7.1428
c 0
b 0
f 0
1
<?php
2
namespace Noz;
3
4
use RuntimeException;
5
use Traversable;
6
7
/**
8
 * Is a value traversable?
9
 *
10
 * @param mixed $value
11
 *
12
 * @return bool
13
 */
14
function is_traversable($value)
15
{
16 13
    return is_array($value) || ($value instanceof Traversable);
17
}
18
19
/**
20
 * Convert $items to an array
21
 *
22
 * @param mixed $items
23
 *
24
 * @throws RuntimeException if cannot be converted to an array
25
 *
26
 * @return array
27
 */
28
function to_array($items, $force = false)
29
{
30 10
    if (method_exists($items, 'toArray')) {
31 2
        return $items->toArray();
32 8
    } elseif (is_array($items)) {
33 4
        return $items;
34 4
    } elseif ($items instanceof Traversable) {
35 1
        return iterator_to_array($items);
36 3
    } elseif (is_string($items)) {
37 2
        $json = json_decode($items, true);
38 2
        if (is_array($json) && json_last_error() == JSON_ERROR_NONE) {
39 1
            return $json;
40
        }
41 1
    }
42
43 2
    if ($force) {
44 1
        return (array) $items;
45
    }
46
47
    throw new RuntimeException(__FUNCTION__ . " could not convert items to an array");
48
}