|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Enjoys\Forms; |
|
6
|
|
|
|
|
7
|
|
|
use Enjoys\Forms\Interfaces\AttributeInterface; |
|
8
|
|
|
|
|
9
|
|
|
final class AttributeCollection implements \Countable, \IteratorAggregate |
|
10
|
|
|
{ |
|
11
|
|
|
/** |
|
12
|
|
|
* @var Attribute[] |
|
13
|
|
|
*/ |
|
14
|
|
|
private array $collection = []; |
|
15
|
|
|
|
|
16
|
|
|
public function __construct() |
|
17
|
|
|
{ |
|
18
|
|
|
} |
|
19
|
|
|
|
|
20
|
6 |
|
public function count() |
|
21
|
|
|
{ |
|
22
|
6 |
|
return count($this->collection); |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
319 |
|
public function has(AttributeInterface $attribute): bool |
|
26
|
|
|
{ |
|
27
|
319 |
|
foreach ($this->collection as $item) { |
|
28
|
308 |
|
if ($item->getName() === $attribute->getName()) { |
|
29
|
5 |
|
return true; |
|
30
|
|
|
} |
|
31
|
|
|
} |
|
32
|
319 |
|
return false; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
319 |
|
public function add(AttributeInterface $attribute): AttributeCollection |
|
36
|
|
|
{ |
|
37
|
319 |
|
if (!$this->has($attribute)) { |
|
38
|
319 |
|
$this->collection[] = $attribute; |
|
39
|
|
|
} |
|
40
|
319 |
|
return $this; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
137 |
|
public function get(string $name): AttributeInterface|null |
|
44
|
|
|
{ |
|
45
|
137 |
|
foreach ($this->collection as $item) { |
|
46
|
135 |
|
if ($item->getName() === $name) { |
|
47
|
126 |
|
return $item; |
|
48
|
|
|
} |
|
49
|
|
|
} |
|
50
|
71 |
|
return null; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
2 |
|
public function clear(): void |
|
54
|
|
|
{ |
|
55
|
2 |
|
$this->collection = []; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
305 |
|
public function remove(string|Attribute $element): AttributeCollection |
|
59
|
|
|
{ |
|
60
|
305 |
|
$attributeName = ($element instanceof AttributeInterface) ? $element->getName() : $element; |
|
61
|
|
|
|
|
62
|
305 |
|
foreach ($this->collection as $key => $item) { |
|
63
|
299 |
|
if ($item->getName() === $attributeName) { |
|
64
|
220 |
|
unset($this->collection[$key]); |
|
65
|
220 |
|
return $this; |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
302 |
|
return $this; |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
1 |
|
public function replace(AttributeInterface $attribute): AttributeCollection |
|
73
|
|
|
{ |
|
74
|
1 |
|
$this->remove($attribute->getName()); |
|
75
|
|
|
|
|
76
|
1 |
|
return $this->add($attribute); |
|
77
|
|
|
} |
|
78
|
|
|
|
|
79
|
60 |
|
public function __toString(): string |
|
80
|
|
|
{ |
|
81
|
60 |
|
return implode( |
|
82
|
|
|
' ', |
|
83
|
60 |
|
array_filter($this->collection, function ($item) { |
|
84
|
58 |
|
return !empty($item->__toString()); |
|
85
|
|
|
}) |
|
86
|
|
|
); |
|
87
|
|
|
} |
|
88
|
|
|
|
|
89
|
62 |
|
public function getIterator(): \ArrayIterator |
|
90
|
|
|
{ |
|
91
|
62 |
|
return new \ArrayIterator($this->collection); |
|
92
|
|
|
} |
|
93
|
|
|
} |
|
94
|
|
|
|