22
33namespace CSSFromHTMLExtractor ;
44
5+ use Doctrine \Common \Cache \ArrayCache ;
6+ use Doctrine \Common \Cache \Cache ;
57use DOMNodeList ;
68use Exception ;
79use Symfony \Component \CssSelector \CssSelectorConverter ;
@@ -28,10 +30,14 @@ class CssFromHTMLExtractor
2830 /** @var HtmlStore */
2931 private $ htmlStore ;
3032
33+ /** @var Cache */
34+ private $ resultCache ;
35+
3136 /**
3237 * CssFromHTMLExtractor constructor.
38+ * @param Cache|null $resultCache
3339 */
34- public function __construct ()
40+ public function __construct (Cache $ resultCache = null )
3541 {
3642 if (class_exists ('Symfony\Component\CssSelector\CssSelectorConverter ' )) {
3743 $ this ->cssConverter = new CssSelectorConverter ();
@@ -41,6 +47,8 @@ public function __construct()
4147 $ this ->htmlStore = new HtmlStore ();
4248 $ this ->processor = new Processor ();
4349 $ this ->cssConverter = new CssSelectorConverter ();
50+
51+ $ this ->resultCache = is_null ($ resultCache ) ? new ArrayCache () : $ resultCache ;
4452 }
4553
4654 public function getCssStore ()
@@ -58,8 +66,21 @@ public function getHtmlStore()
5866 */
5967 public function addBaseRules ($ sourceCss )
6068 {
61- $ this ->rules = $ this ->processor ->getRules ($ sourceCss , $ this ->rules );
62- $ this ->getCssStore ()->setCharset ($ this ->processor ->getCharset ($ sourceCss ));
69+ $ identifier = md5 ($ sourceCss );
70+ if ($ this ->resultCache ->contains ($ identifier )) {
71+ list ($ rules , $ charset ) = $ this ->resultCache ->fetch ($ identifier );
72+ $ this ->rules = $ rules ;
73+ $ this ->getCssStore ()->setCharset ($ charset );
74+
75+ return ;
76+ }
77+
78+ $ results = [$ this ->processor ->getRules ($ sourceCss , $ this ->rules ), $ this ->processor ->getCharset ($ sourceCss )];
79+
80+ $ this ->rules = $ results [0 ];
81+ $ this ->getCssStore ()->setCharset ($ results [1 ]);
82+
83+ $ this ->resultCache ->save ($ identifier , $ results );
6384 }
6485
6586 public function buildExtractedRuleSet ()
0 commit comments