• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

MyIntervals / emogrifier / 22833736182

09 Mar 2026 12:43AM UTC coverage: 96.305%. Remained the same
22833736182

Pull #1587

github

web-flow
Merge 62ee4f332 into c9e5ad70d
Pull Request #1587: [TASK] Add extra check in `getCssFromAllStyleNodes()`

1 of 1 new or added line in 1 file covered. (100.0%)

10 existing lines in 1 file now uncovered.

834 of 866 relevant lines covered (96.3%)

259.91 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

95.43
/src/CssInliner.php
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 Pelago\Emogrifier\Utilities\DeclarationBlockParser;
11
use Symfony\Component\CssSelector\CssSelectorConverter;
12
use Symfony\Component\CssSelector\Exception\ParseException;
13

14
use function Safe\preg_match;
15
use function Safe\preg_replace;
16
use function Safe\preg_replace_callback;
17
use function Safe\preg_split;
18

19
/**
20
 * This class provides functions for converting CSS styles into inline style attributes in your HTML code.
21
 */
22
final class CssInliner extends AbstractHtmlProcessor
23
{
24
    private const CACHE_KEY_SELECTOR = 0;
25
    private const CACHE_KEY_COMBINED_STYLES = 1;
26

27
    /**
28
     * Regular expression component matching a static pseudo class in a selector, without the preceding ":",
29
     * for which the applicable elements can be determined (by converting the selector to an XPath expression).
30
     * (Contains alternation without a group and is intended to be placed within a capturing, non-capturing or lookahead
31
     * group, as appropriate for the usage context.)
32
     */
33
    private const PSEUDO_CLASS_MATCHER
34
        = 'empty|(?:first|last|nth(?:-last)?+|only)-(?:child|of-type)|not\\([[:ascii:]]*\\)|root';
35

36
    /**
37
     * This regular expression component matches an `...of-type` pseudo class name, without the preceding ":".  These
38
     * pseudo-classes can currently online be inlined if they have an associated type in the selector expression.
39
     */
40
    private const OF_TYPE_PSEUDO_CLASS_MATCHER = '(?:first|last|nth(?:-last)?+|only)-of-type';
41

42
    /**
43
     * regular expression component to match a selector combinator
44
     */
45
    private const COMBINATOR_MATCHER = '(?:\\s++|\\s*+[>+~]\\s*+)(?=[[:alpha:]_\\-.#*:\\[])';
46

47
    /**
48
     * options array key for `querySelectorAll`
49
     */
50
    private const QSA_ALWAYS_THROW_PARSE_EXCEPTION = 'alwaysThrowParseException';
51

52
    /**
53
     * @var array<non-empty-string, true>
54
     */
55
    private $excludedSelectors = [];
56

57
    /**
58
     * @var array<non-empty-string, true>
59
     */
60
    private $excludedCssSelectors = [];
61

62
    /**
63
     * @var array<non-empty-string, true>
64
     */
65
    private $allowedMediaTypes = ['all' => true, 'screen' => true, 'print' => true];
66

67
    /**
68
     * @var array{
69
     *         0: array<non-empty-string, int<0, max>>,
70
     *         1: array<non-empty-string, string>
71
     *      }
72
     */
73
    private $caches = [
74
        self::CACHE_KEY_SELECTOR => [],
75
        self::CACHE_KEY_COMBINED_STYLES => [],
76
    ];
77

78
    /**
79
     * @var CssSelectorConverter|null
80
     */
81
    private $cssSelectorConverter = null;
82

83
    /**
84
     * the visited nodes with the XPath paths as array keys
85
     *
86
     * @var array<non-empty-string, \DOMElement>
87
     */
88
    private $visitedNodes = [];
89

90
    /**
91
     * the styles to apply to the nodes with the XPath paths as array keys for the outer array
92
     * and the attribute names/values as key/value pairs for the inner array
93
     *
94
     * @var array<non-empty-string, array<string, string>>
95
     */
96
    private $styleAttributesForNodes = [];
97

98
    /**
99
     * Determines whether the "style" attributes of tags in the the HTML passed to this class should be preserved.
100
     * If set to false, the value of the style attributes will be discarded.
101
     *
102
     * @var bool
103
     */
104
    private $isInlineStyleAttributesParsingEnabled = true;
105

106
    /**
107
     * Determines whether the `<style>` blocks in the HTML passed to this class should be parsed.
108
     *
109
     * If set to true, the `<style>` blocks will be removed from the HTML and their contents will be applied to the HTML
110
     * via inline styles.
111
     *
112
     * If set to false, the `<style>` blocks will be left as they are in the HTML.
113
     *
114
     * @var bool
115
     */
116
    private $isStyleBlocksParsingEnabled = true;
117

118
    /**
119
     * For calculating selector precedence order.
120
     * Keys are a regular expression part to match before a CSS name.
121
     * Values are a multiplier factor per match to weight specificity.
122
     *
123
     * @var array<string, int<1, max>>
124
     */
125
    private $selectorPrecedenceMatchers = [
126
        // IDs: worth 10000
127
        '\\#' => 10000,
128
        // classes, attributes, pseudo-classes (not pseudo-elements) except `:not`: worth 100
129
        '(?:\\.|\\[|(?<!:):(?!not\\())' => 100,
130
        // elements (not attribute values or `:not`), pseudo-elements: worth 1
131
        '(?:(?<![="\':\\w\\-])|::)' => 1,
132
    ];
133

134
    /**
135
     * array of data describing CSS rules which apply to the document but cannot be inlined, in the format returned by
136
     * {@see collateCssRules}
137
     *
138
     * @var array<array-key, array{
139
     *          media: string,
140
     *          selector: non-empty-string,
141
     *          hasUnmatchablePseudo: bool,
142
     *          declarationsBlock: string,
143
     *          line: int<0, max>
144
     *      }>|null
145
     */
146
    private $matchingUninlinableCssRules = null;
147

148
    /**
149
     * Emogrifier will throw Exceptions when it encounters an error instead of silently ignoring them.
150
     *
151
     * @var bool
152
     */
153
    private $debug = false;
154

155
    /**
156
     * Inlines the given CSS into the existing HTML.
157
     *
158
     * @param string $css the CSS to inline, must be UTF-8-encoded
159
     *
160
     * @return $this
161
     *
162
     * @throws ParseException in debug mode, if an invalid selector is encountered
163
     * @throws \RuntimeException
164
     *         in debug mode, if an internal PCRE error occurs
165
     *         or `CssSelectorConverter::toXPath` returns an invalid XPath expression
166
     * @throws \UnexpectedValueException
167
     *         if a selector query result includes a node which is not a `DOMElement`
168
     */
169
    public function inlineCss(string $css = ''): self
1,171✔
170
    {
171
        $this->clearAllCaches();
1,171✔
172
        $this->purgeVisitedNodes();
1,171✔
173

174
        $this->normalizeStyleAttributesOfAllNodes();
1,171✔
175

176
        $combinedCss = $css;
1,171✔
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) {
1,171✔
180
            $combinedCss .= $this->getCssFromAllStyleNodes();
1,169✔
181
        }
182
        $parsedCss = new CssDocument($combinedCss, $this->debug);
1,171✔
183

184
        $excludedNodes = $this->getNodesToExclude();
1,167✔
185
        $cssRules = $this->collateCssRules($parsedCss);
1,166✔
186
        foreach ($cssRules['inlinable'] as $cssRule) {
1,166✔
187
            foreach ($this->querySelectorAll($cssRule['selector']) as $node) {
519✔
188
                if (\in_array($node, $excludedNodes, true)) {
466✔
189
                    continue;
4✔
190
                }
191
                $this->copyInlinableCssToStyleAttribute($this->ensureNodeIsElement($node), $cssRule);
464✔
192
            }
193
        }
194

195
        if ($this->isInlineStyleAttributesParsingEnabled) {
1,166✔
196
            $this->fillStyleAttributesWithMergedStyles();
1,164✔
197
        }
198

199
        $this->removeImportantAnnotationFromAllInlineStyles();
1,166✔
200

201
        $this->determineMatchingUninlinableCssRules($cssRules['uninlinable']);
1,166✔
202
        $this->copyUninlinableCssToStyleNode($parsedCss);
1,165✔
203

204
        return $this;
1,165✔
205
    }
