Skip to content

Commit bc1dbb3

Browse files
committed
feat: add conditional style attributes
1 parent 507a926 commit bc1dbb3

File tree

3 files changed

+37
-4
lines changed

3 files changed

+37
-4
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,9 @@ $attr ??= [];
139139
?>
140140
<button <?= attributes([
141141
'role' => 'button',
142+
'style' => [
143+
'font-size: 2rem;' => ($size === 'large'),
144+
],
142145
])->class([
143146
'button',
144147
"button--{$size}",

src/Attributes.php

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -154,13 +154,29 @@ public static function normalizeClassValue(array|string|null $classes): ?string
154154
return implode(' ', array_unique($value));
155155
}
156156

157+
/**
158+
* normalizes an array of class names to a string, e.g.
159+
* array(['font-size: 1rem', 'color: red' => false]) => "font-size: 1rem;"
160+
* array(['font-size: 1rem', 'color: red' => true]) => "font-size: 1rem; color: red"
161+
*/
157162
public static function normalizeStyleValue(array|string|null $styles): ?string
158163
{
159-
// if (is_null($styles)) {
160-
// return null;
161-
// }
164+
if (is_null($styles)) {
165+
return null;
166+
}
167+
168+
$styles = A::wrap($styles);
169+
$value = [];
170+
171+
foreach ($styles as $key => $property) {
172+
if (is_numeric($key)) {
173+
$value[] = $property;
174+
} elseif ($property) {
175+
$value[] = $key;
176+
}
177+
}
162178

163-
return is_array($styles) ? implode('; ', $styles) : $styles;
179+
return implode('; ', array_map(fn($v) => trim($v, '; '), $value));
164180
}
165181

166182
public function set(string $name, mixed $value): static

tests/AttributesTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,20 @@ public function testAttributesWithClassesArray(): void
158158
$this->assertSame((string) $attr, 'class="foo bar" foo="bar"');
159159
}
160160

161+
public function testAttributesWithStylesArray(): void
162+
{
163+
$attr = new Attributes([
164+
'foo' => 'bar',
165+
'style' => [
166+
'font-size: 1rem;',
167+
'line-height: 1.2' => true,
168+
'line-height: 1.5' => false,
169+
]
170+
]);
171+
172+
$this->assertSame((string) $attr, 'foo="bar" style="font-size: 1rem; line-height: 1.2"');
173+
}
174+
161175
public function testMerge(): void
162176
{
163177
$attr = new Attributes(foo: 'bar');

0 commit comments

Comments
 (0)