Skip to content

Commit c7f10d4

Browse files
committed
Easier HtmlClass creation
1 parent 68a2557 commit c7f10d4

File tree

3 files changed

+14
-6
lines changed

3 files changed

+14
-6
lines changed

examples/1- SimpleMaker.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
'my-class-name',
1212
HtmlTag::pre('A Pre Tag'),
1313
HtmlTag::div(
14-
new HtmlClass(['class-1', 'class-2'])
14+
new HtmlClass('class-1', 'class-2')
1515
)
1616
)
1717
);

src/HtmlClass.php

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,11 @@
77

88
final class HtmlClass implements Stringable, IteratorAggregate
99
{
10-
public function __construct(private array $classList = [])
10+
private array $classList = [];
11+
12+
public function __construct(string ...$classes)
1113
{
14+
$this->classList = array_map(static fn ($e) => trim($e), $classes);
1215
}
1316

1417
public function __toString(): string
@@ -18,11 +21,12 @@ public function __toString(): string
1821

1922
public function has(string $class): bool
2023
{
21-
return in_array($class, $this->classList, true);
24+
return in_array(trim($class), $this->classList, true);
2225
}
2326

2427
public function add(string $class): self
2528
{
29+
$class = trim($class);
2630
if (!(empty($class) || $this->has($class))) {
2731
$this->classList[] = $class;
2832
}
@@ -31,7 +35,7 @@ public function add(string $class): self
3135

3236
public function remove(string $class): self
3337
{
34-
if (($pos = array_search($class, $this->classList, true)) !== false) {
38+
if (($pos = array_search(trim($class), $this->classList, true)) !== false) {
3539
unset($this->classList[$pos]);
3640
}
3741
return $this;
@@ -45,8 +49,12 @@ public function merge(string|self ...$classes): self
4549
array_shift($classes);
4650
}
4751
}
52+
// leftover strings
4853
if ($classes) {
49-
$this->classList = array_merge($this->classList, $classes);
54+
$this->classList = array_merge(
55+
$this->classList,
56+
array_map(static fn ($e) => trim($e), $classes)
57+
);
5058
}
5159
$this->classList = array_filter($this->classList);
5260
return $this;

src/Node/Internal/Attributes.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ trait Attributes
1616
{
1717
public function setClass(string ...$classes): self
1818
{
19-
return $this->setAttribute('class', (string)(new HtmlClass($classes)));
19+
return $this->setAttribute('class', (string)(new HtmlClass(...$classes)));
2020
}
2121

2222
public function getClass(): null|string|array

0 commit comments

Comments
 (0)