Skip to content

Commit 73fc6ae

Browse files
committed
[CssSelector] Added cache on top of CssSelectorConverter
1 parent 8f47ba2 commit 73fc6ae

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

CssSelectorConverter.php

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,10 @@
2727
class CssSelectorConverter
2828
{
2929
private $translator;
30+
private $cache;
31+
32+
private static $xmlCache = [];
33+
private static $htmlCache = [];
3034

3135
/**
3236
* @param bool $html Whether HTML support should be enabled. Disable it for XML documents
@@ -37,6 +41,9 @@ public function __construct(bool $html = true)
3741

3842
if ($html) {
3943
$this->translator->registerExtension(new HtmlExtension($this->translator));
44+
$this->cache = &self::$htmlCache;
45+
} else {
46+
$this->cache = &self::$xmlCache;
4047
}
4148

4249
$this->translator
@@ -57,6 +64,6 @@ public function __construct(bool $html = true)
5764
*/
5865
public function toXPath(string $cssExpr, string $prefix = 'descendant-or-self::')
5966
{
60-
return $this->translator->cssToXPath($cssExpr, $prefix);
67+
return $this->cache[$prefix][$cssExpr] ?? $this->cache[$prefix][$cssExpr] = $this->translator->cssToXPath($cssExpr, $prefix);
6168
}
6269
}

Tests/CssSelectorConverterTest.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,21 @@ public function testCssToXPath()
2626
$this->assertEquals("descendant-or-self::h1[@class and contains(concat(' ', normalize-space(@class), ' '), ' foo ')]", $converter->toXPath('h1.foo'));
2727
$this->assertEquals('descendant-or-self::foo:h1', $converter->toXPath('foo|h1'));
2828
$this->assertEquals('descendant-or-self::h1', $converter->toXPath('H1'));
29+
30+
// Test the cache layer
31+
$converter = new CssSelectorConverter();
32+
$this->assertEquals('descendant-or-self::h1', $converter->toXPath('H1'));
2933
}
3034

3135
public function testCssToXPathXml()
3236
{
3337
$converter = new CssSelectorConverter(false);
3438

3539
$this->assertEquals('descendant-or-self::H1', $converter->toXPath('H1'));
40+
41+
$converter = new CssSelectorConverter(false);
42+
// Test the cache layer
43+
$this->assertEquals('descendant-or-self::H1', $converter->toXPath('H1'));
3644
}
3745

3846
public function testParseExceptions()

0 commit comments

Comments
 (0)