3 declare(strict_types=1);
5 namespace Pelago\Emogrifier\HtmlProcessor;
8 * This HtmlProcessor can convert style HTML attributes to the corresponding other visual HTML attributes,
9 * e.g. it converts style="width: 100px" to width="100".
11 * It will only add attributes, but leaves the style attribute untouched.
13 * To trigger the conversion, call the convertCssToVisualAttributes method.
15 * @author Oliver Klee <github@oliverklee.de>
17 class CssToAttributeConverter extends AbstractHtmlProcessor
20 * This multi-level array contains simple mappings of CSS properties to
21 * HTML attributes. If a mapping only applies to certain HTML nodes or
22 * only for certain values, the mapping is an object with a whitelist
23 * of nodes and values.
27 private $cssToHtmlMap = [
28 'background-color' => [
29 'attribute' => 'bgcolor',
32 'attribute' => 'align',
33 'nodes' => ['p', 'div', 'td'],
34 'values' => ['left', 'right', 'center', 'justify'],
37 'attribute' => 'align',
38 'nodes' => ['table', 'img'],
39 'values' => ['left', 'right'],
42 'attribute' => 'cellspacing',
50 private static $parsedCssCache = [];
53 * Maps the CSS from the style nodes to visual HTML attributes.
55 * @return self fluent interface
57 public function convertCssToVisualAttributes(): self
59 /** @var \DOMElement $node */
60 foreach ($this->getAllNodesWithStyleAttribute() as $node) {
61 $inlineStyleDeclarations = $this->parseCssDeclarationsBlock($node->getAttribute('style'));
62 $this->mapCssToHtmlAttributes($inlineStyleDeclarations, $node);
69 * Returns a list with all DOM nodes that have a style attribute.
71 * @return \DOMNodeList
73 private function getAllNodesWithStyleAttribute(): \DOMNodeList
75 return $this->xPath->query('//*[@style]');
79 * Parses a CSS declaration block into property name/value pairs.
83 * The declaration block
85 * "color: #000; font-weight: bold;"
87 * will be parsed into the following array:
90 * "font-weight" => "bold"
92 * @param string $cssDeclarationsBlock the CSS declarations block without the curly braces, may be empty
95 * the CSS declarations with the property names as array keys and the property values as array values
97 private function parseCssDeclarationsBlock(string $cssDeclarationsBlock): array
99 if (isset(self::$parsedCssCache[$cssDeclarationsBlock])) {
100 return self::$parsedCssCache[$cssDeclarationsBlock];
104 foreach (\preg_split('/;(?!base64|charset)/', $cssDeclarationsBlock) as $declaration) {
106 if (!\preg_match('/^([A-Za-z\\-]+)\\s*:\\s*(.+)$/s', \trim($declaration), $matches)) {
110 $propertyName = \strtolower($matches[1]);
111 $propertyValue = $matches[2];
112 $properties[$propertyName] = $propertyValue;
114 self::$parsedCssCache[$cssDeclarationsBlock] = $properties;
120 * Applies $styles to $node.
122 * This method maps CSS styles to HTML attributes and adds those to the
125 * @param string[] $styles the new CSS styles taken from the global styles to be applied to this node
126 * @param \DOMElement $node node to apply styles to
128 private function mapCssToHtmlAttributes(array $styles, \DOMElement $node): void
130 foreach ($styles as $property => $value) {
131 // Strip !important indicator
132 $value = \trim(\str_replace('!important', '', $value));
133 $this->mapCssToHtmlAttribute($property, $value, $node);
138 * Tries to apply the CSS style to $node as an attribute.
140 * This method maps a CSS rule to HTML attributes and adds those to the node.
142 * @param string $property the name of the CSS property to map
143 * @param string $value the value of the style rule to map
144 * @param \DOMElement $node node to apply styles to
146 private function mapCssToHtmlAttribute(string $property, string $value, \DOMElement $node): void
148 if (!$this->mapSimpleCssProperty($property, $value, $node)) {
149 $this->mapComplexCssProperty($property, $value, $node);
154 * Looks up the CSS property in the mapping table and maps it if it matches the conditions.
156 * @param string $property the name of the CSS property to map
157 * @param string $value the value of the style rule to map
158 * @param \DOMElement $node node to apply styles to
160 * @return bool true if the property can be mapped using the simple mapping table
162 private function mapSimpleCssProperty(string $property, string $value, \DOMElement $node): bool
164 if (!isset($this->cssToHtmlMap[$property])) {
168 $mapping = $this->cssToHtmlMap[$property];
169 $nodesMatch = !isset($mapping['nodes']) || \in_array($node->nodeName, $mapping['nodes'], true);
170 $valuesMatch = !isset($mapping['values']) || \in_array($value, $mapping['values'], true);
171 $canBeMapped = $nodesMatch && $valuesMatch;
173 $node->setAttribute($mapping['attribute'], $value);
180 * Maps CSS properties that need special transformation to an HTML attribute.
182 * @param string $property the name of the CSS property to map
183 * @param string $value the value of the style rule to map
184 * @param \DOMElement $node node to apply styles to
186 private function mapComplexCssProperty(string $property, string $value, \DOMElement $node): void
190 $this->mapBackgroundProperty($node, $value);
193 // intentional fall-through
195 $this->mapWidthOrHeightProperty($node, $value, $property);
198 $this->mapMarginProperty($node, $value);
201 $this->mapBorderProperty($node, $value);
208 * @param \DOMElement $node node to apply styles to
209 * @param string $value the value of the style rule to map
211 private function mapBackgroundProperty(\DOMElement $node, string $value): void
213 // parse out the color, if any
214 $styles = \explode(' ', $value, 2);
216 if (\is_numeric($first[0]) || \strncmp($first, 'url', 3) === 0) {
220 // as this is not a position or image, assume it's a color
221 $node->setAttribute('bgcolor', $first);
225 * @param \DOMElement $node node to apply styles to
226 * @param string $value the value of the style rule to map
227 * @param string $property the name of the CSS property to map
229 private function mapWidthOrHeightProperty(\DOMElement $node, string $value, string $property): void
231 // only parse values in px and %, but not values like "auto"
232 if (!\preg_match('/^(\\d+)(\\.(\\d+))?(px|%)$/', $value)) {
236 $number = \preg_replace('/[^0-9.%]/', '', $value);
237 $node->setAttribute($property, $number);
241 * @param \DOMElement $node node to apply styles to
242 * @param string $value the value of the style rule to map
244 private function mapMarginProperty(\DOMElement $node, string $value): void
246 if (!$this->isTableOrImageNode($node)) {
250 $margins = $this->parseCssShorthandValue($value);
251 if ($margins['left'] === 'auto' && $margins['right'] === 'auto') {
252 $node->setAttribute('align', 'center');
257 * @param \DOMElement $node node to apply styles to
258 * @param string $value the value of the style rule to map
260 private function mapBorderProperty(\DOMElement $node, string $value): void
262 if (!$this->isTableOrImageNode($node)) {
266 if ($value === 'none' || $value === '0') {
267 $node->setAttribute('border', '0');
272 * @param \DOMElement $node
276 private function isTableOrImageNode(\DOMElement $node): bool
278 return $node->nodeName === 'table' || $node->nodeName === 'img';
282 * Parses a shorthand CSS value and splits it into individual values
284 * @param string $value a string of CSS value with 1, 2, 3 or 4 sizes
285 * For example: padding: 0 auto; '0 auto' is split into top: 0, left: auto, bottom: 0, right: auto.
287 * @return string[] an array of values for top, right, bottom and left (using these as associative array keys)
289 private function parseCssShorthandValue(string $value): array
291 /** @var string[] $values */
292 $values = \preg_split('/\\s+/', $value);
295 $css['top'] = $values[0];
296 $css['right'] = (\count($values) > 1) ? $values[1] : $css['top'];
297 $css['bottom'] = (\count($values) > 2) ? $values[2] : $css['top'];
298 $css['left'] = (\count($values) > 3) ? $values[3] : $css['right'];