Test Setup Failed
Pull Request — master (#10)
by Luke
13:21
created

functions.php ➔ collect()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 4
ccs 0
cts 0
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * nozavroni/collect
4
 *
5
 * This is a basic utility library for PHP5.6+ with special emphesis on Collections.
6
 *
7
 * @author Luke Visinoni <[email protected]>
8
 * @copyright (c) 2018 Luke Visinoni <[email protected]>
9
 * @license MIT (see LICENSE file)
10
 */
11
namespace Noz;
12
13
use Noz\Collection\Collection;
14
use RuntimeException;
15
use Traversable;
16 13
17
/**
18
 * Is a value traversable?
19
 *
20
 * @param mixed $value
21
 *
22
 * @return bool
23
 */
24
function is_traversable($value)
25
{
26
    return is_array($value) || ($value instanceof Traversable);
27
}
28
29
/**
30 37
 * Convert $items to an array
31 3
 *
32 36
 * @param mixed $items The var to convert to an array
33 32
 * @param bool $force Force item to array no matter what?
34 5
 *
35 2
 * @throws RuntimeException if cannot be converted to an array
36 4
 *
37 3
 * @return array
38 3
 */
39 2
function to_array($items, $force = false)
40
{
41 1
    if (method_exists($items, 'toArray')) {
42
        return $items->toArray();
43 2
    } elseif (is_array($items)) {
44 1
        return $items;
45
    } elseif ($items instanceof Traversable) {
46
        return iterator_to_array($items);
47 1
    } elseif (is_string($items)) {
48
        $json = json_decode($items, true);
49
        if (is_array($json) && json_last_error() == JSON_ERROR_NONE) {
50
            return $json;
51
        }
52
    }
53
54
    if ($force) {
55
        return (array) $items;
56
    }
57
58
    throw new RuntimeException(__FUNCTION__ . " could not convert items to an array");
59
}
60
61
/**
62
 * Collection factory function
63
 *
64
 * @param array|Traversable $items
65
 *
66
 * @return Collection
67
 */
68
function collect($items)
69
{
70
    return Collection::factory($items);
71
}
72
73
/**
74
 * Assign a value to a variable if a condition is met
75
 *
76
 * @param mixed $var
77
 * @param mixed $value
78
 * @param bool|callable $condition
79
 *
80
 * @return bool
81
 */
82
function assign_if(&$var, $value, $condition)
83
{
84
    if (is_callable($condition)) {
85
        $condition = $condition($value);
86
    }
87
    if ($condition) {
88
        $var = $value;
89
    }
90
}
91
92