|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Guillermoandrae\Common; |
|
4
|
|
|
|
|
5
|
|
|
final class Collection extends AbstractAggregate implements CollectionInterface |
|
6
|
|
|
{ |
|
7
|
1 |
|
public static function make(array $items = []): CollectionInterface |
|
8
|
|
|
{ |
|
9
|
1 |
|
return new static($items); |
|
10
|
|
|
} |
|
11
|
|
|
|
|
12
|
3 |
|
public function all(): array |
|
13
|
|
|
{ |
|
14
|
3 |
|
return $this->items; |
|
15
|
|
|
} |
|
16
|
|
|
|
|
17
|
2 |
|
public function first() |
|
18
|
|
|
{ |
|
19
|
2 |
|
return $this->items[0]; |
|
20
|
|
|
} |
|
21
|
|
|
|
|
22
|
2 |
|
public function last() |
|
23
|
|
|
{ |
|
24
|
2 |
|
$array = array_reverse($this->items); |
|
25
|
2 |
|
return $array[0]; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
1 |
|
public function random() |
|
29
|
|
|
{ |
|
30
|
1 |
|
$key = array_rand($this->items); |
|
31
|
1 |
|
return $this->get($key); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
1 |
|
public function sortBy(string $fieldName): CollectionInterface |
|
35
|
|
|
{ |
|
36
|
1 |
|
$results = $this->items; |
|
37
|
|
|
usort($results, function ($item1, $item2) use ($fieldName) { |
|
38
|
1 |
|
return $item1[$fieldName] <=> $item2[$fieldName]; |
|
39
|
1 |
|
}); |
|
40
|
1 |
|
return new static($results); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
2 |
|
public function count(): int |
|
44
|
|
|
{ |
|
45
|
2 |
|
return count($this->items); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
2 |
|
public function isEmpty(): bool |
|
49
|
|
|
{ |
|
50
|
2 |
|
return empty($this->items); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
1 |
|
public function shuffle(): CollectionInterface |
|
54
|
|
|
{ |
|
55
|
1 |
|
$items = $this->items; |
|
56
|
1 |
|
shuffle($items); |
|
57
|
1 |
|
return new static($items); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
1 |
|
public function limit(int $offset = 0, int $limit = null): CollectionInterface |
|
61
|
|
|
{ |
|
62
|
1 |
|
return new static(array_slice($this->items, $offset, $limit)); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
1 |
|
public function filter(callable $callback): CollectionInterface |
|
66
|
|
|
{ |
|
67
|
1 |
|
return new static(array_filter($this->items, $callback)); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
1 |
|
public function map(callable $callback): CollectionInterface |
|
71
|
|
|
{ |
|
72
|
1 |
|
return new static(array_map($callback, $this->items)); |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
2 |
|
public function toArray(): array |
|
76
|
|
|
{ |
|
77
|
|
|
return array_map(function ($value) { |
|
78
|
2 |
|
return $value instanceof ArrayableInterface ? $value->toArray() : $value; |
|
79
|
2 |
|
}, $this->items); |
|
80
|
|
|
} |
|
81
|
|
|
|
|
82
|
1 |
|
public function toJson(): string |
|
83
|
|
|
{ |
|
84
|
1 |
|
return json_encode($this->toArray()); |
|
85
|
|
|
} |
|
86
|
|
|
|
|
87
|
1 |
|
public function __toString(): string |
|
88
|
|
|
{ |
|
89
|
1 |
|
return $this->toJson(); |
|
90
|
|
|
} |
|
91
|
|
|
} |
|
92
|
|
|
|