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 AttributeInterface[] |
13
|
|
|
*/ |
14
|
|
|
private array $collection = []; |
15
|
|
|
|
16
|
339 |
|
public function __construct() |
17
|
|
|
{ |
18
|
339 |
|
} |
19
|
|
|
|
20
|
6 |
|
public function count(): int |
21
|
|
|
{ |
22
|
6 |
|
return count($this->collection); |
23
|
|
|
} |
24
|
|
|
|
25
|
339 |
|
public function has(AttributeInterface $attribute): bool |
26
|
|
|
{ |
27
|
339 |
|
foreach ($this->collection as $item) { |
28
|
328 |
|
if ($item->getName() === $attribute->getName()) { |
29
|
5 |
|
return true; |
30
|
|
|
} |
31
|
|
|
} |
32
|
339 |
|
return false; |
33
|
|
|
} |
34
|
|
|
|
35
|
339 |
|
public function add(AttributeInterface $attribute): AttributeCollection |
36
|
|
|
{ |
37
|
339 |
|
if (!$this->has($attribute)) { |
38
|
339 |
|
$this->collection[] = $attribute; |
39
|
|
|
} |
40
|
339 |
|
return $this; |
41
|
|
|
} |
42
|
|
|
|
43
|
175 |
|
public function get(string $name): AttributeInterface|null |
44
|
|
|
{ |
45
|
175 |
|
foreach ($this->collection as $item) { |
46
|
173 |
|
if ($item->getName() === $name) { |
47
|
141 |
|
return $item; |
48
|
|
|
} |
49
|
|
|
} |
50
|
105 |
|
return null; |
51
|
|
|
} |
52
|
|
|
|
53
|
2 |
|
public function clear(): void |
54
|
|
|
{ |
55
|
2 |
|
$this->collection = []; |
56
|
|
|
} |
57
|
|
|
|
58
|
325 |
|
public function remove(string|AttributeInterface $element): AttributeCollection |
59
|
|
|
{ |
60
|
325 |
|
$attributeName = ($element instanceof AttributeInterface) ? $element->getName() : $element; |
61
|
|
|
|
62
|
325 |
|
foreach ($this->collection as $key => $item) { |
63
|
319 |
|
if ($item->getName() === $attributeName) { |
64
|
217 |
|
unset($this->collection[$key]); |
65
|
217 |
|
return $this; |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|
69
|
322 |
|
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
|
58 |
|
public function __toString(): string |
80
|
|
|
{ |
81
|
58 |
|
return implode(' ', array_filter($this->collection, fn($item) => !empty($item->__toString()))); |
82
|
|
|
} |
83
|
|
|
|
84
|
67 |
|
public function getIterator(): \ArrayIterator |
85
|
|
|
{ |
86
|
67 |
|
return new \ArrayIterator($this->collection); |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|