1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Equip; |
4
|
|
|
|
5
|
|
|
use function Equip\Arr\to_array; |
6
|
|
|
|
7
|
|
|
class Chain |
8
|
|
|
{ |
9
|
12 |
|
public static function from($source) |
10
|
|
|
{ |
11
|
12 |
|
return new static(to_array($source)); |
12
|
|
|
} |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* @var array |
16
|
|
|
*/ |
17
|
|
|
private $source; |
18
|
|
|
|
19
|
12 |
|
public function __construct(array $source) |
20
|
|
|
{ |
21
|
12 |
|
$this->source = $source; |
22
|
12 |
|
} |
23
|
|
|
|
24
|
9 |
|
public function toArray() |
25
|
|
|
{ |
26
|
9 |
|
return $this->source; |
27
|
|
|
} |
28
|
|
|
|
29
|
1 |
|
public function hasKey($needle) |
30
|
|
|
{ |
31
|
1 |
|
return array_key_exists($needle, $this->source); |
32
|
|
|
} |
33
|
|
|
|
34
|
1 |
|
public function hasValue($needle) |
35
|
|
|
{ |
36
|
1 |
|
return in_array($needle, $this->source); |
37
|
|
|
} |
38
|
|
|
|
39
|
1 |
|
public function values() |
40
|
|
|
{ |
41
|
1 |
|
$copy = clone $this; |
42
|
1 |
|
$copy->source = array_values($this->source); |
43
|
|
|
|
44
|
1 |
|
return $copy; |
45
|
|
|
} |
46
|
|
|
|
47
|
1 |
|
public function keys() |
48
|
|
|
{ |
49
|
1 |
|
$copy = clone $this; |
50
|
1 |
|
$copy->source = array_keys($this->source); |
51
|
|
|
|
52
|
1 |
|
return $copy; |
53
|
|
|
} |
54
|
|
|
|
55
|
1 |
|
public function merge(array $values) |
56
|
|
|
{ |
57
|
1 |
|
$copy = clone $this; |
58
|
1 |
|
$copy->source = array_merge($this->source, $values); |
59
|
|
|
|
60
|
1 |
|
return $copy; |
61
|
|
|
} |
62
|
|
|
|
63
|
1 |
|
public function intersect(array $values) |
64
|
|
|
{ |
65
|
1 |
|
$copy = clone $this; |
66
|
1 |
|
$copy->source = array_intersect($this->source, $values); |
67
|
|
|
|
68
|
1 |
|
return $copy; |
69
|
|
|
} |
70
|
|
|
|
71
|
1 |
|
public function diff(array $values) |
72
|
|
|
{ |
73
|
1 |
|
$copy = clone $this; |
74
|
1 |
|
$copy->source = array_diff($this->source, $values); |
75
|
|
|
|
76
|
1 |
|
return $copy; |
77
|
|
|
} |
78
|
|
|
|
79
|
1 |
|
public function unique() |
80
|
|
|
{ |
81
|
1 |
|
$copy = clone $this; |
82
|
1 |
|
$copy->source = array_unique($this->source); |
83
|
|
|
|
84
|
1 |
|
return $copy; |
85
|
|
|
} |
86
|
|
|
|
87
|
1 |
|
public function reduce(callable $fn, $initial = null) |
88
|
|
|
{ |
89
|
1 |
|
return array_reduce($this->source, $fn, $initial); |
90
|
|
|
} |
91
|
|
|
|
92
|
1 |
|
public function filter(callable $fn) |
93
|
|
|
{ |
94
|
1 |
|
$copy = clone $this; |
95
|
1 |
|
$copy->source = array_filter($this->source, $fn); |
96
|
|
|
|
97
|
1 |
|
return $copy; |
98
|
|
|
} |
99
|
|
|
|
100
|
1 |
|
public function map(callable $fn) |
101
|
|
|
{ |
102
|
1 |
|
$copy = clone $this; |
103
|
1 |
|
$copy->source = array_map($fn, $this->source); |
104
|
|
|
|
105
|
1 |
|
return $copy; |
106
|
|
|
} |
107
|
|
|
} |
108
|
|
|
|