206

207
    /**
208
     * Disables the parsing of inline styles.
209
     *
210
     * @return $this
211
     */
212
    public function disableInlineStyleAttributesParsing(): self
3✔
213
    {
214
        $this->isInlineStyleAttributesParsingEnabled = false;
3✔
215

216
        return $this;
3✔
217
    }
218

219
    /**
220
     * Disables the parsing of `<style>` blocks.
221
     *
222
     * @return $this
223
     */
224
    public function disableStyleBlocksParsing(): self
3✔
225
    {
226
        $this->isStyleBlocksParsingEnabled = false;
3✔
227

228
        return $this;
3✔
229
    }
230

231
    /**
232
     * Marks a media query type to keep.
233
     *
234
     * @param non-empty-string $mediaName the media type name, e.g., "braille"
235
     *
236
     * @return $this
237
     */
238
    public function addAllowedMediaType(string $mediaName): self
2✔
239
    {
240
        $this->allowedMediaTypes[$mediaName] = true;
2✔
241

242
        return $this;
2✔
243
    }
244

245
    /**
246
     * Drops a media query type from the allowed list.
247
     *
248
     * @param non-empty-string $mediaName the tag name, e.g., "braille"
249
     *
250
     * @return $this
251
     */
252
    public function removeAllowedMediaType(string $mediaName): self
2✔
253
    {
254
        if (isset($this->allowedMediaTypes[$mediaName])) {
2✔
255
            unset($this->allowedMediaTypes[$mediaName]);
2✔
256
        }
257

258
        return $this;
2✔
259
    }
260

261
    /**
262
     * Adds a selector to exclude nodes from emogrification.
263
     *
264
     * Any nodes that match the selector will not have their style altered.
265
     *
266
     * @param non-empty-string $selector the selector to exclude, e.g., ".editor"
267
     *
268
     * @return $this
269
     */
270
    public function addExcludedSelector(string $selector): self
9✔
271
    {
272
        $this->excludedSelectors[$selector] = true;
9✔
273

274
        return $this;
9✔
275
    }
276

277
    /**
278
     * No longer excludes the nodes matching this selector from emogrification.
279
     *
280
     * @param non-empty-string $selector the selector to no longer exclude, e.g., ".editor"
281
     *
282
     * @return $this
283
     */
284
    public function removeExcludedSelector(string $selector): self
2✔
285
    {
286
        if (isset($this->excludedSelectors[$selector])) {
2✔
287
            unset($this->excludedSelectors[$selector]);
1✔
288
        }
289

290
        return $this;
2✔
291
    }
292

293
    /**
294
     * Adds a selector to exclude CSS selector from emogrification.
295
     *
296
     * @param non-empty-string $selector the selector to exclude, e.g., `.editor`
297
     *
298
     * @return $this
299
     */
300
    public function addExcludedCssSelector(string $selector): self
6✔
301
    {
302
        $this->excludedCssSelectors[$selector] = true;
6✔
303

304
        return $this;
6✔
305
    }
306

307
    /**
308
     * No longer excludes the CSS selector from emogrification.
309
     *
310
     * @param non-empty-string $selector the selector to no longer exclude, e.g., `.editor`
311
     *
312
     * @return $this
313
     */
314
    public function removeExcludedCssSelector(string $selector): self
2✔
315
    {
316
        if (isset($this->excludedCssSelectors[$selector])) {
2✔
317
            unset($this->excludedCssSelectors[$selector]);
1✔
318
        }
319

320
        return $this;
2✔
321
    }
322

323
    /**
324
     * Sets the debug mode.
325
     *
326
     * @param bool $debug set to true to enable debug mode
327
     *
328
     * @return $this
329
     */
330
    public function setDebug(bool $debug): self
1,167✔
331
    {
332
        $this->debug = $debug;
1,167✔
333

334
        return $this;
1,167✔
335
    }
336

337
    /**
338
     * Gets the array of selectors present in the CSS provided to `inlineCss()` for which the declarations could not be
339
     * applied as inline styles, but which may affect elements in the HTML.  The relevant CSS will have been placed in a
340
     * `<style>` element.  The selectors may include those used within `@media` rules or those involving dynamic
341
     * pseudo-classes (such as `:hover`) or pseudo-elements (such as `::after`).
342
     *
343
     * @return array<array-key, string>
344
     *
345
     * @throws \BadMethodCallException if `inlineCss` has not been called first
346
     */
347
    public function getMatchingUninlinableSelectors(): array
6✔
348
    {
349
        return \array_column($this->getMatchingUninlinableCssRules(), 'selector');
6✔
350
    }
351

