Caching
4 years ago
Css
4 years ago
HtmlProcessor
4 years ago
Utilities
4 years ago
CssInliner.php
4 years ago
CssInliner.php
1197 lines
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Pelago\Emogrifier; |
| 6 | |
| 7 | use Pelago\Emogrifier\Css\CssDocument; |
| 8 | use Pelago\Emogrifier\HtmlProcessor\AbstractHtmlProcessor; |
| 9 | use Pelago\Emogrifier\Utilities\CssConcatenator; |
| 10 | use Symfony\Component\CssSelector\CssSelectorConverter; |
| 11 | use Symfony\Component\CssSelector\Exception\ParseException; |
| 12 | |
| 13 | /** |
| 14 | * This class provides functions for converting CSS styles into inline style attributes in your HTML code. |
| 15 | */ |
| 16 | class CssInliner extends AbstractHtmlProcessor |
| 17 | { |
| 18 | /** |
| 19 | * @var int |
| 20 | */ |
| 21 | private const CACHE_KEY_SELECTOR = 0; |
| 22 | |
| 23 | /** |
| 24 | * @var int |
| 25 | */ |
| 26 | private const CACHE_KEY_CSS_DECLARATIONS_BLOCK = 1; |
| 27 | |
| 28 | /** |
| 29 | * @var int |
| 30 | */ |
| 31 | private const CACHE_KEY_COMBINED_STYLES = 2; |
| 32 | |
| 33 | /** |
| 34 | * Regular expression component matching a static pseudo class in a selector, without the preceding ":", |
| 35 | * for which the applicable elements can be determined (by converting the selector to an XPath expression). |
| 36 | * (Contains alternation without a group and is intended to be placed within a capturing, non-capturing or lookahead |
| 37 | * group, as appropriate for the usage context.) |
| 38 | * |
| 39 | * @var string |
| 40 | */ |
| 41 | private const PSEUDO_CLASS_MATCHER |
| 42 | = 'empty|(?:first|last|nth(?:-last)?+|only)-(?:child|of-type)|not\\([[:ascii:]]*\\)'; |
| 43 | |
| 44 | /** |
| 45 | * This regular expression componenet matches an `...of-type` pseudo class name, without the preceding ":". These |
| 46 | * pseudo-classes can currently online be inlined if they have an associated type in the selector expression. |
| 47 | * |
| 48 | * @var string |
| 49 | */ |
| 50 | private const OF_TYPE_PSEUDO_CLASS_MATCHER = '(?:first|last|nth(?:-last)?+|only)-of-type'; |
| 51 | |
| 52 | /** |
| 53 | * regular expression component to match a selector combinator |
| 54 | * |
| 55 | * @var string |
| 56 | */ |
| 57 | private const COMBINATOR_MATCHER = '(?:\\s++|\\s*+[>+~]\\s*+)(?=[[:alpha:]_\\-.#*:\\[])'; |
| 58 | |
| 59 | /** |
| 60 | * @var array<string, bool> |
| 61 | */ |
| 62 | private $excludedSelectors = []; |
| 63 | |
| 64 | /** |
| 65 | * @var array<string, bool> |
| 66 | */ |
| 67 | private $allowedMediaTypes = ['all' => true, 'screen' => true, 'print' => true]; |
| 68 | |
| 69 | /** |
| 70 | * @var array{ |
| 71 | * 0: array<string, int>, |
| 72 | * 1: array<string, array<string, string>>, |
| 73 | * 2: array<string, string> |
| 74 | * } |
| 75 | */ |
| 76 | private $caches = [ |
| 77 | self::CACHE_KEY_SELECTOR => [], |
| 78 | self::CACHE_KEY_CSS_DECLARATIONS_BLOCK => [], |
| 79 | self::CACHE_KEY_COMBINED_STYLES => [], |
| 80 | ]; |
| 81 | |
| 82 | /** |
| 83 | * @var ?CssSelectorConverter |
| 84 | */ |
| 85 | private $cssSelectorConverter = null; |
| 86 | |
| 87 | /** |
| 88 | * the visited nodes with the XPath paths as array keys |
| 89 | * |
| 90 | * @var array<string, \DOMElement> |
| 91 | */ |
| 92 | private $visitedNodes = []; |
| 93 | |
| 94 | /** |
| 95 | * the styles to apply to the nodes with the XPath paths as array keys for the outer array |
| 96 | * and the attribute names/values as key/value pairs for the inner array |
| 97 | * |
| 98 | * @var array<string, array<string, string>> |
| 99 | */ |
| 100 | private $styleAttributesForNodes = []; |
| 101 | |
| 102 | /** |
| 103 | * Determines whether the "style" attributes of tags in the the HTML passed to this class should be preserved. |
| 104 | * If set to false, the value of the style attributes will be discarded. |
| 105 | * |
| 106 | * @var bool |
| 107 | */ |
| 108 | private $isInlineStyleAttributesParsingEnabled = true; |
| 109 | |
| 110 | /** |
| 111 | * Determines whether the `<style>` blocks in the HTML passed to this class should be parsed. |
| 112 | * |
| 113 | * If set to true, the `<style>` blocks will be removed from the HTML and their contents will be applied to the HTML |
| 114 | * via inline styles. |
| 115 | * |
| 116 | * If set to false, the `<style>` blocks will be left as they are in the HTML. |
| 117 | * |
| 118 | * @var bool |
| 119 | */ |
| 120 | private $isStyleBlocksParsingEnabled = true; |
| 121 | |
| 122 | /** |
| 123 | * For calculating selector precedence order. |
| 124 | * Keys are a regular expression part to match before a CSS name. |
| 125 | * Values are a multiplier factor per match to weight specificity. |
| 126 | * |
| 127 | * @var array<string, int> |
| 128 | */ |
| 129 | private $selectorPrecedenceMatchers = [ |
| 130 | // IDs: worth 10000 |
| 131 | '\\#' => 10000, |
| 132 | // classes, attributes, pseudo-classes (not pseudo-elements) except `:not`: worth 100 |
| 133 | '(?:\\.|\\[|(?<!:):(?!not\\())' => 100, |
| 134 | // elements (not attribute values or `:not`), pseudo-elements: worth 1 |
| 135 | '(?:(?<![="\':\\w\\-])|::)' => 1, |
| 136 | ]; |
| 137 | |
| 138 | /** |
| 139 | * array of data describing CSS rules which apply to the document but cannot be inlined, in the format returned by |
| 140 | * {@see collateCssRules} |
| 141 | * |
| 142 | * @var array<array-key, array{ |
| 143 | * media: string, |
| 144 | * selector: string, |
| 145 | * hasUnmatchablePseudo: bool, |
| 146 | * declarationsBlock: string, |
| 147 | * line: int |
| 148 | * }>|null |
| 149 | */ |
| 150 | private $matchingUninlinableCssRules = null; |
| 151 | |
| 152 | /** |
| 153 | * Emogrifier will throw Exceptions when it encounters an error instead of silently ignoring them. |
| 154 | * |
| 155 | * @var bool |
| 156 | */ |
| 157 | private $debug = false; |
| 158 | |
| 159 | /** |
| 160 | * Inlines the given CSS into the existing HTML. |
| 161 | * |
| 162 | * @param string $css the CSS to inline, must be UTF-8-encoded |
| 163 | * |
| 164 | * @return self fluent interface |
| 165 | * |
| 166 | * @throws ParseException in debug mode, if an invalid selector is encountered |
| 167 | * @throws \RuntimeException in debug mode, if an internal PCRE error occurs |
| 168 | */ |
| 169 | public function inlineCss(string $css = ''): self |
| 170 | { |
| 171 | $this->clearAllCaches(); |
| 172 | $this->purgeVisitedNodes(); |
| 173 | |
| 174 | $this->normalizeStyleAttributesOfAllNodes(); |
| 175 | |
| 176 | $combinedCss = $css; |
| 177 | // grab any existing style blocks from the HTML and append them to the existing CSS |
| 178 | // (these blocks should be appended so as to have precedence over conflicting styles in the existing CSS) |
| 179 | if ($this->isStyleBlocksParsingEnabled) { |
| 180 | $combinedCss .= $this->getCssFromAllStyleNodes(); |
| 181 | } |
| 182 | $parsedCss = new CssDocument($combinedCss); |
| 183 | |
| 184 | $excludedNodes = $this->getNodesToExclude(); |
| 185 | $cssRules = $this->collateCssRules($parsedCss); |
| 186 | $cssSelectorConverter = $this->getCssSelectorConverter(); |
| 187 | foreach ($cssRules['inlinable'] as $cssRule) { |
| 188 | try { |
| 189 | $nodesMatchingCssSelectors = $this->getXPath() |
| 190 | ->query($cssSelectorConverter->toXPath($cssRule['selector'])); |
| 191 | |
| 192 | /** @var \DOMElement $node */ |
| 193 | foreach ($nodesMatchingCssSelectors as $node) { |
| 194 | if (\in_array($node, $excludedNodes, true)) { |
| 195 | continue; |
| 196 | } |
| 197 | $this->copyInlinableCssToStyleAttribute($node, $cssRule); |
| 198 | } |
| 199 | } catch (ParseException $e) { |
| 200 | if ($this->debug) { |
| 201 | throw $e; |
| 202 | } |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | if ($this->isInlineStyleAttributesParsingEnabled) { |
| 207 | $this->fillStyleAttributesWithMergedStyles(); |
| 208 | } |
| 209 | |
| 210 | $this->removeImportantAnnotationFromAllInlineStyles(); |
| 211 | |
| 212 | $this->determineMatchingUninlinableCssRules($cssRules['uninlinable']); |
| 213 | $this->copyUninlinableCssToStyleNode($parsedCss); |
| 214 | |
| 215 | return $this; |
| 216 | } |
| 217 | |
| 218 | /** |
| 219 | * Disables the parsing of inline styles. |
| 220 | * |
| 221 | * @return self fluent interface |
| 222 | */ |
| 223 | public function disableInlineStyleAttributesParsing(): self |
| 224 | { |
| 225 | $this->isInlineStyleAttributesParsingEnabled = false; |
| 226 | |
| 227 | return $this; |
| 228 | } |
| 229 | |
| 230 | /** |
| 231 | * Disables the parsing of `<style>` blocks. |
| 232 | * |
| 233 | * @return self fluent interface |
| 234 | */ |
| 235 | public function disableStyleBlocksParsing(): self |
| 236 | { |
| 237 | $this->isStyleBlocksParsingEnabled = false; |
| 238 | |
| 239 | return $this; |
| 240 | } |
| 241 | |
| 242 | /** |
| 243 | * Marks a media query type to keep. |
| 244 | * |
| 245 | * @param string $mediaName the media type name, e.g., "braille" |
| 246 | * |
| 247 | * @return self fluent interface |
| 248 | */ |
| 249 | public function addAllowedMediaType(string $mediaName): self |
| 250 | { |
| 251 | $this->allowedMediaTypes[$mediaName] = true; |
| 252 | |
| 253 | return $this; |
| 254 | } |
| 255 | |
| 256 | /** |
| 257 | * Drops a media query type from the allowed list. |
| 258 | * |
| 259 | * @param string $mediaName the tag name, e.g., "braille" |
| 260 | * |
| 261 | * @return self fluent interface |
| 262 | */ |
| 263 | public function removeAllowedMediaType(string $mediaName): self |
| 264 | { |
| 265 | if (isset($this->allowedMediaTypes[$mediaName])) { |
| 266 | unset($this->allowedMediaTypes[$mediaName]); |
| 267 | } |
| 268 | |
| 269 | return $this; |
| 270 | } |
| 271 | |
| 272 | /** |
| 273 | * Adds a selector to exclude nodes from emogrification. |
| 274 | * |
| 275 | * Any nodes that match the selector will not have their style altered. |
| 276 | * |
| 277 | * @param string $selector the selector to exclude, e.g., ".editor" |
| 278 | * |
| 279 | * @return self fluent interface |
| 280 | */ |
| 281 | public function addExcludedSelector(string $selector): self |
| 282 | { |
| 283 | $this->excludedSelectors[$selector] = true; |
| 284 | |
| 285 | return $this; |
| 286 | } |
| 287 | |
| 288 | /** |
| 289 | * No longer excludes the nodes matching this selector from emogrification. |
| 290 | * |
| 291 | * @param string $selector the selector to no longer exclude, e.g., ".editor" |
| 292 | * |
| 293 | * @return self fluent interface |
| 294 | */ |
| 295 | public function removeExcludedSelector(string $selector): self |
| 296 | { |
| 297 | if (isset($this->excludedSelectors[$selector])) { |
| 298 | unset($this->excludedSelectors[$selector]); |
| 299 | } |
| 300 | |
| 301 | return $this; |
| 302 | } |
| 303 | |
| 304 | /** |
| 305 | * Sets the debug mode. |
| 306 | * |
| 307 | * @param bool $debug set to true to enable debug mode |
| 308 | * |
| 309 | * @return self fluent interface |
| 310 | */ |
| 311 | public function setDebug(bool $debug): self |
| 312 | { |
| 313 | $this->debug = $debug; |
| 314 | |
| 315 | return $this; |
| 316 | } |
| 317 | |
| 318 | /** |
| 319 | * Gets the array of selectors present in the CSS provided to `inlineCss()` for which the declarations could not be |
| 320 | * applied as inline styles, but which may affect elements in the HTML. The relevant CSS will have been placed in a |
| 321 | * `<style>` element. The selectors may include those used within `@media` rules or those involving dynamic |
| 322 | * pseudo-classes (such as `:hover`) or pseudo-elements (such as `::after`). |
| 323 | * |
| 324 | * @return array<array-key, string> |
| 325 | * |
| 326 | * @throws \BadMethodCallException if `inlineCss` has not been called first |
| 327 | */ |
| 328 | public function getMatchingUninlinableSelectors(): array |
| 329 | { |
| 330 | return \array_column($this->getMatchingUninlinableCssRules(), 'selector'); |
| 331 | } |
| 332 | |
| 333 | /** |
| 334 | * @return array<array-key, array{ |
| 335 | * media: string, |
| 336 | * selector: string, |
| 337 | * hasUnmatchablePseudo: bool, |
| 338 | * declarationsBlock: string, |
| 339 | * line: int |
| 340 | * }> |
| 341 | * |
| 342 | * @throws \BadMethodCallException if `inlineCss` has not been called first |
| 343 | */ |
| 344 | private function getMatchingUninlinableCssRules(): array |
| 345 | { |
| 346 | if (!\is_array($this->matchingUninlinableCssRules)) { |
| 347 | throw new \BadMethodCallException('inlineCss must be called first', 1568385221); |
| 348 | } |
| 349 | |
| 350 | return $this->matchingUninlinableCssRules; |
| 351 | } |
| 352 | |
| 353 | /** |
| 354 | * Clears all caches. |
| 355 | */ |
| 356 | private function clearAllCaches(): void |
| 357 | { |
| 358 | $this->caches = [ |
| 359 | self::CACHE_KEY_SELECTOR => [], |
| 360 | self::CACHE_KEY_CSS_DECLARATIONS_BLOCK => [], |
| 361 | self::CACHE_KEY_COMBINED_STYLES => [], |
| 362 | ]; |
| 363 | } |
| 364 | |
| 365 | /** |
| 366 | * Purges the visited nodes. |
| 367 | */ |
| 368 | private function purgeVisitedNodes(): void |
| 369 | { |
| 370 | $this->visitedNodes = []; |
| 371 | $this->styleAttributesForNodes = []; |
| 372 | } |
| 373 | |
| 374 | /** |
| 375 | * Parses the document and normalizes all existing CSS attributes. |
| 376 | * This changes 'DISPLAY: none' to 'display: none'. |
| 377 | * We wouldn't have to do this if DOMXPath supported XPath 2.0. |
| 378 | * Also stores a reference of nodes with existing inline styles so we don't overwrite them. |
| 379 | */ |
| 380 | private function normalizeStyleAttributesOfAllNodes(): void |
| 381 | { |
| 382 | /** @var \DOMElement $node */ |
| 383 | foreach ($this->getAllNodesWithStyleAttribute() as $node) { |
| 384 | if ($this->isInlineStyleAttributesParsingEnabled) { |
| 385 | $this->normalizeStyleAttributes($node); |
| 386 | } |
| 387 | // Remove style attribute in every case, so we can add them back (if inline style attributes |
| 388 | // parsing is enabled) to the end of the style list, thus keeping the right priority of CSS rules; |
| 389 | // else original inline style rules may remain at the beginning of the final inline style definition |
| 390 | // of a node, which may give not the desired results |
| 391 | $node->removeAttribute('style'); |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | /** |
| 396 | * Returns a list with all DOM nodes that have a style attribute. |
| 397 | * |
| 398 | * @return \DOMNodeList |
| 399 | * |
| 400 | * @throws \RuntimeException |
| 401 | */ |
| 402 | private function getAllNodesWithStyleAttribute(): \DOMNodeList |
| 403 | { |
| 404 | $query = '//*[@style]'; |
| 405 | $matches = $this->getXPath()->query($query); |
| 406 | if (!$matches instanceof \DOMNodeList) { |
| 407 | throw new \RuntimeException('XPatch query failed: ' . $query, 1618577797); |
| 408 | } |
| 409 | |
| 410 | return $matches; |
| 411 | } |
| 412 | |
| 413 | /** |
| 414 | * Normalizes the value of the "style" attribute and saves it. |
| 415 | * |
| 416 | * @param \DOMElement $node |
| 417 | */ |
| 418 | private function normalizeStyleAttributes(\DOMElement $node): void |
| 419 | { |
| 420 | $normalizedOriginalStyle = \preg_replace_callback( |
| 421 | '/-?+[_a-zA-Z][\\w\\-]*+(?=:)/S', |
| 422 | /** @param array<array-key, string> $propertyNameMatches */ |
| 423 | static function (array $propertyNameMatches): string { |
| 424 | return \strtolower($propertyNameMatches[0]); |
| 425 | }, |
| 426 | $node->getAttribute('style') |
| 427 | ); |
| 428 | |
| 429 | // In order to not overwrite existing style attributes in the HTML, we have to save the original HTML styles. |
| 430 | $nodePath = $node->getNodePath(); |
| 431 | if (\is_string($nodePath) && !isset($this->styleAttributesForNodes[$nodePath])) { |
| 432 | $this->styleAttributesForNodes[$nodePath] = $this->parseCssDeclarationsBlock($normalizedOriginalStyle); |
| 433 | $this->visitedNodes[$nodePath] = $node; |
| 434 | } |
| 435 | |
| 436 | $node->setAttribute('style', $normalizedOriginalStyle); |
| 437 | } |
| 438 | |
| 439 | /** |
| 440 | * Parses a CSS declaration block into property name/value pairs. |
| 441 | * |
| 442 | * Example: |
| 443 | * |
| 444 | * The declaration block |
| 445 | * |
| 446 | * "color: #000; font-weight: bold;" |
| 447 | * |
| 448 | * will be parsed into the following array: |
| 449 | * |
| 450 | * "color" => "#000" |
| 451 | * "font-weight" => "bold" |
| 452 | * |
| 453 | * @param string $cssDeclarationsBlock the CSS declarations block without the curly braces, may be empty |
| 454 | * |
| 455 | * @return array<string, string> |
| 456 | * the CSS declarations with the property names as array keys and the property values as array values |
| 457 | */ |
| 458 | private function parseCssDeclarationsBlock(string $cssDeclarationsBlock): array |
| 459 | { |
| 460 | if (isset($this->caches[self::CACHE_KEY_CSS_DECLARATIONS_BLOCK][$cssDeclarationsBlock])) { |
| 461 | return $this->caches[self::CACHE_KEY_CSS_DECLARATIONS_BLOCK][$cssDeclarationsBlock]; |
| 462 | } |
| 463 | |
| 464 | $properties = []; |
| 465 | foreach (\preg_split('/;(?!base64|charset)/', $cssDeclarationsBlock) as $declaration) { |
| 466 | /** @var array<int, string> $matches */ |
| 467 | $matches = []; |
| 468 | if (!\preg_match('/^([A-Za-z\\-]+)\\s*:\\s*(.+)$/s', \trim($declaration), $matches)) { |
| 469 | continue; |
| 470 | } |
| 471 | |
| 472 | $propertyName = \strtolower($matches[1]); |
| 473 | $propertyValue = $matches[2]; |
| 474 | $properties[$propertyName] = $propertyValue; |
| 475 | } |
| 476 | $this->caches[self::CACHE_KEY_CSS_DECLARATIONS_BLOCK][$cssDeclarationsBlock] = $properties; |
| 477 | |
| 478 | return $properties; |
| 479 | } |
| 480 | |
| 481 | /** |
| 482 | * Returns CSS content. |
| 483 | * |
| 484 | * @return string |
| 485 | */ |
| 486 | private function getCssFromAllStyleNodes(): string |
| 487 | { |
| 488 | $styleNodes = $this->getXPath()->query('//style'); |
| 489 | if ($styleNodes === false) { |
| 490 | return ''; |
| 491 | } |
| 492 | |
| 493 | $css = ''; |
| 494 | foreach ($styleNodes as $styleNode) { |
| 495 | $css .= "\n\n" . $styleNode->nodeValue; |
| 496 | $parentNode = $styleNode->parentNode; |
| 497 | if ($parentNode instanceof \DOMNode) { |
| 498 | $parentNode->removeChild($styleNode); |
| 499 | } |
| 500 | } |
| 501 | |
| 502 | return $css; |
| 503 | } |
| 504 | |
| 505 | /** |
| 506 | * Find the nodes that are not to be emogrified. |
| 507 | * |
| 508 | * @return array<int, \DOMElement> |
| 509 | * |
| 510 | * @throws ParseException |
| 511 | * @throws \UnexpectedValueException |
| 512 | */ |
| 513 | private function getNodesToExclude(): array |
| 514 | { |
| 515 | $excludedNodes = []; |
| 516 | foreach (\array_keys($this->excludedSelectors) as $selectorToExclude) { |
| 517 | try { |
| 518 | $matchingNodes = $this->getXPath() |
| 519 | ->query($this->getCssSelectorConverter()->toXPath($selectorToExclude)); |
| 520 | |
| 521 | foreach ($matchingNodes as $node) { |
| 522 | if (!$node instanceof \DOMElement) { |
| 523 | $path = $node->getNodePath() ?? '$node'; |
| 524 | throw new \UnexpectedValueException($path . ' is not a DOMElement.', 1617975914); |
| 525 | } |
| 526 | $excludedNodes[] = $node; |
| 527 | } |
| 528 | } catch (ParseException $e) { |
| 529 | if ($this->debug) { |
| 530 | throw $e; |
| 531 | } |
| 532 | } |
| 533 | } |
| 534 | |
| 535 | return $excludedNodes; |
| 536 | } |
| 537 | |
| 538 | /** |
| 539 | * @return CssSelectorConverter |
| 540 | */ |
| 541 | private function getCssSelectorConverter(): CssSelectorConverter |
| 542 | { |
| 543 | if (!$this->cssSelectorConverter instanceof CssSelectorConverter) { |
| 544 | $this->cssSelectorConverter = new CssSelectorConverter(); |
| 545 | } |
| 546 | |
| 547 | return $this->cssSelectorConverter; |
| 548 | } |
| 549 | |
| 550 | /** |
| 551 | * Collates the individual rules from a `CssDocument` object. |
| 552 | * |
| 553 | * @param CssDocument $parsedCss |
| 554 | * |
| 555 | * @return array<string, array<array-key, array{ |
| 556 | * media: string, |
| 557 | * selector: string, |
| 558 | * hasUnmatchablePseudo: bool, |
| 559 | * declarationsBlock: string, |
| 560 | * line: int |
| 561 | * }>> |
| 562 | * This 2-entry array has the key "inlinable" containing rules which can be inlined as `style` attributes |
| 563 | * and the key "uninlinable" containing rules which cannot. Each value is an array of sub-arrays with the |
| 564 | * following keys: |
| 565 | * - "media" (the media query string, e.g. "@media screen and (max-width: 480px)", |
| 566 | * or an empty string if not from a `@media` rule); |
| 567 | * - "selector" (the CSS selector, e.g., "*" or "header h1"); |
| 568 | * - "hasUnmatchablePseudo" (`true` if that selector contains pseudo-elements or dynamic pseudo-classes such |
| 569 | * that the declarations cannot be applied inline); |
| 570 | * - "declarationsBlock" (the semicolon-separated CSS declarations for that selector, |
| 571 | * e.g., `color: red; height: 4px;`); |
| 572 | * - "line" (the line number, e.g. 42). |
| 573 | */ |
| 574 | private function collateCssRules(CssDocument $parsedCss): array |
| 575 | { |
| 576 | $matches = $parsedCss->getStyleRulesData(\array_keys($this->allowedMediaTypes)); |
| 577 | |
| 578 | $cssRules = [ |
| 579 | 'inlinable' => [], |
| 580 | 'uninlinable' => [], |
| 581 | ]; |
| 582 | foreach ($matches as $key => $cssRule) { |
| 583 | if (!$cssRule->hasAtLeastOneDeclaration()) { |
| 584 | continue; |
| 585 | } |
| 586 | |
| 587 | $mediaQuery = $cssRule->getContainingAtRule(); |
| 588 | $declarationsBlock = $cssRule->getDeclarationAsText(); |
| 589 | foreach ($cssRule->getSelectors() as $selector) { |
| 590 | // don't process pseudo-elements and behavioral (dynamic) pseudo-classes; |
| 591 | // only allow structural pseudo-classes |
| 592 | $hasPseudoElement = \strpos($selector, '::') !== false; |
| 593 | $hasUnmatchablePseudo = $hasPseudoElement || $this->hasUnsupportedPseudoClass($selector); |
| 594 | |
| 595 | $parsedCssRule = [ |
| 596 | 'media' => $mediaQuery, |
| 597 | 'selector' => $selector, |
| 598 | 'hasUnmatchablePseudo' => $hasUnmatchablePseudo, |
| 599 | 'declarationsBlock' => $declarationsBlock, |
| 600 | // keep track of where it appears in the file, since order is important |
| 601 | 'line' => $key, |
| 602 | ]; |
| 603 | $ruleType = (!$cssRule->hasContainingAtRule() && !$hasUnmatchablePseudo) ? 'inlinable' : 'uninlinable'; |
| 604 | $cssRules[$ruleType][] = $parsedCssRule; |
| 605 | } |
| 606 | } |
| 607 | |
| 608 | \usort( |
| 609 | $cssRules['inlinable'], |
| 610 | /** |
| 611 | * @param array{selector: string, line: int} $first |
| 612 | * @param array{selector: string, line: int} $second |
| 613 | */ |
| 614 | function (array $first, array $second): int { |
| 615 | return $this->sortBySelectorPrecedence($first, $second); |
| 616 | } |
| 617 | ); |
| 618 | |
| 619 | return $cssRules; |
| 620 | } |
| 621 | |
| 622 | /** |
| 623 | * Tests if a selector contains a pseudo-class which would mean it cannot be converted to an XPath expression for |
| 624 | * inlining CSS declarations. |
| 625 | * |
| 626 | * Any pseudo class that does not match {@see PSEUDO_CLASS_MATCHER} cannot be converted. Additionally, `...of-type` |
| 627 | * pseudo-classes cannot be converted if they are not associated with a type selector. |
| 628 | * |
| 629 | * @param string $selector |
| 630 | * |
| 631 | * @return bool |
| 632 | */ |
| 633 | private function hasUnsupportedPseudoClass(string $selector): bool |
| 634 | { |
| 635 | if (\preg_match('/:(?!' . self::PSEUDO_CLASS_MATCHER . ')[\\w\\-]/i', $selector)) { |
| 636 | return true; |
| 637 | } |
| 638 | |
| 639 | if (!\preg_match('/:(?:' . self::OF_TYPE_PSEUDO_CLASS_MATCHER . ')/i', $selector)) { |
| 640 | return false; |
| 641 | } |
| 642 | |
| 643 | foreach (\preg_split('/' . self::COMBINATOR_MATCHER . '/', $selector) as $selectorPart) { |
| 644 | if ($this->selectorPartHasUnsupportedOfTypePseudoClass($selectorPart)) { |
| 645 | return true; |
| 646 | } |
| 647 | } |
| 648 | |
| 649 | return false; |
| 650 | } |
| 651 | |
| 652 | /** |
| 653 | * Tests if part of a selector contains an `...of-type` pseudo-class such that it cannot be converted to an XPath |
| 654 | * expression. |
| 655 | * |
| 656 | * @param string $selectorPart part of a selector which has been split up at combinators |
| 657 | * |
| 658 | * @return bool `true` if the selector part does not have a type but does have an `...of-type` pseudo-class |
| 659 | */ |
| 660 | private function selectorPartHasUnsupportedOfTypePseudoClass(string $selectorPart): bool |
| 661 | { |
| 662 | if (\preg_match('/^[\\w\\-]/', $selectorPart)) { |
| 663 | return false; |
| 664 | } |
| 665 | |
| 666 | return (bool)\preg_match('/:(?:' . self::OF_TYPE_PSEUDO_CLASS_MATCHER . ')/i', $selectorPart); |
| 667 | } |
| 668 | |
| 669 | /** |
| 670 | * @param array{selector: string, line: int} $first |
| 671 | * @param array{selector: string, line: int} $second |
| 672 | * |
| 673 | * @return int |
| 674 | */ |
| 675 | private function sortBySelectorPrecedence(array $first, array $second): int |
| 676 | { |
| 677 | $precedenceOfFirst = $this->getCssSelectorPrecedence($first['selector']); |
| 678 | $precedenceOfSecond = $this->getCssSelectorPrecedence($second['selector']); |
| 679 | |
| 680 | // We want these sorted in ascending order so selectors with lesser precedence get processed first and |
| 681 | // selectors with greater precedence get sorted last. |
| 682 | $precedenceForEquals = $first['line'] < $second['line'] ? -1 : 1; |
| 683 | $precedenceForNotEquals = $precedenceOfFirst < $precedenceOfSecond ? -1 : 1; |
| 684 | return ($precedenceOfFirst === $precedenceOfSecond) ? $precedenceForEquals : $precedenceForNotEquals; |
| 685 | } |
| 686 | |
| 687 | /** |
| 688 | * @param string $selector |
| 689 | * |
| 690 | * @return int |
| 691 | */ |
| 692 | private function getCssSelectorPrecedence(string $selector): int |
| 693 | { |
| 694 | $selectorKey = \md5($selector); |
| 695 | if (isset($this->caches[self::CACHE_KEY_SELECTOR][$selectorKey])) { |
| 696 | return $this->caches[self::CACHE_KEY_SELECTOR][$selectorKey]; |
| 697 | } |
| 698 | |
| 699 | $precedence = 0; |
| 700 | foreach ($this->selectorPrecedenceMatchers as $matcher => $value) { |
| 701 | if (\trim($selector) === '') { |
| 702 | break; |
| 703 | } |
| 704 | $number = 0; |
| 705 | $selector = \preg_replace('/' . $matcher . '\\w+/', '', $selector, -1, $number); |
| 706 | $precedence += ($value * (int)$number); |
| 707 | } |
| 708 | $this->caches[self::CACHE_KEY_SELECTOR][$selectorKey] = $precedence; |
| 709 | |
| 710 | return $precedence; |
| 711 | } |
| 712 | |
| 713 | /** |
| 714 | * Copies $cssRule into the style attribute of $node. |
| 715 | * |
| 716 | * Note: This method does not check whether $cssRule matches $node. |
| 717 | * |
| 718 | * @param \DOMElement $node |
| 719 | * @param array{ |
| 720 | * media: string, |
| 721 | * selector: string, |
| 722 | * hasUnmatchablePseudo: bool, |
| 723 | * declarationsBlock: string, |
| 724 | * line: int |
| 725 | * } $cssRule |
| 726 | */ |
| 727 | private function copyInlinableCssToStyleAttribute(\DOMElement $node, array $cssRule): void |
| 728 | { |
| 729 | $declarationsBlock = $cssRule['declarationsBlock']; |
| 730 | $newStyleDeclarations = $this->parseCssDeclarationsBlock($declarationsBlock); |
| 731 | if ($newStyleDeclarations === []) { |
| 732 | return; |
| 733 | } |
| 734 | |
| 735 | // if it has a style attribute, get it, process it, and append (overwrite) new stuff |
| 736 | if ($node->hasAttribute('style')) { |
| 737 | // break it up into an associative array |
| 738 | $oldStyleDeclarations = $this->parseCssDeclarationsBlock($node->getAttribute('style')); |
| 739 | } else { |
| 740 | $oldStyleDeclarations = []; |
| 741 | } |
| 742 | $node->setAttribute( |
| 743 | 'style', |
| 744 | $this->generateStyleStringFromDeclarationsArrays($oldStyleDeclarations, $newStyleDeclarations) |
| 745 | ); |
| 746 | } |
| 747 | |
| 748 | /** |
| 749 | * This method merges old or existing name/value array with new name/value array |
| 750 | * and then generates a string of the combined style suitable for placing inline. |
| 751 | * This becomes the single point for CSS string generation allowing for consistent |
| 752 | * CSS output no matter where the CSS originally came from. |
| 753 | * |
| 754 | * @param array<string, string> $oldStyles |
| 755 | * @param array<string, string> $newStyles |
| 756 | * |
| 757 | * @return string |
| 758 | */ |
| 759 | private function generateStyleStringFromDeclarationsArrays(array $oldStyles, array $newStyles): string |
| 760 | { |
| 761 | $cacheKey = \serialize([$oldStyles, $newStyles]); |
| 762 | if (isset($this->caches[self::CACHE_KEY_COMBINED_STYLES][$cacheKey])) { |
| 763 | return $this->caches[self::CACHE_KEY_COMBINED_STYLES][$cacheKey]; |
| 764 | } |
| 765 | |
| 766 | // Unset the overridden styles to preserve order, important if shorthand and individual properties are mixed |
| 767 | foreach ($oldStyles as $attributeName => $attributeValue) { |
| 768 | if (!isset($newStyles[$attributeName])) { |
| 769 | continue; |
| 770 | } |
| 771 | |
| 772 | $newAttributeValue = $newStyles[$attributeName]; |
| 773 | if ( |
| 774 | $this->attributeValueIsImportant($attributeValue) |
| 775 | && !$this->attributeValueIsImportant($newAttributeValue) |
| 776 | ) { |
| 777 | unset($newStyles[$attributeName]); |
| 778 | } else { |
| 779 | unset($oldStyles[$attributeName]); |
| 780 | } |
| 781 | } |
| 782 | |
| 783 | $combinedStyles = \array_merge($oldStyles, $newStyles); |
| 784 | |
| 785 | $style = ''; |
| 786 | foreach ($combinedStyles as $attributeName => $attributeValue) { |
| 787 | $style .= \strtolower(\trim($attributeName)) . ': ' . \trim($attributeValue) . '; '; |
| 788 | } |
| 789 | $trimmedStyle = \rtrim($style); |
| 790 | |
| 791 | $this->caches[self::CACHE_KEY_COMBINED_STYLES][$cacheKey] = $trimmedStyle; |
| 792 | |
| 793 | return $trimmedStyle; |
| 794 | } |
| 795 | |
| 796 | /** |
| 797 | * Checks whether $attributeValue is marked as !important. |
| 798 | * |
| 799 | * @param string $attributeValue |
| 800 | * |
| 801 | * @return bool |
| 802 | */ |
| 803 | private function attributeValueIsImportant(string $attributeValue): bool |
| 804 | { |
| 805 | return (bool)\preg_match('/!\\s*+important$/i', $attributeValue); |
| 806 | } |
| 807 | |
| 808 | /** |
| 809 | * Merges styles from styles attributes and style nodes and applies them to the attribute nodes |
| 810 | */ |
| 811 | private function fillStyleAttributesWithMergedStyles(): void |
| 812 | { |
| 813 | foreach ($this->styleAttributesForNodes as $nodePath => $styleAttributesForNode) { |
| 814 | $node = $this->visitedNodes[$nodePath]; |
| 815 | $currentStyleAttributes = $this->parseCssDeclarationsBlock($node->getAttribute('style')); |
| 816 | $node->setAttribute( |
| 817 | 'style', |
| 818 | $this->generateStyleStringFromDeclarationsArrays( |
| 819 | $currentStyleAttributes, |
| 820 | $styleAttributesForNode |
| 821 | ) |
| 822 | ); |
| 823 | } |
| 824 | } |
| 825 | |
| 826 | /** |
| 827 | * Searches for all nodes with a style attribute and removes the "!important" annotations out of |
| 828 | * the inline style declarations, eventually by rearranging declarations. |
| 829 | * |
| 830 | * @throws \RuntimeException |
| 831 | */ |
| 832 | private function removeImportantAnnotationFromAllInlineStyles(): void |
| 833 | { |
| 834 | /** @var \DOMElement $node */ |
| 835 | foreach ($this->getAllNodesWithStyleAttribute() as $node) { |
| 836 | $this->removeImportantAnnotationFromNodeInlineStyle($node); |
| 837 | } |
| 838 | } |
| 839 | |
| 840 | /** |
| 841 | * Removes the "!important" annotations out of the inline style declarations, |
| 842 | * eventually by rearranging declarations. |
| 843 | * Rearranging needed when !important shorthand properties are followed by some of their |
| 844 | * not !important expanded-version properties. |
| 845 | * For example "font: 12px serif !important; font-size: 13px;" must be reordered |
| 846 | * to "font-size: 13px; font: 12px serif;" in order to remain correct. |
| 847 | * |
| 848 | * @param \DOMElement $node |
| 849 | * |
| 850 | * @throws \RuntimeException |
| 851 | */ |
| 852 | private function removeImportantAnnotationFromNodeInlineStyle(\DOMElement $node): void |
| 853 | { |
| 854 | $inlineStyleDeclarations = $this->parseCssDeclarationsBlock($node->getAttribute('style')); |
| 855 | /** @var array<string, string> $regularStyleDeclarations */ |
| 856 | $regularStyleDeclarations = []; |
| 857 | /** @var array<string, string> $importantStyleDeclarations */ |
| 858 | $importantStyleDeclarations = []; |
| 859 | foreach ($inlineStyleDeclarations as $property => $value) { |
| 860 | if ($this->attributeValueIsImportant($value)) { |
| 861 | $importantStyleDeclarations[$property] = $this->pregReplace('/\\s*+!\\s*+important$/i', '', $value); |
| 862 | } else { |
| 863 | $regularStyleDeclarations[$property] = $value; |
| 864 | } |
| 865 | } |
| 866 | $inlineStyleDeclarationsInNewOrder = \array_merge($regularStyleDeclarations, $importantStyleDeclarations); |
| 867 | $node->setAttribute( |
| 868 | 'style', |
| 869 | $this->generateStyleStringFromSingleDeclarationsArray($inlineStyleDeclarationsInNewOrder) |
| 870 | ); |
| 871 | } |
| 872 | |
| 873 | /** |
| 874 | * Generates a CSS style string suitable to be used inline from the $styleDeclarations property => value array. |
| 875 | * |
| 876 | * @param array<string, string> $styleDeclarations |
| 877 | * |
| 878 | * @return string |
| 879 | */ |
| 880 | private function generateStyleStringFromSingleDeclarationsArray(array $styleDeclarations): string |
| 881 | { |
| 882 | return $this->generateStyleStringFromDeclarationsArrays([], $styleDeclarations); |
| 883 | } |
| 884 | |
| 885 | /** |
| 886 | * Determines which of `$cssRules` actually apply to `$this->domDocument`, and sets them in |
| 887 | * `$this->matchingUninlinableCssRules`. |
| 888 | * |
| 889 | * @param array<array-key, array{ |
| 890 | * media: string, |
| 891 | * selector: string, |
| 892 | * hasUnmatchablePseudo: bool, |
| 893 | * declarationsBlock: string, |
| 894 | * line: int |
| 895 | * }> $cssRules |
| 896 | * the "uninlinable" array of CSS rules returned by `collateCssRules` |
| 897 | */ |
| 898 | private function determineMatchingUninlinableCssRules(array $cssRules): void |
| 899 | { |
| 900 | $this->matchingUninlinableCssRules = \array_filter( |
| 901 | $cssRules, |
| 902 | function (array $cssRule): bool { |
| 903 | return $this->existsMatchForSelectorInCssRule($cssRule); |
| 904 | } |
| 905 | ); |
| 906 | } |
| 907 | |
| 908 | /** |
| 909 | * Checks whether there is at least one matching element for the CSS selector contained in the `selector` element |
| 910 | * of the provided CSS rule. |
| 911 | * |
| 912 | * Any dynamic pseudo-classes will be assumed to apply. If the selector matches a pseudo-element, |
| 913 | * it will test for a match with its originating element. |
| 914 | * |
| 915 | * @param array{ |
| 916 | * media: string, |
| 917 | * selector: string, |
| 918 | * hasUnmatchablePseudo: bool, |
| 919 | * declarationsBlock: string, |
| 920 | * line: int |
| 921 | * } $cssRule |
| 922 | * |
| 923 | * @return bool |
| 924 | * |
| 925 | * @throws ParseException |
| 926 | */ |
| 927 | private function existsMatchForSelectorInCssRule(array $cssRule): bool |
| 928 | { |
| 929 | $selector = $cssRule['selector']; |
| 930 | if ($cssRule['hasUnmatchablePseudo']) { |
| 931 | $selector = $this->removeUnmatchablePseudoComponents($selector); |
| 932 | } |
| 933 | return $this->existsMatchForCssSelector($selector); |
| 934 | } |
| 935 | |
| 936 | /** |
| 937 | * Checks whether there is at least one matching element for $cssSelector. |
| 938 | * When not in debug mode, it returns true also for invalid selectors (because they may be valid, |
| 939 | * just not implemented/recognized yet by Emogrifier). |
| 940 | * |
| 941 | * @param string $cssSelector |
| 942 | * |
| 943 | * @return bool |
| 944 | * |
| 945 | * @throws ParseException |
| 946 | */ |
| 947 | private function existsMatchForCssSelector(string $cssSelector): bool |
| 948 | { |
| 949 | try { |
| 950 | $nodesMatchingSelector = $this->getXPath()->query($this->getCssSelectorConverter()->toXPath($cssSelector)); |
| 951 | } catch (ParseException $e) { |
| 952 | if ($this->debug) { |
| 953 | throw $e; |
| 954 | } |
| 955 | return true; |
| 956 | } |
| 957 | |
| 958 | return $nodesMatchingSelector !== false && $nodesMatchingSelector->length !== 0; |
| 959 | } |
| 960 | |
| 961 | /** |
| 962 | * Removes pseudo-elements and dynamic pseudo-classes from a CSS selector, replacing them with "*" if necessary. |
| 963 | * If such a pseudo-component is within the argument of `:not`, the entire `:not` component is removed or replaced. |
| 964 | * |
| 965 | * @param string $selector |
| 966 | * |
| 967 | * @return string |
| 968 | * selector which will match the relevant DOM elements if the pseudo-classes are assumed to apply, or in the |
| 969 | * case of pseudo-elements will match their originating element |
| 970 | */ |
| 971 | private function removeUnmatchablePseudoComponents(string $selector): string |
| 972 | { |
| 973 | // The regex allows nested brackets via `(?2)`. |
| 974 | // A space is temporarily prepended because the callback can't determine if the match was at the very start. |
| 975 | $selectorWithoutNots = \ltrim(\preg_replace_callback( |
| 976 | '/([\\s>+~]?+):not(\\([^()]*+(?:(?2)[^()]*+)*+\\))/i', |
| 977 | /** @param array<array-key, string> $matches */ |
| 978 | function (array $matches): string { |
| 979 | return $this->replaceUnmatchableNotComponent($matches); |
| 980 | }, |
| 981 | ' ' . $selector |
| 982 | )); |
| 983 | |
| 984 | $selectorWithoutUnmatchablePseudoComponents = $this->removeSelectorComponents( |
| 985 | ':(?!' . self::PSEUDO_CLASS_MATCHER . '):?+[\\w\\-]++(?:\\([^\\)]*+\\))?+', |
| 986 | $selectorWithoutNots |
| 987 | ); |
| 988 | |
| 989 | if ( |
| 990 | !\preg_match( |
| 991 | '/:(?:' . self::OF_TYPE_PSEUDO_CLASS_MATCHER . ')/i', |
| 992 | $selectorWithoutUnmatchablePseudoComponents |
| 993 | ) |
| 994 | ) { |
| 995 | return $selectorWithoutUnmatchablePseudoComponents; |
| 996 | } |
| 997 | return \implode('', \array_map( |
| 998 | function (string $selectorPart): string { |
| 999 | return $this->removeUnsupportedOfTypePseudoClasses($selectorPart); |
| 1000 | }, |
| 1001 | \preg_split( |
| 1002 | '/(' . self::COMBINATOR_MATCHER . ')/', |
| 1003 | $selectorWithoutUnmatchablePseudoComponents, |
| 1004 | -1, |
| 1005 | PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY |
| 1006 | ) |
| 1007 | )); |
| 1008 | } |
| 1009 | |
| 1010 | /** |
| 1011 | * Helps `removeUnmatchablePseudoComponents()` replace or remove a selector `:not(...)` component if its argument |
| 1012 | * contains pseudo-elements or dynamic pseudo-classes. |
| 1013 | * |
| 1014 | * @param array<array-key, string> $matches array of elements matched by the regular expression |
| 1015 | * |
| 1016 | * @return string |
| 1017 | * the full match if there were no unmatchable pseudo components within; otherwise, any preceding combinator |
| 1018 | * followed by "*", or an empty string if there was no preceding combinator |
| 1019 | */ |
| 1020 | private function replaceUnmatchableNotComponent(array $matches): string |
| 1021 | { |
| 1022 | [$notComponentWithAnyPrecedingCombinator, $anyPrecedingCombinator, $notArgumentInBrackets] = $matches; |
| 1023 | |
| 1024 | if ($this->hasUnsupportedPseudoClass($notArgumentInBrackets)) { |
| 1025 | return $anyPrecedingCombinator !== '' ? $anyPrecedingCombinator . '*' : ''; |
| 1026 | } |
| 1027 | return $notComponentWithAnyPrecedingCombinator; |
| 1028 | } |
| 1029 | |
| 1030 | /** |
| 1031 | * Removes components from a CSS selector, replacing them with "*" if necessary. |
| 1032 | * |
| 1033 | * @param string $matcher regular expression part to match the components to remove |
| 1034 | * @param string $selector |
| 1035 | * |
| 1036 | * @return string |
| 1037 | * selector which will match the relevant DOM elements if the removed components are assumed to apply (or in |
| 1038 | * the case of pseudo-elements will match their originating element) |
| 1039 | */ |
| 1040 | private function removeSelectorComponents(string $matcher, string $selector): string |
| 1041 | { |
| 1042 | return \preg_replace( |
| 1043 | ['/([\\s>+~]|^)' . $matcher . '/i', '/' . $matcher . '/i'], |
| 1044 | ['$1*', ''], |
| 1045 | $selector |
| 1046 | ); |
| 1047 | } |
| 1048 | |
| 1049 | /** |
| 1050 | * Removes any `...-of-type` pseudo-classes from part of a CSS selector, if it does not have a type, replacing them |
| 1051 | * with "*" if necessary. |
| 1052 | * |
| 1053 | * @param string $selectorPart part of a selector which has been split up at combinators |
| 1054 | * |
| 1055 | * @return string |
| 1056 | * selector part which will match the relevant DOM elements if the pseudo-classes are assumed to apply |
| 1057 | */ |
| 1058 | private function removeUnsupportedOfTypePseudoClasses(string $selectorPart): string |
| 1059 | { |
| 1060 | if (!$this->selectorPartHasUnsupportedOfTypePseudoClass($selectorPart)) { |
| 1061 | return $selectorPart; |
| 1062 | } |
| 1063 | |
| 1064 | return $this->removeSelectorComponents( |
| 1065 | ':(?:' . self::OF_TYPE_PSEUDO_CLASS_MATCHER . ')(?:\\([^\\)]*+\\))?+', |
| 1066 | $selectorPart |
| 1067 | ); |
| 1068 | } |
| 1069 | |
| 1070 | /** |
| 1071 | * Applies `$this->matchingUninlinableCssRules` to `$this->domDocument` by placing them as CSS in a `<style>` |
| 1072 | * element. |
| 1073 | * If there are no uninlinable CSS rules to copy there, a `<style>` element will be created containing only the |
| 1074 | * applicable at-rules from `$parsedCss`. |
| 1075 | * If there are none of either, an empty `<style>` element will not be created. |
| 1076 | * |
| 1077 | * @param CssDocument $parsedCss |
| 1078 | * This may contain various at-rules whose content `CssInliner` does not currently attempt to inline or |
| 1079 | * process in any other way, such as `@import`, `@font-face`, `@keyframes`, etc., and which should precede |
| 1080 | * the processed but found-to-be-uninlinable CSS placed in the `<style>` element. |
| 1081 | * Note that `CssInliner` processes `@media` rules so that they can be ordered correctly with respect to |
| 1082 | * other uninlinable rules; these will not be duplicated from `$parsedCss`. |
| 1083 | */ |
| 1084 | private function copyUninlinableCssToStyleNode(CssDocument $parsedCss): void |
| 1085 | { |
| 1086 | $css = $parsedCss->renderNonConditionalAtRules(); |
| 1087 | |
| 1088 | // avoid including unneeded class dependency if there are no rules |
| 1089 | if ($this->getMatchingUninlinableCssRules() !== []) { |
| 1090 | $cssConcatenator = new CssConcatenator(); |
| 1091 | foreach ($this->getMatchingUninlinableCssRules() as $cssRule) { |
| 1092 | $cssConcatenator->append([$cssRule['selector']], $cssRule['declarationsBlock'], $cssRule['media']); |
| 1093 | } |
| 1094 | $css .= $cssConcatenator->getCss(); |
| 1095 | } |
| 1096 | |
| 1097 | // avoid adding empty style element |
| 1098 | if ($css !== '') { |
| 1099 | $this->addStyleElementToDocument($css); |
| 1100 | } |
| 1101 | } |
| 1102 | |
| 1103 | /** |
| 1104 | * Adds a style element with $css to $this->domDocument. |
| 1105 | * |
| 1106 | * This method is protected to allow overriding. |
| 1107 | * |
| 1108 | * @see https://github.com/MyIntervals/emogrifier/issues/103 |
| 1109 | * |
| 1110 | * @param string $css |
| 1111 | */ |
| 1112 | protected function addStyleElementToDocument(string $css): void |
| 1113 | { |
| 1114 | $domDocument = $this->getDomDocument(); |
| 1115 | $styleElement = $domDocument->createElement('style', $css); |
| 1116 | $styleAttribute = $domDocument->createAttribute('type'); |
| 1117 | $styleAttribute->value = 'text/css'; |
| 1118 | $styleElement->appendChild($styleAttribute); |
| 1119 | |
| 1120 | $headElement = $this->getHeadElement(); |
| 1121 | $headElement->appendChild($styleElement); |
| 1122 | } |
| 1123 | |
| 1124 | /** |
| 1125 | * Returns the HEAD element. |
| 1126 | * |
| 1127 | * This method assumes that there always is a HEAD element. |
| 1128 | * |
| 1129 | * @return \DOMElement |
| 1130 | * |
| 1131 | * @throws \UnexpectedValueException |
| 1132 | */ |
| 1133 | private function getHeadElement(): \DOMElement |
| 1134 | { |
| 1135 | $node = $this->getDomDocument()->getElementsByTagName('head')->item(0); |
| 1136 | if (!$node instanceof \DOMElement) { |
| 1137 | throw new \UnexpectedValueException('There is no HEAD element. This should never happen.', 1617923227); |
| 1138 | } |
| 1139 | |
| 1140 | return $node; |
| 1141 | } |
| 1142 | |
| 1143 | /** |
| 1144 | * Wraps `preg_replace`. If an error occurs (which is highly unlikely), either it is logged and the original |
| 1145 | * `$subject` is returned, or in debug mode an exception is thrown. |
| 1146 | * |
| 1147 | * This method only supports strings, not arrays of strings. |
| 1148 | * |
| 1149 | * @param string $pattern |
| 1150 | * @param string $replacement |
| 1151 | * @param string $subject |
| 1152 | * |
| 1153 | * @return string |
| 1154 | * |
| 1155 | * @throws \RuntimeException |
| 1156 | */ |
| 1157 | private function pregReplace(string $pattern, string $replacement, string $subject): string |
| 1158 | { |
| 1159 | $result = \preg_replace($pattern, $replacement, $subject); |
| 1160 | |
| 1161 | if (!\is_string($result)) { |
| 1162 | $this->logOrThrowPregLastError(); |
| 1163 | $result = $subject; |
| 1164 | } |
| 1165 | |
| 1166 | return $result; |
| 1167 | } |
| 1168 | |
| 1169 | /** |
| 1170 | * Obtains the name of the error constant for `preg_last_error` (based on code posted at |
| 1171 | * {@see https://www.php.net/manual/en/function.preg-last-error.php#124124}) and puts it into an error message |
| 1172 | * which is either passed to `trigger_error` (in non-debug mode) or an exception which is thrown (in debug mode). |
| 1173 | * |
| 1174 | * @throws \RuntimeException |
| 1175 | */ |
| 1176 | private function logOrThrowPregLastError(): void |
| 1177 | { |
| 1178 | $pcreConstants = \get_defined_constants(true)['pcre']; |
| 1179 | $pcreErrorConstantNames = \array_flip(\array_filter( |
| 1180 | $pcreConstants, |
| 1181 | static function (string $key): bool { |
| 1182 | return \substr($key, -6) === '_ERROR'; |
| 1183 | }, |
| 1184 | ARRAY_FILTER_USE_KEY |
| 1185 | )); |
| 1186 | |
| 1187 | $pregLastError = \preg_last_error(); |
| 1188 | $message = 'PCRE regex execution error `' . (string)($pcreErrorConstantNames[$pregLastError] ?? $pregLastError) |
| 1189 | . '`'; |
| 1190 | |
| 1191 | if ($this->debug) { |
| 1192 | throw new \RuntimeException($message, 1592870147); |
| 1193 | } |
| 1194 | \trigger_error($message); |
| 1195 | } |
| 1196 | } |
| 1197 |