8000 [CssSelector] Added cache on top of CssSelectorConverter · symfony/symfony@edec12f · GitHub
[go: up one dir, main page]

Skip to content

Commit edec12f

Browse files
committed
[CssSelector] Added cache on top of CssSelectorConverter
1 parent 07818f2 commit edec12f

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

src/Symfony/Component/CssSelector/CssSelectorConverter.php

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,16 +27,25 @@
2727
class CssSelectorConverter
2828
{
2929
private $translator;
30+
private $html;
31+
private $cache;
32+
33+
private static $xmlCache = [];
34+
private static $htmlCache = [];
3035

3136
/**
3237
* @param bool $html Whether HTML support should be enabled. Disable it for XML documents
3338
*/
3439
public function __construct(bool $html = true)
3540
{
3641
$this->translator = new Translator();
42+
$this->html = $html;
3743

38-
if ($html) {
44+
if ($this->html) {
3945
$this->translator->registerExtension(new HtmlExtension($this->translator));
46+
$this->cache = &self::$htmlCache;
47+
} else {
48+
$this->cache = &self::$xmlCache;
4049
}
4150

4251
$this->translator
@@ -57,6 +66,10 @@ public function __construct(bool $html = true)
5766
*/
5867
public function toXPath(string $cssExpr, string $prefix = 'descendant-or-self::')
5968
{
60-
return $this->translator->cssToXPath($cssExpr, $prefix);
69+
if ($this->cache[$prefix][$cssExpr] ?? false) {
70+
return $this->cache[$prefix][$cssExpr];
71+
}
72+
73+
return $this->cache[$prefix][$cssExpr] = $this->translator->cssToXPath($cssExpr, $prefix);
6174
}
6275
}

src/Symfony/Component/CssSelector/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)
0