352
    /**
353
     * @return array<array-key, array{
354
     *             media: string,
355
     *             selector: non-empty-string,
356
     *             hasUnmatchablePseudo: bool,
357
     *             declarationsBlock: string,
358
     *             line: int<0, max>
359
     *         }>
360
     *
361
     * @throws \BadMethodCallException if `inlineCss` has not been called first
362
     */
363
    private function getMatchingUninlinableCssRules(): array
1,167✔
364
    {
365
        if (!\is_array($this->matchingUninlinableCssRules)) {
1,167✔
366
            throw new \BadMethodCallException('inlineCss must be called first', 1568385221);
1✔
367
        }
368

369
        return $this->matchingUninlinableCssRules;
1,166✔
370
    }
371

372
    /**
373
     * Clears all caches.
374
     */
375
    private function clearAllCaches(): void
1,171✔
376
    {
377
        $this->caches = [
1,171✔
378
            self::CACHE_KEY_SELECTOR => [],
1,171✔
379
            self::CACHE_KEY_COMBINED_STYLES => [],
1,171✔
380
        ];
1,171✔
381

382
        DeclarationBlockParser::clearCache();
1,171✔
383
    }
384

385
    /**
386
     * Purges the visited nodes.
387
     */
388
    private function purgeVisitedNodes(): void
1,171✔
389
    {
390
        $this->visitedNodes = [];
1,171✔
391
        $this->styleAttributesForNodes = [];
1,171✔
392
    }
393

394
    /**
395
     * Parses the document and normalizes all existing CSS attributes.
396
     * This changes 'DISPLAY: none' to 'display: none'.
397
     * We wouldn't have to do this if DOMXPath supported XPath 2.0.
398
     * Also stores a reference of nodes with existing inline styles so we don't overwrite them.
399
     */
400
    private function normalizeStyleAttributesOfAllNodes(): void
1,171✔
401
    {
402
        foreach ($this->getAllNodesWithStyleAttribute() as $node) {
1,171✔
403
            if ($this->isInlineStyleAttributesParsingEnabled) {
44✔
404
                $this->normalizeStyleAttributes($node);
42✔
405
            }
406
            // Remove style attribute in every case, so we can add them back (if inline style attributes
407
            // parsing is enabled) to the end of the style list, thus keeping the right priority of CSS rules;
408
            // else original inline style rules may remain at the beginning of the final inline style definition
409
            // of a node, which may give not the desired results
410
            $node->removeAttribute('style');
44✔
411
        }
412
    }
413

414
    /**
415
     * Returns a list with all DOM nodes that have a style attribute.
416
     *
417
     * @return \DOMNodeList<\DOMElement>
418
     *
419
     * @throws \RuntimeException
420
     */
421
    private function getAllNodesWithStyleAttribute(): \DOMNodeList
1,171✔
422
    {
423
        $query = '//*[@style]';
1,171✔
424
        $matches = $this->getXPath()->query($query);
1,171✔
425
        if (!$matches instanceof \DOMNodeList) {
1,171✔
426
            throw new \RuntimeException('XPatch query failed: ' . $query, 1618577797);
×
427
        }
428
        /** @var \DOMNodeList<\DOMElement> $matches */
429

430
        return $matches;
1,171✔
431
    }
432

433
    /**
434
     * Normalizes the value of the "style" attribute and saves it.
435
     */
436
    private function normalizeStyleAttributes(\DOMElement $node): void
42✔
437
    {
438
        $declarationBlockParser = new DeclarationBlockParser();
42✔
439

440
        $pattern = '/-{0,2}+[_a-zA-Z][\\w\\-]*+(?=:)/S';
42✔
441
        /** @param array<array-key, string> $propertyNameMatches */
442
        $callback = static function (array $propertyNameMatches) use ($declarationBlockParser): string {
42✔
443
            return $declarationBlockParser->normalizePropertyName($propertyNameMatches[0]);
42✔
444
        };
42✔
445
        if (\function_exists('Safe\\preg_replace_callback')) {
42✔
446
            $normalizedOriginalStyle = preg_replace_callback($pattern, $callback, $node->getAttribute('style'));
42✔
447
        } else {
448
            // @phpstan-ignore-next-line The safe version is only available in "thecodingmachine/safe" for PHP >= 8.1.
449
            $normalizedOriginalStyle = \preg_replace_callback($pattern, $callback, $node->getAttribute('style'));
×
450
            \assert(\is_string($normalizedOriginalStyle));
×
451
        }
452

453
        // In order to not overwrite existing style attributes in the HTML, we have to save the original HTML styles.
454
        $nodePath = $node->getNodePath();
42✔
455
        if (\is_string($nodePath) && ($nodePath !== '') && !isset($this->styleAttributesForNodes[$nodePath])) {
42✔
456
            $this->styleAttributesForNodes[$nodePath] = $declarationBlockParser->parse($normalizedOriginalStyle);
42✔
457
            $this->visitedNodes[$nodePath] = $node;
42✔
458
        }
459

460
        $node->setAttribute('style', $normalizedOriginalStyle);
42✔
461
    }
462

463
    /**
464
     * Returns CSS content.
465
     */
466
    private function getCssFromAllStyleNodes(): string
1,169✔
467
    {
468
        $styleNodes = $this->getXPath()->query('//style');
1,169✔
469
        if ($styleNodes === false) {
1,169✔
470
            return '';
×
471
        }
472

473
        $css = '';
1,169✔
474
        foreach ($styleNodes as $styleNode) {
1,169✔
475
            if (\is_string($styleNode->nodeValue)) {
39✔
476
                $css .= "\n\n" . $styleNode->nodeValue;
39✔
477
            }
478
            $parentNode = $styleNode->parentNode;
39✔
479
            if ($parentNode instanceof \DOMNode && $styleNode instanceof \DOMNode) {
39✔
480
                $parentNode->removeChild($styleNode);
39✔
481
            }
482
        }
483

484
        return $css;
1,169✔
485
    }
486

487
    /**
488
     * Find the nodes that are not to be emogrified.
489
     *
490
     * @return list<\DOMElement>
491
     *
492
     * @throws ParseException in debug mode, if an invalid selector is encountered
493
     * @throws \RuntimeException in debug mode, if `CssSelectorConverter::toXPath` returns an invalid XPath expression
494
     * @throws \UnexpectedValueException if the selector query result includes a node which is not a `DOMElement`
495
     */
496
    private function getNodesToExclude(): array
