1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @author Maxim Sokolovsky |
4
|
|
|
*/ |
5
|
|
|
|
6
|
|
|
namespace WS\Utils\Collections; |
7
|
|
|
|
8
|
|
|
abstract class AbstractCollection implements Collection |
9
|
|
|
{ |
10
|
|
|
protected $elements = []; |
11
|
|
|
|
12
|
214 |
|
public function __construct(?array $elements = null) |
13
|
|
|
{ |
14
|
214 |
|
if ($elements === null) { |
15
|
126 |
|
return; |
16
|
|
|
} |
17
|
198 |
|
foreach ($elements as $element) { |
18
|
166 |
|
$this->add($element); |
19
|
|
|
} |
20
|
198 |
|
} |
21
|
|
|
|
22
|
92 |
|
public static function of(...$elements): self |
23
|
|
|
{ |
24
|
92 |
|
return new static($elements ?: null); |
25
|
|
|
} |
26
|
|
|
|
27
|
177 |
|
public function add($element): bool |
28
|
|
|
{ |
29
|
177 |
|
$beforeSize = count($this->elements); |
30
|
177 |
|
$this->elements[] = $element; |
31
|
177 |
|
return $beforeSize < count($this->elements); |
32
|
|
|
} |
33
|
|
|
|
34
|
116 |
|
public function addAll(iterable $elements): bool |
35
|
|
|
{ |
36
|
116 |
|
$res = true; |
37
|
116 |
|
foreach ($elements as $element) { |
38
|
97 |
|
!$this->add($element) && $res = false; |
39
|
|
|
} |
40
|
116 |
|
return $res; |
41
|
|
|
} |
42
|
|
|
|
43
|
4 |
|
public function merge(Collection $collection): bool |
44
|
|
|
{ |
45
|
4 |
|
$this->elements = array_merge($this->toArray(), $collection->toArray()); |
46
|
4 |
|
return true; |
47
|
|
|
} |
48
|
|
|
|
49
|
6 |
|
public function clear(): void |
50
|
|
|
{ |
51
|
6 |
|
$this->elements = []; |
52
|
6 |
|
} |
53
|
|
|
|
54
|
10 |
|
public function contains($element): bool |
55
|
|
|
{ |
56
|
10 |
|
return in_array($element, $this->elements, true); |
57
|
|
|
} |
58
|
|
|
|
59
|
24 |
|
public function equals(Collection $collection): bool |
60
|
|
|
{ |
61
|
24 |
|
return $this->toArray() === $collection->toArray(); |
62
|
|
|
} |
63
|
|
|
|
64
|
91 |
|
public function size(): int |
65
|
|
|
{ |
66
|
91 |
|
return count($this->elements); |
67
|
|
|
} |
68
|
|
|
|
69
|
27 |
|
public function isEmpty(): bool |
70
|
|
|
{ |
71
|
27 |
|
return !$this->size(); |
72
|
|
|
} |
73
|
|
|
|
74
|
151 |
|
public function toArray(): array |
75
|
|
|
{ |
76
|
151 |
|
return array_values($this->elements); |
77
|
|
|
} |
78
|
|
|
|
79
|
114 |
|
public function getIterator() |
80
|
|
|
{ |
81
|
114 |
|
yield from $this->toArray(); |
82
|
113 |
|
} |
83
|
|
|
|
84
|
16 |
|
public function copy(): Collection |
85
|
|
|
{ |
86
|
16 |
|
return clone $this; |
87
|
|
|
} |
88
|
|
|
|
89
|
8 |
|
protected function setElements(array $elements): void |
90
|
|
|
{ |
91
|
8 |
|
$this->elements = $elements; |
92
|
8 |
|
} |
93
|
|
|
|
94
|
10 |
|
protected function getElements(): array |
95
|
|
|
{ |
96
|
10 |
|
return $this->elements; |
97
|
|
|
} |
98
|
|
|
|
99
|
|
|
abstract public function stream(): Stream; |
100
|
|
|
} |
101
|
|
|
|