1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Zalas\Toolbox\Tool; |
4
|
|
|
|
5
|
|
|
use Countable; |
6
|
|
|
use IteratorAggregate; |
7
|
|
|
use Traversable; |
8
|
|
|
|
9
|
|
|
class Collection implements IteratorAggregate, Countable |
10
|
|
|
{ |
11
|
|
|
private array $elements; |
12
|
|
|
|
13
|
63 |
|
private function __construct(array $elements) |
14
|
|
|
{ |
15
|
63 |
|
$this->elements = $elements; |
16
|
|
|
} |
17
|
|
|
|
18
|
63 |
|
public static function create(array $elements): Collection |
19
|
|
|
{ |
20
|
63 |
|
return new self($elements); |
21
|
|
|
} |
22
|
|
|
|
23
|
7 |
|
public function getIterator(): Traversable |
24
|
|
|
{ |
25
|
7 |
|
yield from $this->elements; |
26
|
|
|
} |
27
|
|
|
|
28
|
27 |
|
public function merge(Collection $other): Collection |
29
|
|
|
{ |
30
|
27 |
|
return self::create(\array_merge($this->elements, $other->elements)); |
31
|
|
|
} |
32
|
|
|
|
33
|
28 |
|
public function filter(callable $f): Collection |
34
|
|
|
{ |
35
|
28 |
|
return self::create(\array_values(\array_filter($this->elements, $f))); |
36
|
|
|
} |
37
|
|
|
|
38
|
21 |
|
public function map(callable $f): Collection |
39
|
|
|
{ |
40
|
21 |
|
return self::create(\array_map($f, $this->elements)); |
41
|
|
|
} |
42
|
|
|
|
43
|
9 |
|
public function reduce($initial, callable $param) |
44
|
|
|
{ |
45
|
9 |
|
return \array_reduce($this->elements, $param, $initial); |
46
|
|
|
} |
47
|
|
|
|
48
|
1 |
|
public function sort(callable $f): Collection |
49
|
|
|
{ |
50
|
1 |
|
$elements = $this->elements; |
51
|
1 |
|
\usort($elements, $f); |
52
|
|
|
|
53
|
1 |
|
return self::create($elements); |
54
|
|
|
} |
55
|
|
|
|
56
|
34 |
|
public function toArray(): array |
57
|
|
|
{ |
58
|
34 |
|
return $this->elements; |
59
|
|
|
} |
60
|
|
|
|
61
|
16 |
|
public function count(): int |
62
|
|
|
{ |
63
|
16 |
|
return \count($this->elements); |
64
|
|
|
} |
65
|
|
|
|
66
|
31 |
|
public function empty(): bool |
67
|
|
|
{ |
68
|
31 |
|
return empty($this->elements); |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|