1,167✔
497
    {
498
        $excludedNodes = [];
1,167✔
499
        foreach (\array_keys($this->excludedSelectors) as $selectorToExclude) {
1,167✔
500
            foreach ($this->querySelectorAll($selectorToExclude) as $node) {
7✔
501
                $excludedNodes[] = $this->ensureNodeIsElement($node);
4✔
502
            }
503
        }
504

505
        return $excludedNodes;
1,166✔
506
    }
507

508
    /**
509
     * @param array{alwaysThrowParseException?: bool} $options
510
     *        This is an array of option values to control behaviour:
511
     *        - `QSA_ALWAYS_THROW_PARSE_EXCEPTION` - `bool` - throw any `ParseException` regardless of debug setting.
512
     *
513
     * @return \DOMNodeList<\DOMElement> the HTML elements that match the provided CSS `$selectors`
514
     *
515
     * @throws ParseException
516
     *         in debug mode (or with `QSA_ALWAYS_THROW_PARSE_EXCEPTION` option), if an invalid selector is encountered
517
     * @throws \RuntimeException in debug mode, if `CssSelectorConverter::toXPath` returns an invalid XPath expression
518
     */
519
    private function querySelectorAll(string $selectors, array $options = []): \DOMNodeList
1,065✔
520
    {
521
        try {
522
            $result = $this->getXPath()->query($this->getCssSelectorConverter()->toXPath($selectors));
1,065✔
523

524
            if ($result === false) {
1,061✔
UNCOV
525
                throw new \RuntimeException('query failed with selector \'' . $selectors . '\'', 1726533051);
×
526
            }
527
            /** @var \DOMNodeList<\DOMElement> $result */
528

529
            return $result;
1,061✔
530
        } catch (ParseException $exception) {
5✔
531
            $alwaysThrowParseException = $options[self::QSA_ALWAYS_THROW_PARSE_EXCEPTION] ?? false;
5✔
532
            if ($this->debug || $alwaysThrowParseException) {
5✔
533
                throw $exception;
3✔
534
            }
535
            $list = new \DOMNodeList();
2✔
536
            /** @var \DOMNodeList<\DOMElement> $list */
537
            return $list;
2✔
UNCOV
538
        } catch (\RuntimeException $exception) {
×
539
            if (
UNCOV
540
                $this->debug
×
541
            ) {
UNCOV
542
                throw $exception;
×
543
            }
544
            // `RuntimeException` indicates a bug in CssSelector so pass the message to the error handler.
UNCOV
545
            \trigger_error($exception->getMessage());
×
546
            $list = new \DOMNodeList();
×
547
            /** @var \DOMNodeList<\DOMElement> $list */
UNCOV
548
            return $list;
×
549
        }
550
    }
551

552
    /**
553
     * @throws \UnexpectedValueException if `$node` is not a `DOMElement`
554
     */
555
    private function ensureNodeIsElement(\DOMNode $node): \DOMElement
466✔
556
    {
557
        if (!($node instanceof \DOMElement)) {
466✔
UNCOV
558
            $path = $node->getNodePath() ?? '$node';
×
559
            throw new \UnexpectedValueException($path . ' is not a DOMElement.', 1617975914);
×
560
        }
561

562
        return $node;
466✔
563
    }
564

565
    private function getCssSelectorConverter(): CssSelectorConverter
1,065✔
566
    {
567
        if (!$this->cssSelectorConverter instanceof CssSelectorConverter) {
1,065✔
568
            $this->cssSelectorConverter = new CssSelectorConverter();
1,065✔
569
        }
570

571
        return $this->cssSelectorConverter;
1,065✔
572
    }
573

574
    /**
575
     * Collates the individual rules from a `CssDocument` object.
576
     *
577
     * @return array<string, array<array-key, array{
578
     *           media: string,
579
     *           selector: non-empty-string,
580
     *           hasUnmatchablePseudo: bool,
581
     *           declarationsBlock: string,
582
     *           line: int<0, max>
583
     *         }>>
584
     *         This 2-entry array has the key "inlinable" containing rules which can be inlined as `style` attributes
585
     *         and the key "uninlinable" containing rules which cannot.  Each value is an array of sub-arrays with the
586
     *         following keys:
587
     *         - "media" (the media query string, e.g. "@media screen and (max-width: 480px)",
588
     *           or an empty string if not from a `@media` rule);
589
     *         - "selector" (the CSS selector, e.g., "*" or "header h1");
590
     *         - "hasUnmatchablePseudo" (`true` if that selector contains pseudo-elements or dynamic pseudo-classes such
591
     *           that the declarations cannot be applied inline);
592
     *         - "declarationsBlock" (the semicolon-separated CSS declarations for that selector,
593
     *           e.g., `color: red; height: 4px;`);
594
     *         - "line" (the line number, e.g. 42).
595
     */
596
    private function collateCssRules(CssDocument $parsedCss): array
1,166✔
597
    {
598
        $matches = $parsedCss->getStyleRulesData(\array_keys($this->allowedMediaTypes));
1,166✔
599

600
        $cssRules = [
1,166✔
601
            'inlinable' => [],
1,166✔
602
            'uninlinable' => [],
1,166✔
603
        ];
1,166✔
604
        foreach ($matches as $key => $cssRule) {
1,166✔
605
            if (!$cssRule->hasAtLeastOneDeclaration()) {
1,066✔
606
                continue;
3✔
607
            }
608

609
            $mediaQuery = $cssRule->getContainingAtRule();
1,063✔
610
            $declarationsBlock = $cssRule->getDeclarationsAsText();
1,063✔
611
            $selectors = $cssRule->getSelectors();
1,063✔
612

613
            // Maybe exclude CSS selectors
614
            if (\count($this->excludedCssSelectors) > 0) {
1,063✔
615
                // Normalize spaces, line breaks & tabs
616
                $selectorsNormalized = \array_map(static function (string $selector): string {
5✔
617
                    return preg_replace('@\\s++@u', ' ', $selector);
5✔
618
                }, $selectors);
5✔
619
                /** @var array<non-empty-string> $selectors */
620
                $selectors = \array_filter($selectorsNormalized, function (string $selector): bool {
5✔
621
                    return !isset($this->excludedCssSelectors[$selector]);
5✔
622
                });
5✔
623
            }
624

625
            foreach ($selectors as $selector) {
1,063✔
626
                // don't process pseudo-elements and behavioral (dynamic) pseudo-classes;
627
                // only allow structural pseudo-classes
628
                $hasPseudoElement = \strpos($selector, '::') !== false;
1,063✔
629
                $hasUnmatchablePseudo = $hasPseudoElement || $this->hasUnsupportedPseudoClass($selector);
1,063✔
630

631
                $parsedCssRule = [
1,063✔
632
                    'media' => $mediaQuery,
1,063✔
633
                    'selector' => $selector,
1,063✔
634
                    'hasUnmatchablePseudo' => $hasUnmatchablePseudo,
1,063✔
635
                    'declarationsBlock' => $declarationsBlock,
1,063✔
636
                    // keep track of where it appears in the file, since order is important
637
                    'line' => $key,
1,063✔
638
                ];
1,063✔
639
                $ruleType = (!$cssRule->hasContainingAtRule() && !$hasUnmatchablePseudo) ? 'inlinable' : 'uninlinable';
1,063✔
640
                $cssRules[$ruleType][] = $parsedCssRule;
1,063✔
641
            }
642
        }
643

644
        \usort(
1,166✔
645
            $cssRules['inlinable'],
1,166✔
646
            /**
647
             * @param array{selector: non-empty-string, line: int<0, max>} $first
648
             * @param array{selector: non-empty-string, line: int<0, max>} $second
649
             */
650
            function (array $first, array $second): int {
1,166✔
651
                return $this->sortBySelectorPrecedence($first, $second);
75✔
652
            }
1,166✔
653
        );
1,166✔
654

655
        return $cssRules;
1,166✔
656
    }
