Skip to content

[CssSelector] Added cache on top of CssSelectorConverter #35425

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion src/Symfony/Component/CssSelector/CssSelectorConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@
class CssSelectorConverter
{
private $translator;
private $cache;

private static $xmlCache = [];
private static $htmlCache = [];

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

if ($html) {
$this->translator->registerExtension(new HtmlExtension($this->translator));
$this->cache = &self::$htmlCache;
} else {
$this->cache = &self::$xmlCache;
}

$this->translator
Expand All @@ -57,6 +64,6 @@ public function __construct(bool $html = true)
*/
public function toXPath(string $cssExpr, string $prefix = 'descendant-or-self::')
{
return $this->translator->cssToXPath($cssExpr, $prefix);
return $this->cache[$prefix][$cssExpr] ?? $this->cache[$prefix][$cssExpr] = $this->translator->cssToXPath($cssExpr, $prefix);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,21 @@ public function testCssToXPath()
$this->assertEquals("descendant-or-self::h1[@class and contains(concat(' ', normalize-space(@class), ' '), ' foo ')]", $converter->toXPath('h1.foo'));
$this->assertEquals('descendant-or-self::foo:h1', $converter->toXPath('foo|h1'));
$this->assertEquals('descendant-or-self::h1', $converter->toXPath('H1'));

// Test the cache layer
$converter = new CssSelectorConverter();
$this->assertEquals('descendant-or-self::h1', $converter->toXPath('H1'));
}

public function testCssToXPathXml()
{
$converter = new CssSelectorConverter(false);

$this->assertEquals('descendant-or-self::H1', $converter->toXPath('H1'));

$converter = new CssSelectorConverter(false);
// Test the cache layer
$this->assertEquals('descendant-or-self::H1', $converter->toXPath('H1'));
}

public function testParseExceptions()
Expand Down
5 changes: 5 additions & 0 deletions src/Symfony/Component/DomCrawler/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

5.1.0
-----

* Added an internal cache layer on top of the CssSelectorConverter

5.0.0
-----

Expand Down