Skip to content

Commit 517f67b

Browse files
authored
Merge pull request #524 from ampproject/fix/522-uncaught-domexception
Fix error when source is missing closing head tag
2 parents 89cd1f6 + a4f9e8e commit 517f67b

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

src/Dom/Document.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -566,7 +566,13 @@ private function normalizeDocumentStructure($content)
566566
} elseif (! preg_match(self::HTML_STRUCTURE_BODY_END_TAG, $content, $matches)) {
567567
// Only <body> missing.
568568
// @todo This is an expensive regex operation, look into further optimization.
569-
$content = preg_replace(self::HTML_STRUCTURE_HEAD_TAG, '$0<body>', $content, 1);
569+
$content = preg_replace(self::HTML_STRUCTURE_HEAD_TAG, '$0<body>', $content, 1, $count);
570+
571+
// Closing </head> tag is missing.
572+
if (! $count) {
573+
$content = $content . '</head><body>';
574+
}
575+
570576
$content .= '</body>';
571577
}
572578

tests/Dom/DocumentTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
use AmpProject\Html\Tag;
1212
use AmpProject\Tests\MarkupComparison;
1313
use AmpProject\Tests\TestCase;
14+
use AmpProject\Tests\TestMarkup;
1415
use AmpProject\Validator\Spec\CssRuleset\AmpNoTransformed;
1516
use AmpProject\Validator\Spec\SpecRule;
1617
use DOMNode;
@@ -752,6 +753,17 @@ public function testInvalidHeadNodes()
752753
$this->assertEquals('meta', $dom->head->firstChild->tagName);
753754
$this->assertNull($dom->head->firstChild->nextSibling);
754755
$this->assertEquals(6, $dom->body->childNodes->length);
756+
757+
// Test with missing closing head tag.
758+
$expected = TestMarkup::DOCTYPE . '<html>'
759+
. '<head>' . TestMarkup::META_CHARSET . '<meta name="foo" content="bar"></head>'
760+
. '<body><foo></foo><bar></bar></body></html>';
761+
762+
$html = '<html><head><meta name="foo" content="bar"><foo></foo><bar></bar>';
763+
$document = Document::fromHtml($html);
764+
$output = $document->saveHTML();
765+
766+
$this->assertEqualMarkup($expected, $output);
755767
}
756768

757769
/**

0 commit comments

Comments
 (0)