657

658
    /**
659
     * Tests if a selector contains a pseudo-class which would mean it cannot be converted to an XPath expression for
660
     * inlining CSS declarations.
661
     *
662
     * Any pseudo class that does not match {@see PSEUDO_CLASS_MATCHER} cannot be converted.  Additionally, `...of-type`
663
     * pseudo-classes cannot be converted if they are not associated with a type selector.
664
     */
665
    private function hasUnsupportedPseudoClass(string $selector): bool
1,006✔
666
    {
667
        if (preg_match('/:(?!' . self::PSEUDO_CLASS_MATCHER . ')[\\w\\-]/i', $selector) !== 0) {
1,006✔
668
            return true;
323✔
669
        }
670

671
        if (preg_match('/:(?:' . self::OF_TYPE_PSEUDO_CLASS_MATCHER . ')/i', $selector) === 0) {
788✔
672
            return false;
668✔
673
        }
674

675
        foreach (preg_split('/' . self::COMBINATOR_MATCHER . '/', $selector) as $selectorPart) {
120✔
676
            \assert(\is_string($selectorPart));
120✔
677
            if ($this->selectorPartHasUnsupportedOfTypePseudoClass($selectorPart)) {
120✔
678
                return true;
67✔
679
            }
680
        }
681

682
        return false;
53✔
683
    }
684

685
    /**
686
     * Tests if part of a selector contains an `...of-type` pseudo-class such that it cannot be converted to an XPath
687
     * expression.
688
     *
689
     * @param string $selectorPart part of a selector which has been split up at combinators
690
     *
691
     * @return bool `true` if the selector part does not have a type but does have an `...of-type` pseudo-class
692
     */
693
    private function selectorPartHasUnsupportedOfTypePseudoClass(string $selectorPart): bool
120✔
694
    {
695
        if (preg_match('/^[\\w\\-]/', $selectorPart) !== 0) {
120✔
696
            return false;
97✔
697
        }
698

699
        return preg_match('/:(?:' . self::OF_TYPE_PSEUDO_CLASS_MATCHER . ')/i', $selectorPart) !== 0;
67✔
700
    }
701

702
    /**
703
     * @param array{selector: non-empty-string, line: int<0, max>} $first
704
     * @param array{selector: non-empty-string, line: int<0, max>} $second
705
     */
706
    private function sortBySelectorPrecedence(array $first, array $second): int
75✔
707
    {
708
        $precedenceOfFirst = $this->getCssSelectorPrecedence($first['selector']);
75✔
709
        $precedenceOfSecond = $this->getCssSelectorPrecedence($second['selector']);
75✔
710

711
        // We want these sorted in ascending order so selectors with lesser precedence get processed first and
712
        // selectors with greater precedence get sorted last.
713
        $precedenceForEquals = $first['line'] < $second['line'] ? -1 : 1;
75✔
714
        $precedenceForNotEquals = $precedenceOfFirst < $precedenceOfSecond ? -1 : 1;
75✔
715
        return ($precedenceOfFirst === $precedenceOfSecond) ? $precedenceForEquals : $precedenceForNotEquals;
75✔
716
    }
717

718
    /**
719
     * @param non-empty-string $selector
720
     *
721
     * @return int<0, max>
722
     */
723
    private function getCssSelectorPrecedence(string $selector): int
75✔
724
    {
725
        $selectorKey = $selector;
75✔
726
        if (isset($this->caches[self::CACHE_KEY_SELECTOR][$selectorKey])) {
75✔
727
            return $this->caches[self::CACHE_KEY_SELECTOR][$selectorKey];
68✔
728
        }
729

730
        $precedence = 0;
75✔
731
        foreach ($this->selectorPrecedenceMatchers as $matcher => $value) {
75✔
732
            if (\trim($selector) === '') {
75✔
733
                break;
8✔
734
            }
735
            $count = 0;
75✔
736
            $selector = preg_replace('/' . $matcher . '\\w+/', '', $selector, -1, $count);
75✔
737
            $precedence += ($value * $count);
75✔
738
            \assert($precedence >= 0);
75✔
739
        }
740
        $this->caches[self::CACHE_KEY_SELECTOR][$selectorKey] = $precedence;
75✔
741

742
        return $precedence;
75✔
743
    }
744

745
    /**
746
     * Copies `$cssRule` into the style attribute of `$node`.
747
     *
748
     * Note: This method does not check whether $cssRule matches $node.
749
     *
750
     * @param array{
751
     *            media: string,
752
     *            selector: non-empty-string,
753
     *            hasUnmatchablePseudo: bool,
754
     *            declarationsBlock: string,
755
     *            line: int<0, max>
756
     *        } $cssRule
757
     */
758
    private function copyInlinableCssToStyleAttribute(\DOMElement $node, array $cssRule): void
464✔
759
    {
760
        $declarationsBlock = $cssRule['declarationsBlock'];
464✔
761
        $declarationBlockParser = new DeclarationBlockParser();
464✔
762
        $newStyleDeclarations = $declarationBlockParser->parse($declarationsBlock);
464✔
763
        if ($newStyleDeclarations === []) {
464✔
764
            return;
1✔
765
        }
766

767
        // if it has a style attribute, get it, process it, and append (overwrite) new stuff
768
        if ($node->hasAttribute('style')) {
463✔
769
            // break it up into an associative array
770
            $oldStyleDeclarations = $declarationBlockParser->parse($node->getAttribute('style'));
67✔
771
        } else {
772
            $oldStyleDeclarations = [];
463✔
773
        }
774
        $node->setAttribute(
463✔
775
            'style',
463✔
776
            $this->generateStyleStringFromDeclarationsArrays($oldStyleDeclarations, $newStyleDeclarations)
463✔
777
        );
463✔
778
    }
