Skip to content

Commit 42da43c

Browse files
committed
Fix #13
HTML id attributes are a special case.
1 parent f596906 commit 42da43c

File tree

3 files changed

+22
-2
lines changed

3 files changed

+22
-2
lines changed

src/Core/StapleTrait.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ public function flattenAttributes(): string
6363
$pieces = $this->renderAttributes();
6464

6565
if (!empty($this->id)) {
66-
$pieces['id'] = Utilities::escapeAttribute($this->id);
66+
$pieces['id'] = $this->id;
6767
}
6868

6969
if (!empty($this->classes)) {
@@ -91,7 +91,11 @@ public function flattenAttributes(): string
9191
}
9292
$return = '';
9393
foreach ($pieces as $attr => $value) {
94-
$return .= "{$attr}=\"" . Utilities::escapeAttribute((string) $value) . "\" ";
94+
if ($attr === 'id') {
95+
$return .= "{$attr}=\"" . Utilities::escapeIDAttribute((string)$value) . "\" ";
96+
} else {
97+
$return .= "{$attr}=\"" . Utilities::escapeAttribute((string)$value) . "\" ";
98+
}
9599
}
96100
return ' ' . trim($return);
97101
}

src/Core/Utilities.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,11 @@ public static function escapeAttribute(string $input): string
5858
return htmlentities($input, ENT_HTML5 | ENT_QUOTES, 'utf-8');
5959
}
6060

61+
public static function escapeIDAttribute(string $id): string
62+
{
63+
return preg_replace('/[^A-Za-z0-9-_]/', '', $id);
64+
}
65+
6166
/**
6267
* @param array $classes
6368
* @return string

tests/FormTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,17 @@ public function testEmpty()
3737
$form . ''
3838
);
3939
}
40+
41+
public function testIdWithUnderline()
42+
{
43+
$form = (new Form())->disableAntiCSRF();
44+
$form->setId('group_order');
45+
$this->assertSame(
46+
'<form id="group_order" method="GET" action=""></form>',
47+
$form . ''
48+
);
49+
}
50+
4051
public function testEmptyWithoutDisablingCsrfProtection()
4152
{
4253
/** @var array<string, string> $storage */

0 commit comments

Comments
 (0)