@@ -34,6 +34,12 @@ class CssFromHTMLExtractor
34
34
/** @var Cache */
35
35
private $ resultCache ;
36
36
37
+ /** @var array */
38
+ private $ loadedfiles = [];
39
+
40
+ /** @var array */
41
+ private $ cachedRules = [];
42
+
37
43
/**
38
44
* CssFromHTMLExtractor constructor.
39
45
* @param Cache|null $resultCache
@@ -50,6 +56,7 @@ public function __construct(Cache $resultCache = null)
50
56
$ this ->cssConverter = new CssSelectorConverter ();
51
57
52
58
$ this ->resultCache = is_null ($ resultCache ) ? new ArrayCache () : $ resultCache ;
59
+ $ this ->cachedRules = (array )$ resultCache ->fetch ('cachedRules ' );
53
60
}
54
61
55
62
public function getCssStore ()
@@ -68,6 +75,8 @@ public function getHtmlStore()
68
75
public function addBaseRules ($ sourceCss )
69
76
{
70
77
$ identifier = md5 ($ sourceCss );
78
+
79
+ $ this ->loadedfiles [] = $ identifier ;
71
80
if ($ this ->resultCache ->contains ($ identifier )) {
72
81
list ($ rules , $ charset ) = $ this ->resultCache ->fetch ($ identifier );
73
82
$ this ->rules = $ rules ;
@@ -128,9 +137,15 @@ public function extractCss($html)
128
137
129
138
$ xPath = new DOMXPath ($ document );
130
139
140
+ $ cssIdentifier = join ('- ' , $ this ->loadedfiles );
141
+
131
142
$ applicable_rules = array_filter (
132
143
$ this ->rules ,
133
- function (Rule $ rule ) use ($ xPath ) {
144
+ function (Rule $ rule ) use ($ xPath , $ cssIdentifier ) {
145
+ if (isset ($ this ->cachedRules [$ cssIdentifier ][$ rule ->getSelector ()])) {
146
+ return true ;
147
+ }
148
+
134
149
$ expression = $ this ->buildExpressionForSelector ($ rule ->getSelector ());
135
150
136
151
/** @var DOMNodeList $elements */
@@ -140,11 +155,15 @@ function (Rule $rule) use ($xPath) {
140
155
return false ;
141
156
}
142
157
158
+ $ this ->cachedRules [$ cssIdentifier ][$ rule ->getSelector ()] = true ;
159
+
143
160
return true ;
144
161
}
145
162
);
146
163
147
164
165
+ $ this ->resultCache ->save ('cachedRules ' , $ this ->cachedRules );
166
+
148
167
return $ applicable_rules ;
149
168
}
150
169
@@ -173,6 +192,11 @@ public function purgeCssStore()
173
192
return $ this ;
174
193
}
175
194
195
+ /**
196
+ * @param string $selector
197
+ *
198
+ * @return false|string
199
+ */
176
200
private function buildExpressionForSelector (string $ selector )
177
201
{
178
202
0 commit comments