779

780
    /**
781
     * This method merges old or existing name/value array with new name/value array
782
     * and then generates a string of the combined style suitable for placing inline.
783
     * This becomes the single point for CSS string generation allowing for consistent
784
     * CSS output no matter where the CSS originally came from.
785
     *
786
     * @param array<string, string> $oldStyles
787
     * @param array<string, string> $newStyles
788
     *
789
     * @throws \UnexpectedValueException if an empty property name is encountered (which should not happen)
790
     */
791
    private function generateStyleStringFromDeclarationsArrays(array $oldStyles, array $newStyles): string
482✔
792
    {
793
        $cacheKey = \serialize([$oldStyles, $newStyles]);
482✔
794
        \assert($cacheKey !== '');
482✔
795
        if (isset($this->caches[self::CACHE_KEY_COMBINED_STYLES][$cacheKey])) {
482✔
796
            return $this->caches[self::CACHE_KEY_COMBINED_STYLES][$cacheKey];
397✔
797
        }
798

799
        // Unset the overridden styles to preserve order, important if shorthand and individual properties are mixed
800
        foreach ($oldStyles as $attributeName => $attributeValue) {
482✔
801
            if (!isset($newStyles[$attributeName])) {
87✔
802
                continue;
64✔
803
            }
804

805
            $newAttributeValue = $newStyles[$attributeName];
74✔
806
            if (
807
                $this->attributeValueIsImportant($attributeValue)
74✔
808
                && !$this->attributeValueIsImportant($newAttributeValue)
74✔
809
            ) {
810
                unset($newStyles[$attributeName]);
11✔
811
            } else {
812
                unset($oldStyles[$attributeName]);
63✔
813
            }
814
        }
815

816
        $combinedStyles = \array_merge($oldStyles, $newStyles);
482✔
817

818
        $declarationBlockParser = new DeclarationBlockParser();
482✔
819
        $style = '';
482✔
820
        foreach ($combinedStyles as $attributeName => $attributeValue) {
482✔
821
            $trimmedAttributeName = \trim($attributeName);
482✔
822
            if ($trimmedAttributeName === '') {
482✔
UNCOV
823
                throw new \UnexpectedValueException('An empty property name was encountered.', 1727046078);
×
824
            }
825
            $propertyName = $declarationBlockParser->normalizePropertyName($trimmedAttributeName);
482✔
826
            $propertyValue = \trim($attributeValue);
482✔
827
            $style .= $propertyName . ': ' . $propertyValue . '; ';
482✔
828
        }
829
        $trimmedStyle = \rtrim($style);
482✔
830

831
        $this->caches[self::CACHE_KEY_COMBINED_STYLES][$cacheKey] = $trimmedStyle;
482✔
832

833
        return $trimmedStyle;
482✔
834
    }
835

836
    /**
837
     * Checks whether `$attributeValue` is marked as `!important`.
838
     */
839
    private function attributeValueIsImportant(string $attributeValue): bool
482✔
840
    {
841
        return preg_match('/!\\s*+important$/i', $attributeValue) !== 0;
482✔
842
    }
843

844
    /**
845
     * Merges styles from styles attributes and style nodes and applies them to the attribute nodes
846
     */
847
    private function fillStyleAttributesWithMergedStyles(): void
1,164✔
848
    {
849
        $declarationBlockParser = new DeclarationBlockParser();
1,164✔
850
        foreach ($this->styleAttributesForNodes as $nodePath => $styleAttributesForNode) {
1,164✔
851
            $node = $this->visitedNodes[$nodePath];
42✔
852
            $currentStyleAttributes = $declarationBlockParser->parse($node->getAttribute('style'));
42✔
853
            $node->setAttribute(
42✔
854
                'style',
42✔
855
                $this->generateStyleStringFromDeclarationsArrays(
42✔
856
                    $currentStyleAttributes,
42✔
857
                    $styleAttributesForNode
42✔
858
                )
42✔
859
            );
42✔
860
        }
861
    }
862

863
    /**
864
     * Searches for all nodes with a style attribute and removes the "!important" annotations out of
865
     * the inline style declarations, eventually by rearranging declarations.
866
     *
867
     * @throws \RuntimeException
868
     */
869
    private function removeImportantAnnotationFromAllInlineStyles(): void
1,166✔
870
    {
871
        foreach ($this->getAllNodesWithStyleAttribute() as $node) {
1,166✔
872
            $this->removeImportantAnnotationFromNodeInlineStyle($node);
482✔
873
        }
874
    }
875

876
    /**
877
     * Removes the "!important" annotations out of the inline style declarations,
878
     * eventually by rearranging declarations.
879
     * Rearranging needed when !important shorthand properties are followed by some of their
880
     * not !important expanded-version properties.
881
     * For example "font: 12px serif !important; font-size: 13px;" must be reordered
882
     * to "font-size: 13px; font: 12px serif;" in order to remain correct.
883
     *
884
     * @throws \RuntimeException
885
     */
886
    private function removeImportantAnnotationFromNodeInlineStyle(\DOMElement $node): void
482✔
887
    {
888
        $style = $node->getAttribute('style');
482✔
889
        $inlineStyleDeclarations = (new DeclarationBlockParser())->parse((bool) $style ? $style : '');
482✔
890
        /** @var array<string, string> $regularStyleDeclarations */
891
        $regularStyleDeclarations = [];
482✔
892
        /** @var array<string, string> $importantStyleDeclarations */
893
        $importantStyleDeclarations = [];
482✔
894
        foreach ($inlineStyleDeclarations as $property => $value) {
482✔
895
            if ($this->attributeValueIsImportant($value)) {
482✔
896
                $declaration = preg_replace('/\\s*+!\\s*+important$/i', '', $value);
38✔
897
                $importantStyleDeclarations[$property] = $declaration;
38✔
898
            } else {
899
                $regularStyleDeclarations[$property] = $value;
458✔
900
            }
901
        }
902
        $inlineStyleDeclarationsInNewOrder = \array_merge($regularStyleDeclarations, $importantStyleDeclarations);
482✔
903
        $node->setAttribute(
482✔
904
            'style',
482✔
905
            $this->generateStyleStringFromSingleDeclarationsArray($inlineStyleDeclarationsInNewOrder)
482✔
906
        );
482✔
907
    }
