Skip to content

Commit

Permalink
Add ability to set lib xml parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
bytestream committed May 21, 2021
1 parent b43b05c commit 0c0289d
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
18 changes: 17 additions & 1 deletion src/CssToInlineStyles.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,29 @@ class CssToInlineStyles
{
private $cssConverter;

/** @var int */
private $libXmlOptions = 0;

public function __construct()
{
if (class_exists('Symfony\Component\CssSelector\CssSelectorConverter')) {
$this->cssConverter = new CssSelectorConverter();
}
}

/**
* Set DOMDocument LibXML parameters.
*
* @param int $options
* @return self
*/
public function setLibXmlOptions($options)
{
$this->libXmlOptions = $options;

return $this;
}

/**
* Will inline the $css into the given $html
*
Expand Down Expand Up @@ -113,7 +129,7 @@ protected function createDomDocumentFromHtml($html)
{
$document = new \DOMDocument('1.0', 'UTF-8');
$internalErrors = libxml_use_internal_errors(true);
$document->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
$document->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'), $this->libXmlOptions);
libxml_use_internal_errors($internalErrors);
$document->formatOutput = true;

Expand Down
17 changes: 17 additions & 0 deletions tests/CssToInlineStylesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,23 @@ public function testSelfClosingTags()
$this->assertCorrectConversion($expected, $html, $css);
}

public function testSetLibXmlOptions()
{
$dtd = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">';
$expected = '<html><body><p></p></body></html>';

$this->assertSame(
$dtd . "\n" . $expected,
$this->cssToInlineStyles->convert('<p></p>')
);

$this->cssToInlineStyles->setLibXmlOptions(LIBXML_HTML_NODEFDTD);
$this->assertSame(
"\n" . $expected,
$this->cssToInlineStyles->convert('<p></p>')
);
}

private function assertCorrectConversion($expected, $html, $css = null)
{
$this->assertEquals(
Expand Down

0 comments on commit 0c0289d

Please sign in to comment.