Skip to content

Commit f3455aa

Browse files
committed
Cache rules further by storing the combination of css/rules
1 parent 5bae038 commit f3455aa

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

src/CssFromHTMLExtractor.php

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,12 @@ class CssFromHTMLExtractor
3434
/** @var Cache */
3535
private $resultCache;
3636

37+
/** @var array */
38+
private $loadedfiles = [];
39+
40+
/** @var array */
41+
private $cachedRules = [];
42+
3743
/**
3844
* CssFromHTMLExtractor constructor.
3945
* @param Cache|null $resultCache
@@ -50,6 +56,7 @@ public function __construct(Cache $resultCache = null)
5056
$this->cssConverter = new CssSelectorConverter();
5157

5258
$this->resultCache = is_null($resultCache) ? new ArrayCache() : $resultCache;
59+
$this->cachedRules = (array)$resultCache->fetch('cachedRules');
5360
}
5461

5562
public function getCssStore()
@@ -68,6 +75,8 @@ public function getHtmlStore()
6875
public function addBaseRules($sourceCss)
6976
{
7077
$identifier = md5($sourceCss);
78+
79+
$this->loadedfiles[] = $identifier;
7180
if ($this->resultCache->contains($identifier)) {
7281
list($rules, $charset) = $this->resultCache->fetch($identifier);
7382
$this->rules = $rules;
@@ -128,9 +137,15 @@ public function extractCss($html)
128137

129138
$xPath = new DOMXPath($document);
130139

140+
$cssIdentifier = join('-', $this->loadedfiles);
141+
131142
$applicable_rules = array_filter(
132143
$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+
134149
$expression = $this->buildExpressionForSelector($rule->getSelector());
135150

136151
/** @var DOMNodeList $elements */
@@ -140,11 +155,15 @@ function (Rule $rule) use ($xPath) {
140155
return false;
141156
}
142157

158+
$this->cachedRules[$cssIdentifier][$rule->getSelector()] = true;
159+
143160
return true;
144161
}
145162
);
146163

147164

165+
$this->resultCache->save('cachedRules', $this->cachedRules);
166+
148167
return $applicable_rules;
149168
}
150169

@@ -173,6 +192,11 @@ public function purgeCssStore()
173192
return $this;
174193
}
175194

195+
/**
196+
* @param string $selector
197+
*
198+
* @return false|string
199+
*/
176200
private function buildExpressionForSelector(string $selector)
177201
{
178202

0 commit comments

Comments
 (0)