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
|
59 |
|
private function __construct(array $elements) |
17
|
|
|
{ |
18
|
59 |
|
$this->elements = $elements; |
19
|
|
|
} |
20
|
|
|
|
21
|
59 |
|
public static function create(array $elements): Collection |
22
|
|
|
{ |
23
|
59 |
|
return new self($elements); |
24
|
|
|
} |
25
|
|
|
|
26
|
6 |
|
public function getIterator(): Traversable |
27
|
|
|
{ |
28
|
6 |
|
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
|
31 |
|
public function sort(callable $f): Collection |
52
|
|
|
{ |
53
|
31 |
|
$elements = $this->elements; |
54
|
|
|
usort($elements, $f); |
55
|
|
|
return self::create($elements); |
56
|
15 |
|
} |
57
|
|
|
|
58
|
15 |
|
public function toArray(): array |
59
|
|
|
{ |
60
|
|
|
return $this->elements; |
61
|
29 |
|
} |
62
|
|
|
|
63
|
29 |
|
public function count(): int |
64
|
|
|
{ |
65
|
|
|
return \count($this->elements); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
public function empty(): bool |
69
|
|
|
{ |
70
|
|
|
return empty($this->elements); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|