@@ -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