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
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Is a value traversable? |
19
|
|
|
* |
20
|
|
|
* @param mixed $value |
21
|
|
|
* |
22
|
|
|
* @return bool |
23
|
|
|
*/ |
24
|
|
|
function is_traversable($value) |
25
|
|
|
{ |
26
|
14 |
|
return is_array($value) || ($value instanceof Traversable); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Convert $items to an array |
31
|
|
|
* |
32
|
|
|
* @param mixed $items The var to convert to an array |
33
|
|
|
* @param bool $force Force item to array no matter what? |
34
|
|
|
* |
35
|
|
|
* @throws RuntimeException if cannot be converted to an array |
36
|
|
|
* |
37
|
|
|
* @return array |
38
|
|
|
*/ |
39
|
|
|
function to_array($items, $force = false) |
40
|
|
|
{ |
41
|
45 |
|
if (method_exists($items, 'toArray')) { |
42
|
3 |
|
return $items->toArray(); |
43
|
44 |
|
} elseif (is_array($items)) { |
44
|
40 |
|
return $items; |
45
|
5 |
|
} elseif ($items instanceof Traversable) { |
46
|
2 |
|
return iterator_to_array($items); |
47
|
4 |
|
} elseif (is_string($items)) { |
48
|
3 |
|
$json = json_decode($items, true); |
49
|
3 |
|
if (is_array($json) && json_last_error() == JSON_ERROR_NONE) { |
50
|
2 |
|
return $json; |
51
|
|
|
} |
52
|
1 |
|
} |
53
|
|
|
|
54
|
2 |
|
if ($force) { |
55
|
1 |
|
return (array) $items; |
56
|
|
|
} |
57
|
|
|
|
58
|
1 |
|
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
|
1 |
|
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
|
5 |
|
if (is_callable($condition)) { |
85
|
2 |
|
$condition = $condition($value); |
86
|
2 |
|
} |
87
|
5 |
|
if ($condition) { |
88
|
4 |
|
$var = $value; |
89
|
4 |
|
} |
90
|
5 |
|
} |
91
|
|
|
|
92
|
|
|
|