1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | |||
6 | namespace Enjoys\AssetsCollector; |
||
7 | |||
8 | |||
9 | final class AttributeCollection |
||
10 | { |
||
11 | /** |
||
12 | * @var array<string, string|null|false> |
||
13 | */ |
||
14 | private array $attributes = []; |
||
15 | |||
16 | /** |
||
17 | * @param array<array-key, string|null|false> $attributes |
||
0 ignored issues
–
show
Documentation
Bug
introduced
by
![]() |
|||
18 | */ |
||
19 | public function __construct(array $attributes = []) |
||
20 | { |
||
21 | foreach ($attributes as $key => $value) { |
||
22 | if (is_int($key) && is_string($value)) { |
||
23 | $key = $value; |
||
24 | $value = null; |
||
25 | } |
||
26 | if ($key === ''){ |
||
27 | continue; |
||
28 | } |
||
29 | /** @psalm-suppress MixedPropertyTypeCoercion */ |
||
30 | $this->attributes[$key] = $value; |
||
31 | } |
||
32 | } |
||
33 | |||
34 | public function isEmpty(): bool |
||
35 | { |
||
36 | return $this->attributes === []; |
||
37 | } |
||
38 | |||
39 | public function set(string $key, string|null|false $value, bool $replace = false): AttributeCollection |
||
40 | { |
||
41 | if ($replace === false && array_key_exists($key, $this->attributes)) { |
||
42 | return $this; |
||
43 | } |
||
44 | |||
45 | $this->attributes[$key] = $value; |
||
46 | return $this; |
||
47 | } |
||
48 | |||
49 | public function get(string $key): string|null|false |
||
50 | { |
||
51 | if (array_key_exists($key, $this->attributes)) { |
||
52 | return $this->attributes[$key]; |
||
53 | } |
||
54 | return false; |
||
55 | } |
||
56 | |||
57 | public function __toString(): string |
||
58 | { |
||
59 | if ($this->isEmpty()) { |
||
60 | return ''; |
||
61 | } |
||
62 | |||
63 | $result = []; |
||
64 | foreach ($this->attributes as $key => $value) { |
||
65 | if ($value === false) { |
||
66 | continue; |
||
67 | } |
||
68 | |||
69 | if ($value === null) { |
||
70 | $result[] = sprintf("%s", $key); |
||
71 | continue; |
||
72 | } |
||
73 | $result[] = sprintf("%s='%s'", $key, $value); |
||
74 | } |
||
75 | |||
76 | return (empty($result)) ? '' : ' ' . implode(" ", $result); |
||
77 | } |
||
78 | |||
79 | |||
80 | /** |
||
81 | * @return array<array-key, string|null|false> |
||
0 ignored issues
–
show
|
|||
82 | */ |
||
83 | public function getArray(): array |
||
84 | { |
||
85 | return $this->attributes; |
||
86 | } |
||
87 | |||
88 | |||
89 | } |
||
90 |