908

909
    /**
910
     * Generates a CSS style string suitable to be used inline from the $styleDeclarations property => value array.
911
     *
912
     * @param array<string, string> $styleDeclarations
913
     */
914
    private function generateStyleStringFromSingleDeclarationsArray(array $styleDeclarations): string
482✔
915
    {
916
        return $this->generateStyleStringFromDeclarationsArrays([], $styleDeclarations);
482✔
917
    }
918

919
    /**
920
     * Determines which of `$cssRules` actually apply to `$this->domDocument`, and sets them in
921
     * `$this->matchingUninlinableCssRules`.
922
     *
923
     * @param array<array-key, array{
924
     *            media: string,
925
     *            selector: non-empty-string,
926
     *            hasUnmatchablePseudo: bool,
927
     *            declarationsBlock: string,
928
     *            line: int<0, max>
929
     *        }> $cssRules
930
     *        the "uninlinable" array of CSS rules returned by `collateCssRules`
931
     */
932
    private function determineMatchingUninlinableCssRules(array $cssRules): void
1,166✔
933
    {
934
        $this->matchingUninlinableCssRules = \array_filter(
1,166✔
935
            $cssRules,
1,166✔
936
            function (array $cssRule): bool {
1,166✔
937
                return $this->existsMatchForSelectorInCssRule($cssRule);
581✔
938
            }
1,166✔
939
        );
1,166✔
940
    }
941

942
    /**
943
     * Checks whether there is at least one matching element for the CSS selector contained in the `selector` element
944
     * of the provided CSS rule.
945
     *
946
     * Any dynamic pseudo-classes will be assumed to apply. If the selector matches a pseudo-element,
947
     * it will test for a match with its originating element.
948
     *
949
     * @param array{
950
     *            media: string,
951
     *            selector: non-empty-string,
952
     *            hasUnmatchablePseudo: bool,
953
     *            declarationsBlock: string,
954
     *            line: int<0, max>
955
     *        } $cssRule
956
     *
957
     * @throws ParseException
958
     */
959
    private function existsMatchForSelectorInCssRule(array $cssRule): bool
581✔
960
    {
961
        $selector = $cssRule['selector'];
581✔
962
        if ($cssRule['hasUnmatchablePseudo']) {
581✔
963
            $selector = $this->removeUnmatchablePseudoComponents($selector);
449✔
964
        }
965
        return $this->existsMatchForCssSelector($selector);
581✔
966
    }
967

968
    /**
969
     * Checks whether there is at least one matching element for $cssSelector.
970
     * When not in debug mode, it returns true also for invalid selectors (because they may be valid,
971
     * just not implemented/recognized yet by Emogrifier).
972
     *
973
     * @throws ParseException in debug mode, if an invalid selector is encountered
974
     * @throws \RuntimeException in debug mode, if `CssSelectorConverter::toXPath` returns an invalid XPath expression
975
     */
976
    private function existsMatchForCssSelector(string $cssSelector): bool
581✔
977
    {
978
        try {
979
            $nodesMatchingSelector
581✔
980
                = $this->querySelectorAll($cssSelector, [self::QSA_ALWAYS_THROW_PARSE_EXCEPTION => true]);
581✔
981
        } catch (ParseException $e) {
2✔
982
            if ($this->debug) {
2✔
983
                throw $e;
1✔
984
            }
985
            return true;
1✔
986
        }
987

988
        return $nodesMatchingSelector->length !== 0;
579✔
989
    }
990

991
    /**
992
     * Removes pseudo-elements and dynamic pseudo-classes from a CSS selector, replacing them with "*" if necessary.
993
     * If such a pseudo-component is within the argument of `:not`, the entire `:not` component is removed or replaced.
994
     *
995
     * @return string
996
     *         selector which will match the relevant DOM elements if the pseudo-classes are assumed to apply, or in the
997
     *         case of pseudo-elements will match their originating element
998
     */
999
    private function removeUnmatchablePseudoComponents(string $selector): string
449✔
1000
    {
1001
        // The regex allows nested brackets via `(?2)`.
1002
        // A space is temporarily prepended because the callback can't determine if the match was at the very start.
1003
        $pattern = '/([\\s>+~]?+):not(\\([^()]*+(?:(?2)[^()]*+)*+\\))/i';
449✔
1004
        /** @param array<array-key, string> $matches */
1005
        $callback = function (array $matches): string {
449✔
1006
            return $this->replaceUnmatchableNotComponent($matches);
60✔
1007
        };
449✔
1008
        if (\function_exists('Safe\\preg_replace_callback')) {
449✔
1009
            $untrimmedSelectorWithoutNots = preg_replace_callback($pattern, $callback, ' ' . $selector);
449✔
1010
        } else {
1011
            // @phpstan-ignore-next-line The safe version is only available in "thecodingmachine/safe" for PHP >= 8.1.
UNCOV
1012
            $untrimmedSelectorWithoutNots = \preg_replace_callback($pattern, $callback, ' ' . $selector);
×
1013
            \assert(\is_string($untrimmedSelectorWithoutNots));
×
1014
        }
1015
        $selectorWithoutNots = \ltrim($untrimmedSelectorWithoutNots);
449✔
1016

1017
        $selectorWithoutUnmatchablePseudoComponents = $this->removeSelectorComponents(
449✔
1018
            ':(?!' . self::PSEUDO_CLASS_MATCHER . '):?+[\\w\\-]++(?:\\([^\\)]*+\\))?+',
449✔
1019
            $selectorWithoutNots
449✔
1020
        );
449✔
1021

1022
        if (preg_match(
449✔
1023
            '/:(?:' . self::OF_TYPE_PSEUDO_CLASS_MATCHER . ')/i',
449✔
1024
            $selectorWithoutUnmatchablePseudoComponents
449✔
1025
        ) === 0) {
449✔
1026
            return $selectorWithoutUnmatchablePseudoComponents;
382✔
1027
        }
1028

1029
        $selectorParts = preg_split(
67✔
1030
            '/(' . self::COMBINATOR_MATCHER . ')/',
67✔
1031
            $selectorWithoutUnmatchablePseudoComponents,
67✔
1032
            -1,
67✔
1033
            PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
67✔
1034
        );
67✔
1035
        /** @var list<string> $selectorParts */
1036

1037
        return \implode('', \array_map(
67✔
1038
            function (string $selectorPart): string {
67✔
1039
                return $this->removeUnsupportedOfTypePseudoClasses($selectorPart);
67✔
1040
            },
67✔
1041
            $selectorParts
67✔
1042
        ));
67✔
1043
    }
