From ba64b1908afa6178f22ec0217e9b21e586f71384 Mon Sep 17 00:00:00 2001 From: Christophe Coevoet Date: Fri, 22 Jul 2016 15:31:32 +0200 Subject: [PATCH] Reuse the same CssSelectorConverter 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. --- src/CssToInlineStyles.php | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/CssToInlineStyles.php b/src/CssToInlineStyles.php index 5f9052b..37a97a7 100644 --- a/src/CssToInlineStyles.php +++ b/src/CssToInlineStyles.php @@ -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 * @@ -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) {