Skip to content

Commit c97a75a

Browse files
committed
Ensure empty inline svg and math tags are serialized as void tags
Before this change, e.g. `<svg></svg>` has been incorrectly serialized as `<svg /></svg>`. This change ensures, that the result is a proper (self-closing) void tag `<svg />`.
1 parent 4259770 commit c97a75a

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

src/HTML5/Serializer/OutputRules.php

+7-1
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,9 @@ protected function doctype()
206206
$this->nl();
207207
}
208208

209+
/**
210+
* @param \DOMElement $ele
211+
*/
209212
public function element($ele)
210213
{
211214
$name = $ele->tagName;
@@ -227,6 +230,9 @@ public function element($ele)
227230
}
228231

229232
$this->openTag($ele);
233+
// The tag is already self-closed (`<svg />` or `<math />`) in `openTag` if there are no child nodes.
234+
$handledAsVoidTag = $this->outputMode !== static::IM_IN_HTML && !$ele->hasChildNodes();
235+
230236
if (Elements::isA($name, Elements::TEXT_RAW)) {
231237
foreach ($ele->childNodes as $child) {
232238
if ($child instanceof \DOMCharacterData) {
@@ -248,7 +254,7 @@ public function element($ele)
248254
}
249255

250256
// If not unary, add a closing tag.
251-
if (!Elements::isA($name, Elements::VOID_TAG)) {
257+
if (!$handledAsVoidTag && !Elements::isA($name, Elements::VOID_TAG)) {
252258
$this->closeTag($ele);
253259
}
254260
}

test/HTML5/Serializer/OutputRulesTest.php

+17
Original file line numberDiff line numberDiff line change
@@ -652,4 +652,21 @@ public function testHandlingInvalidRawContent()
652652
<h1>Hello!</h1>
653653
<p>Bar</p></script>'));
654654
}
655+
656+
public function testSvgAndMathElementsWithoutChildNodesAreHandledAsVoidTags()
657+
{
658+
$dom = $this->html5->loadHTML(
659+
'<!doctype html>
660+
<html lang="en" id="base">
661+
<body>
662+
<svg></svg>
663+
<math></math>
664+
</body>
665+
</html>');
666+
667+
$contents = $this->html5->saveHTML($dom);
668+
669+
self::assertRegExp('|^\h*<svg />$|m', $contents);
670+
self::assertRegExp('|^\h*<math />$|m', $contents);
671+
}
655672
}

0 commit comments

Comments
 (0)