-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCollection.php
More file actions
107 lines (84 loc) · 2 KB
/
Collection.php
File metadata and controls
107 lines (84 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<?php
/**
* Class Collection
*/
class Collection
{
/** @var callable[] */
protected $stack = [];
/** @var Traversable */
protected $collection;
/**
* Collection constructor.
*
* @param array $collection
*/
function __construct($collection = [])
{
$this->collection = $collection;
}
function map($callable)
{
$this->stack[] = function ($t) use ($callable) {
foreach ($t as $k => $v) {
yield $k => $callable($v);
}
};
return $this;
}
function items()
{
$this->stack[] = function ($t) {
foreach ($t as $k => $v) {
yield [$k, $v];
}
};
return $this;
}
function filter($callable)
{
$this->stack[] = function ($t) use ($callable) {
foreach ($t as $k => $v) {
if ($callable($v)) {
yield $k => $v;
}
}
};
return $this;
}
function reduce($initialValue, $callable)
{
$this->stack[] = function ($t) use ($initialValue, $callable) {
$accumulator = $initialValue;
foreach ($t as $k => $v) {
$accumulator = $callable($accumulator, $v);
}
return $accumulator;
};
return $this;
}
function unique()
{
$this->stack[] = function ($t) {
$seen = [];
foreach ($t as $k => $v) {
if ( ! in_array($v, $seen, true)) {
$seen[] = $v;
yield $k => $v;
}
}
};
return $this;
}
/**
* @return array
*/
function get()
{
$collection = $this->collection;
foreach ($this->stack as $callable) {
$collection = $callable($collection);
}
return is_array($collection) ? $collection : iterator_to_array($collection, false);
}
}