Skip to content

Ensure empty inline svg and math tags are serialized as void tags #259

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/HTML5/Serializer/OutputRules.php
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,9 @@ protected function doctype()
$this->nl();
}

/**
* @param \DOMElement $ele
*/
public function element($ele)
{
$name = $ele->tagName;
Expand All @@ -227,6 +230,9 @@ public function element($ele)
}

$this->openTag($ele);
// The tag is already self-closed (`<svg />` or `<math />`) 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) {
Expand All @@ -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);
}
}
Expand Down
17 changes: 17 additions & 0 deletions test/HTML5/Serializer/OutputRulesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -652,4 +652,21 @@ public function testHandlingInvalidRawContent()
<h1>Hello!</h1>
<p>Bar</p></script>'));
}

public function testSvgAndMathElementsWithoutChildNodesAreHandledAsVoidTags()
{
$dom = $this->html5->loadHTML(
'<!doctype html>
<html lang="en" id="base">
<body>
<svg></svg>
<math></math>
</body>
</html>');

$contents = $this->html5->saveHTML($dom);

self::assertRegExp('|^\h*<svg />$|m', $contents);
self::assertRegExp('|^\h*<math />$|m', $contents);
}
}