Skip to content

Commit

Permalink
Refactor the storage of the computed properties
Browse files Browse the repository at this point in the history
  • Loading branch information
stof committed Jul 22, 2016
1 parent b081b74 commit c8dad9f
Showing 1 changed file with 15 additions and 43 deletions.
58 changes: 15 additions & 43 deletions src/CssToInlineStyles.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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;
Expand All @@ -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) {
Expand Down Expand Up @@ -237,15 +218,6 @@ private function calculatePropertiesToBeApplied(
}
}

$element->setAttribute(
'data-css-to-inline-styles',
base64_encode(
serialize(
array_values($cssProperties)
)
)
);

return $element;
return $cssProperties;
}
}

0 comments on commit c8dad9f

Please sign in to comment.