Skip to content

Commit 5891920

Browse files
committed
[Fixes #5][Fixes #6]
1 parent 30e20c1 commit 5891920

2 files changed

Lines changed: 39 additions & 8 deletions

File tree

examples/example.html

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,11 @@
55
<meta http-equiv="X-UA-Compatible" content="IE=edge">
66
<meta name="viewport" content="width=device-width, initial-scale=1">
77
<title>Northys\Inliner Example</title>
8+
<style type="text/css">
9+
body {
10+
background: #000;
11+
}
12+
</style>
813
</head>
914
<body>
1015
<h1 id="heading">Hello, world!</h1>

src/Northys/CssInliner/CssInliner.php

Lines changed: 34 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,29 +18,54 @@ class CSSInliner
1818
*/
1919
private $css;
2020

21+
/**
22+
* @var DOMDocument
23+
*/
24+
private $dom;
25+
26+
/**
27+
* @var DOMXPath
28+
*/
29+
private $finder;
30+
2131

2232

2333
public function addCSS($filename)
2434
{
2535
if ( ! $css = @file_get_contents($filename)) {
2636
throw new \Exception("Failed on loading CSS file. Check the file path you have provided!", 1);
2737
}
38+
// merge all CSS content into $this-css variable
39+
$this->css .= $css;
40+
}
41+
42+
43+
44+
public function parseCSS() {
45+
// get styles inside <style> tags in provided HTML
46+
foreach ($this->dom->getElementsByTagName('style') as $style) {
47+
$this->css .= $style->textContent;
48+
}
49+
$parser = new CSS\Parser($this->css);
2850

29-
$parser = new CSS\Parser($css);
30-
$this->css = $parser->parse();
51+
$css = $parser->parse();
52+
if (!$css) {
53+
throw new \Exception("You haven't provided any styles by addCSS() method. There is also no styles inside HTML.", 1);
54+
}
55+
return $css;
3156
}
3257

3358

3459

3560
public function render($html)
3661
{
37-
$dom = new \DOMDocument;
38-
$dom->loadHTML($html);
39-
$finder = new \DOMXPath($dom);
40-
62+
$this->dom = new \DOMDocument;
63+
$this->dom->loadHTML($html);
64+
$this->finder = new \DOMXPath($this->dom);
65+
$this->css = $this->parseCSS();
4166
foreach ($this->css->getAllRuleSets() as $ruleSet) {
4267
$selector = $ruleSet->getSelector();
43-
foreach ($finder->evaluate(CssSelector::toXPath($selector[0])) as $node) {
68+
foreach ($this->finder->evaluate(CssSelector::toXPath($selector[0])) as $node) {
4469
if ($node->getAttribute('style')) {
4570
$node->setAttribute('style', $node->getAttribute('style') . implode(' ', $ruleSet->getRules()));
4671
} else {
@@ -49,6 +74,7 @@ public function render($html)
4974
}
5075
}
5176

52-
return $dom->saveHTML();
77+
return $this->dom->saveHTML();
5378
}
79+
5480
}

0 commit comments

Comments
 (0)