From c97a75a6517ed405451d96172c253aca1cb66f5a Mon Sep 17 00:00:00 2001 From: Oliver Hader Date: Thu, 6 Mar 2025 22:22:42 +0100 Subject: [PATCH] Ensure empty inline svg and math tags are serialized as void tags Before this change, e.g. `` has been incorrectly serialized as ``. This change ensures, that the result is a proper (self-closing) void tag ``. --- src/HTML5/Serializer/OutputRules.php | 8 +++++++- test/HTML5/Serializer/OutputRulesTest.php | 17 +++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/HTML5/Serializer/OutputRules.php b/src/HTML5/Serializer/OutputRules.php index ec467f2..13cbdc6 100644 --- a/src/HTML5/Serializer/OutputRules.php +++ b/src/HTML5/Serializer/OutputRules.php @@ -206,6 +206,9 @@ protected function doctype() $this->nl(); } + /** + * @param \DOMElement $ele + */ public function element($ele) { $name = $ele->tagName; @@ -227,6 +230,9 @@ public function element($ele) } $this->openTag($ele); + // The tag is already self-closed (`` or ``) in `openTag` if there are no child nodes. + $handledAsVoidTag = $this->outputMode !== static::IM_IN_HTML && !$ele->hasChildNodes(); + if (Elements::isA($name, Elements::TEXT_RAW)) { foreach ($ele->childNodes as $child) { if ($child instanceof \DOMCharacterData) { @@ -248,7 +254,7 @@ public function element($ele) } // If not unary, add a closing tag. - if (!Elements::isA($name, Elements::VOID_TAG)) { + if (!$handledAsVoidTag && !Elements::isA($name, Elements::VOID_TAG)) { $this->closeTag($ele); } } diff --git a/test/HTML5/Serializer/OutputRulesTest.php b/test/HTML5/Serializer/OutputRulesTest.php index bb09853..7155e25 100644 --- a/test/HTML5/Serializer/OutputRulesTest.php +++ b/test/HTML5/Serializer/OutputRulesTest.php @@ -652,4 +652,21 @@ public function testHandlingInvalidRawContent()

Hello!

Bar

')); } + + public function testSvgAndMathElementsWithoutChildNodesAreHandledAsVoidTags() + { + $dom = $this->html5->loadHTML( + ' + + + + + +'); + + $contents = $this->html5->saveHTML($dom); + + self::assertRegExp('|^\h*$|m', $contents); + self::assertRegExp('|^\h*$|m', $contents); + } }