diff --git a/src/CssToInlineStyles.php b/src/CssToInlineStyles.php index 5f9052b..b29814f 100644 --- a/src/CssToInlineStyles.php +++ b/src/CssToInlineStyles.php @@ -143,6 +143,8 @@ protected function inline(\DOMDocument $document, array $rules) return $document; } + $propertyStorage = new \SplObjectStorage(); + $xPath = new \DOMXPath($document); foreach ($rules as $rule) { try { @@ -163,20 +165,15 @@ protected function inline(\DOMDocument $document, array $rules) } foreach ($elements as $element) { - $this->calculatePropertiesToBeApplied($element, $rule->getProperties()); + $propertyStorage[$element] = $this->calculatePropertiesToBeApplied( + $rule->getProperties(), + $propertyStorage->contains($element) ? $propertyStorage[$element] : array() + ); } } - $elements = $xPath->query('//*[@data-css-to-inline-styles]'); - - foreach ($elements as $element) { - $propertiesToBeApplied = $element->attributes->getNamedItem('data-css-to-inline-styles'); - $element->removeAttribute('data-css-to-inline-styles'); - - if ($propertiesToBeApplied !== null) { - $properties = unserialize(base64_decode($propertiesToBeApplied->value)); - $this->inlineCssOnElement($element, $properties); - } + foreach ($propertyStorage as $element) { + $this->inlineCssOnElement($element, $propertyStorage[$element]); } return $document; @@ -185,31 +182,15 @@ protected function inline(\DOMDocument $document, array $rules) /** * Store the calculated values in a temporary data-attribute * - * @param \DOMElement $element * @param Css\Property\Property[] $properties - * @return \DOMElement + * @param Css\Property\Property[] $cssProperties existing applied properties indexed by name + * + * @return Css\Property\Property[] updated properties, indexed by name */ - private function calculatePropertiesToBeApplied( - \DOMElement $element, - array $properties - ) { + private function calculatePropertiesToBeApplied(array $properties, array $cssProperties) + { if (empty($properties)) { - return $element; - } - - $cssProperties = array(); - $currentStyles = $element->attributes->getNamedItem('data-css-to-inline-styles'); - - if ($currentStyles !== null) { - $currentProperties = unserialize( - base64_decode( - $currentStyles->value - ) - ); - - foreach ($currentProperties as $property) { - $cssProperties[$property->getName()] = $property; - } + return $cssProperties; } foreach ($properties as $property) { @@ -237,15 +218,6 @@ private function calculatePropertiesToBeApplied( } } - $element->setAttribute( - 'data-css-to-inline-styles', - base64_encode( - serialize( - array_values($cssProperties) - ) - ) - ); - - return $element; + return $cssProperties; } }