Skip to content

Commit 040c7f4

Browse files
committed
accept Stringables as well as strings
1 parent 06dd89d commit 040c7f4

File tree

2 files changed

+28
-10
lines changed

2 files changed

+28
-10
lines changed

src/microhtml.php

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@
55
namespace MicroHTML;
66

77
/**
8-
* @phpstan-type Attrs array<string,string|null|bool|int|float>
9-
* @phpstan-type Child \MicroHTML\HTMLElement|string|null|bool|int|float
8+
* @phpstan-type Attrs array<string,string|\Stringable|null|bool|int|float>
9+
* @phpstan-type Child \MicroHTML\HTMLElement|string|\Stringablenull|bool|int|float
1010
* @phpstan-type Arg Attrs|Child
1111
*/
1212
class HTMLElement
@@ -52,10 +52,7 @@ protected function renderAttrs(): string
5252
// set to false, which is often easier than deleting
5353
// the key from the attributes dictionary
5454
} else {
55-
if (is_numeric($val)) {
56-
$val = (string)$val;
57-
}
58-
$val = htmlentities($val, ENT_QUOTES, "UTF-8");
55+
$val = htmlentities((string)$val, ENT_QUOTES, "UTF-8");
5956
$par .= " $name='$val'";
6057
}
6158
}
@@ -72,10 +69,7 @@ protected function renderChildren(): string
7269
if (is_null($child) || is_bool($child)) {
7370
$child = "";
7471
}
75-
if (is_numeric($child)) {
76-
$child = (string)$child;
77-
}
78-
$sub .= htmlentities($child, ENT_QUOTES, "UTF-8");
72+
$sub .= htmlentities((string)$child, ENT_QUOTES, "UTF-8");
7973
}
8074
}
8175
return $sub;

tests/HTMLElementTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,14 @@
1313
use function MicroHTML\rawHTML;
1414
use function MicroHTML\joinHTML;
1515

16+
class MockUrl
17+
{
18+
public function __toString(): string
19+
{
20+
return "https://example.com";
21+
}
22+
}
23+
1624
class HTMLElementTest extends \PHPUnit\Framework\TestCase
1725
{
1826
/*
@@ -236,4 +244,20 @@ public function testJoinFiltered(): void
236244
joinHTML(", ", [P("A"), null, "C"], filterNulls: false)
237245
);
238246
}
247+
248+
public function testStringableAttribute(): void
249+
{
250+
$this->assertEquals(
251+
"<a href='https://example.com'>link</a>",
252+
A(["href" => new MockUrl()], "link")
253+
);
254+
}
255+
256+
public function testStringableChild(): void
257+
{
258+
$this->assertEquals(
259+
"<p>https://example.com</p>",
260+
P(new MockUrl())
261+
);
262+
}
239263
}

0 commit comments

Comments
 (0)