|
1
|
|
|
<?php |
|
2
|
|
|
/* |
|
3
|
|
|
* Copyright (c) Nate Brunette. |
|
4
|
|
|
* Distributed under the MIT License (http://opensource.org/licenses/MIT) |
|
5
|
|
|
*/ |
|
6
|
|
|
|
|
7
|
|
|
namespace Tebru\Collection; |
|
8
|
|
|
|
|
9
|
|
|
use ArrayIterator; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* Class Bag |
|
13
|
|
|
* |
|
14
|
|
|
* A generic [@see CollectionInterface] backed by an array. |
|
15
|
|
|
* |
|
16
|
|
|
* @author Nate Brunette <[email protected]> |
|
17
|
|
|
*/ |
|
18
|
|
|
class Bag extends AbstractCollection |
|
19
|
|
|
{ |
|
20
|
|
|
/** |
|
21
|
|
|
* The collection elements |
|
22
|
|
|
* |
|
23
|
|
|
* @var array |
|
24
|
|
|
*/ |
|
25
|
|
|
protected $elements = []; |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* Constructor |
|
29
|
|
|
* |
|
30
|
|
|
* @param array $elements |
|
31
|
|
|
*/ |
|
32
|
4 |
|
public function __construct(array $elements = []) |
|
33
|
|
|
{ |
|
34
|
4 |
|
$this->elements = array_values($elements); |
|
35
|
4 |
|
} |
|
36
|
|
|
|
|
37
|
|
|
/** |
|
38
|
|
|
* Ensure the element exists in the collection |
|
39
|
|
|
* |
|
40
|
|
|
* Returns true if the collection can contain duplicates, |
|
41
|
|
|
* and false if it cannot. |
|
42
|
|
|
* |
|
43
|
|
|
* @param mixed $element |
|
44
|
|
|
* @return bool |
|
45
|
|
|
*/ |
|
46
|
28 |
|
public function add($element): bool |
|
47
|
|
|
{ |
|
48
|
28 |
|
$this->elements[] = $element; |
|
49
|
|
|
|
|
50
|
28 |
|
return true; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* Removes all elements from a collection |
|
55
|
|
|
* |
|
56
|
|
|
* @return void |
|
57
|
|
|
*/ |
|
58
|
1 |
|
public function clear(): void |
|
59
|
|
|
{ |
|
60
|
1 |
|
$this->elements = []; |
|
61
|
1 |
|
} |
|
62
|
|
|
|
|
63
|
|
|
/** |
|
64
|
|
|
* Removes object if it exists |
|
65
|
|
|
* |
|
66
|
|
|
* Returns true if the element was removed |
|
67
|
|
|
* |
|
68
|
|
|
* @param mixed $element |
|
69
|
|
|
* @return bool |
|
70
|
|
|
*/ |
|
71
|
8 |
|
public function remove($element): bool |
|
72
|
|
|
{ |
|
73
|
8 |
|
$index = array_search($element, $this->elements, true); |
|
74
|
|
|
|
|
75
|
8 |
|
if (false === $index) { |
|
76
|
2 |
|
return false; |
|
77
|
|
|
} |
|
78
|
|
|
|
|
79
|
7 |
|
array_splice($this->elements, $index, 1); |
|
80
|
|
|
|
|
81
|
7 |
|
return true; |
|
82
|
|
|
} |
|
83
|
|
|
|
|
84
|
|
|
/** |
|
85
|
|
|
* Returns an array of all elements in the collection |
|
86
|
|
|
* |
|
87
|
|
|
* @return array |
|
88
|
|
|
*/ |
|
89
|
31 |
|
public function toArray(): array |
|
90
|
|
|
{ |
|
91
|
31 |
|
return $this->elements; |
|
92
|
|
|
} |
|
93
|
|
|
|
|
94
|
|
|
/** |
|
95
|
|
|
* Retrieve an external iterator |
|
96
|
|
|
* |
|
97
|
|
|
* @return ArrayIterator |
|
98
|
|
|
*/ |
|
99
|
|
|
public function getIterator(): ArrayIterator |
|
100
|
|
|
{ |
|
101
|
|
|
return new ArrayIterator($this->elements); |
|
102
|
|
|
} |
|
103
|
|
|
} |
|
104
|
|
|
|