1044

1045
    /**
1046
     * Helps `removeUnmatchablePseudoComponents()` replace or remove a selector `:not(...)` component if its argument
1047
     * contains pseudo-elements or dynamic pseudo-classes.
1048
     *
1049
     * @param array<array-key, string> $matches array of elements matched by the regular expression
1050
     *
1051
     * @return string
1052
     *         the full match if there were no unmatchable pseudo components within; otherwise, any preceding combinator
1053
     *         followed by "*", or an empty string if there was no preceding combinator
1054
     */
1055
    private function replaceUnmatchableNotComponent(array $matches): string
60✔
1056
    {
1057
        [$notComponentWithAnyPrecedingCombinator, $anyPrecedingCombinator, $notArgumentInBrackets] = $matches;
60✔
1058

1059
        if ($this->hasUnsupportedPseudoClass($notArgumentInBrackets)) {
60✔
1060
            return $anyPrecedingCombinator !== '' ? $anyPrecedingCombinator . '*' : '';
54✔
1061
        }
1062
        return $notComponentWithAnyPrecedingCombinator;
8✔
1063
    }
1064

1065
    /**
1066
     * Removes components from a CSS selector, replacing them with "*" if necessary.
1067
     *
1068
     * @param string $matcher regular expression part to match the components to remove
1069
     *
1070
     * @return string
1071
     *         selector which will match the relevant DOM elements if the removed components are assumed to apply (or in
1072
     *         the case of pseudo-elements will match their originating element)
1073
     */
1074
    private function removeSelectorComponents(string $matcher, string $selector): string
449✔
1075
    {
1076
        return preg_replace(
449✔
1077
            ['/([\\s>+~]|^)' . $matcher . '/i', '/' . $matcher . '/i'],
449✔
1078
            ['$1*', ''],
449✔
1079
            $selector
449✔
1080
        );
449✔
1081
    }
1082

1083
    /**
1084
     * Removes any `...-of-type` pseudo-classes from part of a CSS selector, if it does not have a type, replacing them
1085
     * with "*" if necessary.
1086
     *
1087
     * @param string $selectorPart part of a selector which has been split up at combinators
1088
     *
1089
     * @return string
1090
     *         selector part which will match the relevant DOM elements if the pseudo-classes are assumed to apply
1091
     */
1092
    private function removeUnsupportedOfTypePseudoClasses(string $selectorPart): string
67✔
1093
    {
1094
        if (!$this->selectorPartHasUnsupportedOfTypePseudoClass($selectorPart)) {
67✔
1095
            return $selectorPart;
44✔
1096
        }
1097

1098
        return $this->removeSelectorComponents(
67✔
1099
            ':(?:' . self::OF_TYPE_PSEUDO_CLASS_MATCHER . ')(?:\\([^\\)]*+\\))?+',
67✔
1100
            $selectorPart
67✔
1101
        );
67✔
1102
    }
1103

1104
    /**
1105
     * Applies `$this->matchingUninlinableCssRules` to `$this->domDocument` by placing them as CSS in a `<style>`
1106
     * element.
1107
     * If there are no uninlinable CSS rules to copy there, a `<style>` element will be created containing only the
1108
     * applicable at-rules from `$parsedCss`.
1109
     * If there are none of either, an empty `<style>` element will not be created.
1110
     *
1111
     * @param CssDocument $parsedCss
1112
     *        This may contain various at-rules whose content `CssInliner` does not currently attempt to inline or
1113
     *        process in any other way, such as `@import`, `@font-face`, `@keyframes`, etc., and which should precede
1114
     *        the processed but found-to-be-uninlinable CSS placed in the `<style>` element.
1115
     *        Note that `CssInliner` processes `@media` rules so that they can be ordered correctly with respect to
1116
     *        other uninlinable rules; these will not be duplicated from `$parsedCss`.
1117
     */
1118
    private function copyUninlinableCssToStyleNode(CssDocument $parsedCss): void
1,166✔
1119
    {
1120
        $css = $parsedCss->renderNonConditionalAtRules();
1,166✔
1121

1122
        // avoid including unneeded class dependency if there are no rules
1123
        if ($this->getMatchingUninlinableCssRules() !== []) {
1,166✔
1124
            $cssConcatenator = new CssConcatenator();
435✔
1125
            foreach ($this->getMatchingUninlinableCssRules() as $cssRule) {
435✔
1126
                $cssConcatenator->append([$cssRule['selector']], $cssRule['declarationsBlock'], $cssRule['media']);
435✔
1127
            }
1128
            $css .= $cssConcatenator->getCss();
435✔
1129
        }
1130

1131
        // avoid adding empty style element
1132
        if ($css !== '') {
1,166✔
1133
            $this->addStyleElementToDocument($css);
470✔
1134
        }
1135
    }
1136

1137
    /**
1138
     * Adds a style element with `$css` to `$this->domDocument`.
1139
     *
1140
     * This method is protected to allow overriding.
1141
     *
1142
     * @see https://github.com/MyIntervals/emogrifier/issues/103
1143
     */
1144
    protected function addStyleElementToDocument(string $css): void
470✔
1145
    {
1146
        $domDocument = $this->getDomDocument();
470✔
1147
        $styleElement = $domDocument->createElement('style', $css);
470✔
1148
        $styleAttribute = $domDocument->createAttribute('type');
470✔
1149
        $styleAttribute->value = 'text/css';
470✔
1150
        $styleElement->appendChild($styleAttribute);
470✔
1151

1152
        $headElement = $this->getHeadElement();
470✔
1153
        $headElement->appendChild($styleElement);
470✔
1154
    }
1155

1156
    /**
1157
     * Returns the `HEAD` element.
1158
     *
1159
     * This method assumes that there always is a HEAD element.
1160
     *
1161
     * @throws \UnexpectedValueException
1162
     */
1163
    private function getHeadElement(): \DOMElement
470✔
1164
    {
1165
        $node = $this->getDomDocument()->getElementsByTagName('head')->item(0);
470✔
1166
        if (!$node instanceof \DOMElement) {
470✔
UNCOV
1167
            throw new \UnexpectedValueException('There is no HEAD element. This should never happen.', 1617923227);
×
1168
        }
1169

1170
        return $node;
470✔
1171
    }
1172
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc