|
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
|
|
|
/** |
|
12
|
|
|
* @var array |
|
13
|
|
|
*/ |
|
14
|
|
|
private $elements; |
|
15
|
|
|
|
|
16
|
60 |
|
private function __construct(array $elements) |
|
17
|
|
|
{ |
|
18
|
60 |
|
$this->elements = $elements; |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
60 |
|
public static function create(array $elements): Collection |
|
22
|
|
|
{ |
|
23
|
60 |
|
return new self($elements); |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
7 |
|
public function getIterator(): Traversable |
|
27
|
|
|
{ |
|
28
|
7 |
|
yield from $this->elements; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
24 |
|
public function merge(Collection $other): Collection |
|
32
|
|
|
{ |
|
33
|
24 |
|
return self::create(\array_merge($this->elements, $other->elements)); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
26 |
|
public function filter(callable $f): Collection |
|
37
|
|
|
{ |
|
38
|
26 |
|
return self::create(\array_values(\array_filter($this->elements, $f))); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
19 |
|
public function map(callable $f): Collection |
|
42
|
|
|
{ |
|
43
|
19 |
|
return self::create(\array_map($f, $this->elements)); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
9 |
|
public function reduce($initial, callable $param) |
|
47
|
|
|
{ |
|
48
|
9 |
|
return \array_reduce($this->elements, $param, $initial); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
1 |
|
public function sort(callable $f): Collection |
|
52
|
|
|
{ |
|
53
|
1 |
|
$elements = $this->elements; |
|
54
|
1 |
|
\usort($elements, $f); |
|
55
|
|
|
|
|
56
|
1 |
|
return self::create($elements); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
31 |
|
public function toArray(): array |
|
60
|
|
|
{ |
|
61
|
31 |
|
return $this->elements; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
15 |
|
public function count(): int |
|
65
|
|
|
{ |
|
66
|
15 |
|
return \count($this->elements); |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
29 |
|
public function empty(): bool |
|
70
|
|
|
{ |
|
71
|
29 |
|
return empty($this->elements); |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|