diff --git a/src/HtmlConverter.php b/src/HtmlConverter.php index 944cb08..44955da 100644 --- a/src/HtmlConverter.php +++ b/src/HtmlConverter.php @@ -110,21 +110,25 @@ public function convert(string $html): string private function createDOMDocument(string $html): \DOMDocument { - $document = new \DOMDocument(); + $document = new \DOMDocument(); + $previousLibxmlErrorState = null; if ($this->getConfig()->getOption('suppress_errors')) { // Suppress conversion errors (from http://bit.ly/pCCRSX) - \libxml_use_internal_errors(true); + $previousLibxmlErrorState = \libxml_use_internal_errors(true); } - // Hack to load utf-8 HTML (from http://bit.ly/pVDyCt) - $document->loadHTML('' . $html); - $document->encoding = 'UTF-8'; + try { + // Hack to load utf-8 HTML (from http://bit.ly/pVDyCt) + $document->loadHTML('' . $html); + $document->encoding = 'UTF-8'; - $this->replaceMisplacedComments($document); - - if ($this->getConfig()->getOption('suppress_errors')) { - \libxml_clear_errors(); + $this->replaceMisplacedComments($document); + } finally { + if ($this->getConfig()->getOption('suppress_errors')) { + \libxml_clear_errors(); + \libxml_use_internal_errors($previousLibxmlErrorState); + } } return $document; diff --git a/tests/HtmlConverterTest.php b/tests/HtmlConverterTest.php index 4b71832..e657d57 100644 --- a/tests/HtmlConverterTest.php +++ b/tests/HtmlConverterTest.php @@ -316,6 +316,34 @@ public function testMalformedHtml(): void $this->assertHtmlGivesMarkdown('Strong italic Regular text', '***Strong italic*** Regular text'); // Missing closing } + public function testLibxmlInternalErrorsIsRestoredAfterConvert(): void + { + $previousState = \libxml_use_internal_errors(false); + + try { + $converter = new HtmlConverter(); + $converter->convert('

Hello

'); + + $this->assertFalse(\libxml_use_internal_errors()); + } finally { + \libxml_use_internal_errors($previousState); + } + } + + public function testLibxmlInternalErrorsIsUnchangedWhenSuppressErrorsDisabled(): void + { + $previousState = \libxml_use_internal_errors(true); + + try { + $converter = new HtmlConverter(['suppress_errors' => false]); + $converter->convert('

Hello

'); + + $this->assertTrue(\libxml_use_internal_errors()); + } finally { + \libxml_use_internal_errors($previousState); + } + } + public function testHtml5TagsArePreserved(): void { $this->assertHtmlGivesMarkdown('
Some stuff
', '
Some stuff
');