Skip to content

Commit

Permalink
Reuse the same CssSelectorConverter
Browse files Browse the repository at this point in the history
Initializing the CSS converter is a bit heavy. Reusing the same instance
for all rules instead of creating a new one each time leads to a major
performance boost (-20% time spent when running the example).
This optimization is possible only when using the Symfony CssSelector
component 2.8+. The old API from Symfony 2.7 and older does not allow to
perform it, as it exposes only a static method.
  • Loading branch information
stof committed Jul 22, 2016
1 parent b081b74 commit ba64b19
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions src/CssToInlineStyles.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,15 @@

class CssToInlineStyles
{
private $cssConverter;

public function __construct()
{
if (class_exists('Symfony\Component\CssSelector\CssSelectorConverter')) {
$this->cssConverter = new CssSelectorConverter();
}
}

/**
* Will inline the $css into the given $html
*
Expand Down Expand Up @@ -146,10 +155,10 @@ protected function inline(\DOMDocument $document, array $rules)
$xPath = new \DOMXPath($document);
foreach ($rules as $rule) {
try {
if (class_exists('Symfony\Component\CssSelector\CssSelectorConverter')) {
$converter = new CssSelectorConverter();
$expression = $converter->toXPath($rule->getSelector());
if (null !== $this->cssConverter) {
$expression = $this->cssConverter->toXPath($rule->getSelector());
} else {
// Compatibility layer for Symfony 2.7 and older
$expression = CssSelector::toXPath($rule->getSelector());
}
} catch (ExceptionInterface $e) {
Expand Down

0 comments on commit ba64b19

Please sign in to comment.