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