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

MyIntervals / emogrifier / 22984522063

12 Mar 2026 02:56AM UTC coverage: 96.224% (+0.008%) from 96.216%
22984522063

Pull #1598

github

web-flow
Merge 5eac6f5fa into e1130f61d
Pull Request #1598: [CLEANUP] Have specific methods for PCRE callbacks

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

12 existing lines in 1 file now uncovered.

841 of 874 relevant lines covered (96.22%)

257.72 hits per line

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

95.47
/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
        $pattern = '/-{0,2}+[_a-zA-Z][\\w\\-]*+(?=:)/S';
42✔
439
        $callback = \Closure::fromCallable([self::class, 'normalizePropertyNameCallback']);
42✔
440
        if (\function_exists('Safe\\preg_replace_callback')) {
42✔
441
            $normalizedOriginalStyle = preg_replace_callback($pattern, $callback, $node->getAttribute('style'));
42✔
442
        } else {
443
            // @phpstan-ignore-next-line The safe version is only available in "thecodingmachine/safe" for PHP >= 8.1.
UNCOV
444
            $normalizedOriginalStyle = \preg_replace_callback($pattern, $callback, $node->getAttribute('style'));
×
UNCOV
445
            \assert(\is_string($normalizedOriginalStyle));
×
446
        }
447

448
        // In order to not overwrite existing style attributes in the HTML, we have to save the original HTML styles.
449
        $nodePath = $node->getNodePath();
42✔
450
        if (\is_string($nodePath) && ($nodePath !== '') && !isset($this->styleAttributesForNodes[$nodePath])) {
42✔
451
            $this->styleAttributesForNodes[$nodePath] = (new DeclarationBlockParser())->parse($normalizedOriginalStyle);
42✔
452
            $this->visitedNodes[$nodePath] = $node;
42✔
453
        }
454

455
        $node->setAttribute('style', $normalizedOriginalStyle);
42✔
456
    }
457

458
    /**
459
     * @param array<mixed> $matches
460
     *        A narrower type cannot be specified because it's a callback that may be passed different types in the
461
     *        array, depending on the flags provided to `preg_replace_callback()` (which are not actually used).
462
     *
463
     * @internal This method is only public so it can be used as a callback via the 'Safe' library.
464
     */
465
    public static function normalizePropertyNameCallback(array $matches): string
42✔
466
    {
467
        \assert(\is_string($matches[0]));
42✔
468
        \assert($matches[0] !== '');
42✔
469
        return (new DeclarationBlockParser())->normalizePropertyName($matches[0]);
42✔
470
    }
471

472
    /**
473
     * Returns CSS content.
474
     */
475
    private function getCssFromAllStyleNodes(): string
1,169✔
476
    {
477
        $styleNodes = $this->getXPath()->query('//style');
1,169✔
478
        if ($styleNodes === false) {
1,169✔
UNCOV
479
            return '';
×
480
        }
481

482
        $css = '';
1,169✔
483
        foreach ($styleNodes as $styleNode) {
1,169✔
484
            \assert($styleNode instanceof \DOMNode);
39✔
485
            if (\is_string($styleNode->nodeValue)) {
39✔
486
                $css .= "\n\n" . $styleNode->nodeValue;
39✔
487
            }
488
            $parentNode = $styleNode->parentNode;
39✔
489
            if ($parentNode instanceof \DOMNode) {
39✔
490
                $parentNode->removeChild($styleNode);
39✔
491
            }
492
        }
493

494
        return $css;
1,169✔
495
    }
496

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

515
        return $excludedNodes;
1,166✔
516
    }
517

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

534
            if ($result === false) {
1,061✔
UNCOV
535
                throw new \RuntimeException('query failed with selector \'' . $selectors . '\'', 1726533051);
×
536
            }
537
            /** @var \DOMNodeList<\DOMElement> $result */
538

539
            return $result;
1,061✔
540
        } catch (ParseException $exception) {
5✔
541
            $alwaysThrowParseException = $options[self::QSA_ALWAYS_THROW_PARSE_EXCEPTION] ?? false;
5✔
542
            if ($this->debug || $alwaysThrowParseException) {
5✔
543
                throw $exception;
3✔
544
            }
545
            $list = new \DOMNodeList();
2✔
546
            /** @var \DOMNodeList<\DOMElement> $list */
547
            return $list;
2✔
UNCOV
548
        } catch (\RuntimeException $exception) {
×
549
            if (
UNCOV
550
                $this->debug
×
551
            ) {
UNCOV
552
                throw $exception;
×
553
            }
554
            // `RuntimeException` indicates a bug in CssSelector so pass the message to the error handler.
UNCOV
555
            \trigger_error($exception->getMessage());
×
556
            $list = new \DOMNodeList();
×
557
            /** @var \DOMNodeList<\DOMElement> $list */
UNCOV
558
            return $list;
×
559
        }
560
    }
561

562
    /**
563
     * @throws \UnexpectedValueException if `$node` is not a `DOMElement`
564
     */
565
    private function ensureNodeIsElement(\DOMNode $node): \DOMElement
466✔
566
    {
567
        if (!($node instanceof \DOMElement)) {
466✔
UNCOV
568
            $path = $node->getNodePath() ?? '$node';
×
569
            throw new \UnexpectedValueException($path . ' is not a DOMElement.', 1617975914);
×
570
        }
571

572
        return $node;
466✔
573
    }
574

575
    private function getCssSelectorConverter(): CssSelectorConverter
1,065✔
576
    {
577
        if (!$this->cssSelectorConverter instanceof CssSelectorConverter) {
1,065✔
578
            $this->cssSelectorConverter = new CssSelectorConverter();
1,065✔
579
        }
580

581
        return $this->cssSelectorConverter;
1,065✔
582
    }
583

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

610
        $cssRules = [
1,166✔
611
            'inlinable' => [],
1,166✔
612
            'uninlinable' => [],
1,166✔
613
        ];
1,166✔
614
        foreach ($matches as $key => $cssRule) {
1,166✔
615
            if (!$cssRule->hasAtLeastOneDeclaration()) {
1,066✔
616
                continue;
3✔
617
            }
618

619
            $mediaQuery = $cssRule->getContainingAtRule();
1,063✔
620
            $declarationsBlock = $cssRule->getDeclarationsAsText();
1,063✔
621
            $selectors = $cssRule->getSelectors();
1,063✔
622

623
            // Maybe exclude CSS selectors
624
            if (\count($this->excludedCssSelectors) > 0) {
1,063✔
625
                // Normalize spaces, line breaks & tabs
626
                $selectorsNormalized = \array_map(static function (string $selector): string {
5✔
627
                    return preg_replace('@\\s++@u', ' ', $selector);
5✔
628
                }, $selectors);
5✔
629
                /** @var array<non-empty-string> $selectors */
630
                $selectors = \array_filter($selectorsNormalized, function (string $selector): bool {
5✔
631
                    return !isset($this->excludedCssSelectors[$selector]);
5✔
632
                });
5✔
633
            }
634

635
            foreach ($selectors as $selector) {
1,063✔
636
                // don't process pseudo-elements and behavioral (dynamic) pseudo-classes;
637
                // only allow structural pseudo-classes
638
                $hasPseudoElement = \strpos($selector, '::') !== false;
1,063✔
639
                $hasUnmatchablePseudo = $hasPseudoElement || $this->hasUnsupportedPseudoClass($selector);
1,063✔
640

641
                $parsedCssRule = [
1,063✔
642
                    'media' => $mediaQuery,
1,063✔
643
                    'selector' => $selector,
1,063✔
644
                    'hasUnmatchablePseudo' => $hasUnmatchablePseudo,
1,063✔
645
                    'declarationsBlock' => $declarationsBlock,
1,063✔
646
                    // keep track of where it appears in the file, since order is important
647
                    'line' => $key,
1,063✔
648
                ];
1,063✔
649
                $ruleType = (!$cssRule->hasContainingAtRule() && !$hasUnmatchablePseudo) ? 'inlinable' : 'uninlinable';
1,063✔
650
                $cssRules[$ruleType][] = $parsedCssRule;
1,063✔
651
            }
652
        }
653

654
        \usort(
1,166✔
655
            $cssRules['inlinable'],
1,166✔
656
            /**
657
             * @param array{selector: non-empty-string, line: int<0, max>} $first
658
             * @param array{selector: non-empty-string, line: int<0, max>} $second
659
             */
660
            function (array $first, array $second): int {
1,166✔
661
                return $this->sortBySelectorPrecedence($first, $second);
75✔
662
            }
1,166✔
663
        );
1,166✔
664

665
        return $cssRules;
1,166✔
666
    }
667

668
    /**
669
     * Tests if a selector contains a pseudo-class which would mean it cannot be converted to an XPath expression for
670
     * inlining CSS declarations.
671
     *
672
     * Any pseudo class that does not match {@see PSEUDO_CLASS_MATCHER} cannot be converted.  Additionally, `...of-type`
673
     * pseudo-classes cannot be converted if they are not associated with a type selector.
674
     */
675
    private function hasUnsupportedPseudoClass(string $selector): bool
1,006✔
676
    {
677
        if (preg_match('/:(?!' . self::PSEUDO_CLASS_MATCHER . ')[\\w\\-]/i', $selector) !== 0) {
1,006✔
678
            return true;
323✔
679
        }
680

681
        if (preg_match('/:(?:' . self::OF_TYPE_PSEUDO_CLASS_MATCHER . ')/i', $selector) === 0) {
788✔
682
            return false;
668✔
683
        }
684

685
        foreach (preg_split('/' . self::COMBINATOR_MATCHER . '/', $selector) as $selectorPart) {
120✔
686
            \assert(\is_string($selectorPart));
120✔
687
            if ($this->selectorPartHasUnsupportedOfTypePseudoClass($selectorPart)) {
120✔
688
                return true;
67✔
689
            }
690
        }
691

692
        return false;
53✔
693
    }
694

695
    /**
696
     * Tests if part of a selector contains an `...of-type` pseudo-class such that it cannot be converted to an XPath
697
     * expression.
698
     *
699
     * @param string $selectorPart part of a selector which has been split up at combinators
700
     *
701
     * @return bool `true` if the selector part does not have a type but does have an `...of-type` pseudo-class
702
     */
703
    private function selectorPartHasUnsupportedOfTypePseudoClass(string $selectorPart): bool
120✔
704
    {
705
        if (preg_match('/^[\\w\\-]/', $selectorPart) !== 0) {
120✔
706
            return false;
97✔
707
        }
708

709
        return preg_match('/:(?:' . self::OF_TYPE_PSEUDO_CLASS_MATCHER . ')/i', $selectorPart) !== 0;
67✔
710
    }
711

712
    /**
713
     * @param array{selector: non-empty-string, line: int<0, max>} $first
714
     * @param array{selector: non-empty-string, line: int<0, max>} $second
715
     */
716
    private function sortBySelectorPrecedence(array $first, array $second): int
75✔
717
    {
718
        $precedenceOfFirst = $this->getCssSelectorPrecedence($first['selector']);
75✔
719
        $precedenceOfSecond = $this->getCssSelectorPrecedence($second['selector']);
75✔
720

721
        // We want these sorted in ascending order so selectors with lesser precedence get processed first and
722
        // selectors with greater precedence get sorted last.
723
        $precedenceForEquals = $first['line'] < $second['line'] ? -1 : 1;
75✔
724
        $precedenceForNotEquals = $precedenceOfFirst < $precedenceOfSecond ? -1 : 1;
75✔
725
        return ($precedenceOfFirst === $precedenceOfSecond) ? $precedenceForEquals : $precedenceForNotEquals;
75✔
726
    }
727

728
    /**
729
     * @param non-empty-string $selector
730
     *
731
     * @return int<0, max>
732
     */
733
    private function getCssSelectorPrecedence(string $selector): int
75✔
734
    {
735
        $selectorKey = $selector;
75✔
736
        if (isset($this->caches[self::CACHE_KEY_SELECTOR][$selectorKey])) {
75✔
737
            return $this->caches[self::CACHE_KEY_SELECTOR][$selectorKey];
68✔
738
        }
739

740
        $precedence = 0;
75✔
741
        foreach ($this->selectorPrecedenceMatchers as $matcher => $value) {
75✔
742
            if (\trim($selector) === '') {
75✔
743
                break;
8✔
744
            }
745
            $count = 0;
75✔
746
            $selector = preg_replace('/' . $matcher . '\\w+/', '', $selector, -1, $count);
75✔
747
            $precedence += ($value * $count);
75✔
748
            \assert($precedence >= 0);
75✔
749
        }
750
        $this->caches[self::CACHE_KEY_SELECTOR][$selectorKey] = $precedence;
75✔
751

752
        return $precedence;
75✔
753
    }
754

755
    /**
756
     * Copies `$cssRule` into the style attribute of `$node`.
757
     *
758
     * Note: This method does not check whether $cssRule matches $node.
759
     *
760
     * @param array{
761
     *            media: string,
762
     *            selector: non-empty-string,
763
     *            hasUnmatchablePseudo: bool,
764
     *            declarationsBlock: string,
765
     *            line: int<0, max>
766
     *        } $cssRule
767
     */
768
    private function copyInlinableCssToStyleAttribute(\DOMElement $node, array $cssRule): void
464✔
769
    {
770
        $declarationsBlock = $cssRule['declarationsBlock'];
464✔
771
        $declarationBlockParser = new DeclarationBlockParser();
464✔
772
        $newStyleDeclarations = $declarationBlockParser->parse($declarationsBlock);
464✔
773
        if ($newStyleDeclarations === []) {
464✔
774
            return;
1✔
775
        }
776

777
        // if it has a style attribute, get it, process it, and append (overwrite) new stuff
778
        if ($node->hasAttribute('style')) {
463✔
779
            // break it up into an associative array
780
            $oldStyleDeclarations = $declarationBlockParser->parse($node->getAttribute('style'));
67✔
781
        } else {
782
            $oldStyleDeclarations = [];
463✔
783
        }
784
        $node->setAttribute(
463✔
785
            'style',
463✔
786
            $this->generateStyleStringFromDeclarationsArrays($oldStyleDeclarations, $newStyleDeclarations)
463✔
787
        );
463✔
788
    }
789

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

809
        // Unset the overridden styles to preserve order, important if shorthand and individual properties are mixed
810
        foreach ($oldStyles as $attributeName => $attributeValue) {
482✔
811
            if (!isset($newStyles[$attributeName])) {
87✔
812
                continue;
64✔
813
            }
814

815
            $newAttributeValue = $newStyles[$attributeName];
74✔
816
            if (
817
                $this->attributeValueIsImportant($attributeValue)
74✔
818
                && !$this->attributeValueIsImportant($newAttributeValue)
74✔
819
            ) {
820
                unset($newStyles[$attributeName]);
11✔
821
            } else {
822
                unset($oldStyles[$attributeName]);
63✔
823
            }
824
        }
825

826
        $combinedStyles = \array_merge($oldStyles, $newStyles);
482✔
827

828
        $declarationBlockParser = new DeclarationBlockParser();
482✔
829
        $style = '';
482✔
830
        foreach ($combinedStyles as $attributeName => $attributeValue) {
482✔
831
            $trimmedAttributeName = \trim($attributeName);
482✔
832
            if ($trimmedAttributeName === '') {
482✔
UNCOV
833
                throw new \UnexpectedValueException('An empty property name was encountered.', 1727046078);
×
834
            }
835
            $propertyName = $declarationBlockParser->normalizePropertyName($trimmedAttributeName);
482✔
836
            $propertyValue = \trim($attributeValue);
482✔
837
            $style .= $propertyName . ': ' . $propertyValue . '; ';
482✔
838
        }
839
        $trimmedStyle = \rtrim($style);
482✔
840

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

843
        return $trimmedStyle;
482✔
844
    }
845

846
    /**
847
     * Checks whether `$attributeValue` is marked as `!important`.
848
     */
849
    private function attributeValueIsImportant(string $attributeValue): bool
482✔
850
    {
851
        return preg_match('/!\\s*+important$/i', $attributeValue) !== 0;
482✔
852
    }
853

854
    /**
855
     * Merges styles from styles attributes and style nodes and applies them to the attribute nodes
856
     */
857
    private function fillStyleAttributesWithMergedStyles(): void
1,164✔
858
    {
859
        $declarationBlockParser = new DeclarationBlockParser();
1,164✔
860
        foreach ($this->styleAttributesForNodes as $nodePath => $styleAttributesForNode) {
1,164✔
861
            $node = $this->visitedNodes[$nodePath];
42✔
862
            $currentStyleAttributes = $declarationBlockParser->parse($node->getAttribute('style'));
42✔
863
            $node->setAttribute(
42✔
864
                'style',
42✔
865
                $this->generateStyleStringFromDeclarationsArrays(
42✔
866
                    $currentStyleAttributes,
42✔
867
                    $styleAttributesForNode
42✔
868
                )
42✔
869
            );
42✔
870
        }
871
    }
872

873
    /**
874
     * Searches for all nodes with a style attribute and removes the "!important" annotations out of
875
     * the inline style declarations, eventually by rearranging declarations.
876
     *
877
     * @throws \RuntimeException
878
     */
879
    private function removeImportantAnnotationFromAllInlineStyles(): void
1,166✔
880
    {
881
        foreach ($this->getAllNodesWithStyleAttribute() as $node) {
1,166✔
882
            $this->removeImportantAnnotationFromNodeInlineStyle($node);
482✔
883
        }
884
    }
885

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

919
    /**
920
     * Generates a CSS style string suitable to be used inline from the $styleDeclarations property => value array.
921
     *
922
     * @param array<string, string> $styleDeclarations
923
     */
924
    private function generateStyleStringFromSingleDeclarationsArray(array $styleDeclarations): string
482✔
925
    {
926
        return $this->generateStyleStringFromDeclarationsArrays([], $styleDeclarations);
482✔
927
    }
928

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

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

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

998
        return $nodesMatchingSelector->length !== 0;
579✔
999
    }
1000

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

1024
        $selectorWithoutUnmatchablePseudoComponents = $this->removeSelectorComponents(
449✔
1025
            ':(?!' . self::PSEUDO_CLASS_MATCHER . '):?+[\\w\\-]++(?:\\([^\\)]*+\\))?+',
449✔
1026
            $selectorWithoutNots
449✔
1027
        );
449✔
1028

1029
        if (preg_match(
449✔
1030
            '/:(?:' . self::OF_TYPE_PSEUDO_CLASS_MATCHER . ')/i',
449✔
1031
            $selectorWithoutUnmatchablePseudoComponents
449✔
1032
        ) === 0) {
449✔
1033
            return $selectorWithoutUnmatchablePseudoComponents;
382✔
1034
        }
1035

1036
        $selectorParts = preg_split(
67✔
1037
            '/(' . self::COMBINATOR_MATCHER . ')/',
67✔
1038
            $selectorWithoutUnmatchablePseudoComponents,
67✔
1039
            -1,
67✔
1040
            PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
67✔
1041
        );
67✔
1042
        /** @var list<string> $selectorParts */
1043

1044
        return \implode('', \array_map(
67✔
1045
            function (string $selectorPart): string {
67✔
1046
                return $this->removeUnsupportedOfTypePseudoClasses($selectorPart);
67✔
1047
            },
67✔
1048
            $selectorParts
67✔
1049
        ));
67✔
1050
    }
1051

1052
    /**
1053
     * Helps `removeUnmatchablePseudoComponents()` replace or remove a selector `:not(...)` component if its argument
1054
     * contains pseudo-elements or dynamic pseudo-classes.
1055
     *
1056
     * @param array<mixed> $matches
1057
     *        This is an array of elements matched by the regular expression.
1058
     *        A narrower type cannot be specified because it's a callback that may be passed different types in the
1059
     *        array, depending on the flags provided to `preg_replace_callback()` (which are not actually used).
1060
     *
1061
     * @return string
1062
     *         the full match if there were no unmatchable pseudo components within; otherwise, any preceding combinator
1063
     *         followed by "*", or an empty string if there was no preceding combinator
1064
     *
1065
     * @internal This method is only public so it can be used as a callback via the 'Safe' library.
1066
     */
1067
    public function replaceUnmatchableNotComponent(array $matches): string
60✔
1068
    {
1069
        [$notComponentWithAnyPrecedingCombinator, $anyPrecedingCombinator, $notArgumentInBrackets] = $matches;
60✔
1070
        \assert(\is_string($notComponentWithAnyPrecedingCombinator));
60✔
1071
        \assert(\is_string($anyPrecedingCombinator));
60✔
1072
        \assert(\is_string($notArgumentInBrackets));
60✔
1073

1074
        if ($this->hasUnsupportedPseudoClass($notArgumentInBrackets)) {
60✔
1075
            return $anyPrecedingCombinator !== '' ? $anyPrecedingCombinator . '*' : '';
54✔
1076
        }
1077
        return $notComponentWithAnyPrecedingCombinator;
8✔
1078
    }
1079

1080
    /**
1081
     * Removes components from a CSS selector, replacing them with "*" if necessary.
1082
     *
1083
     * @param string $matcher regular expression part to match the components to remove
1084
     *
1085
     * @return string
1086
     *         selector which will match the relevant DOM elements if the removed components are assumed to apply (or in
1087
     *         the case of pseudo-elements will match their originating element)
1088
     */
1089
    private function removeSelectorComponents(string $matcher, string $selector): string
449✔
1090
    {
1091
        return preg_replace(
449✔
1092
            ['/([\\s>+~]|^)' . $matcher . '/i', '/' . $matcher . '/i'],
449✔
1093
            ['$1*', ''],
449✔
1094
            $selector
449✔
1095
        );
449✔
1096
    }
1097

1098
    /**
1099
     * Removes any `...-of-type` pseudo-classes from part of a CSS selector, if it does not have a type, replacing them
1100
     * with "*" if necessary.
1101
     *
1102
     * @param string $selectorPart part of a selector which has been split up at combinators
1103
     *
1104
     * @return string
1105
     *         selector part which will match the relevant DOM elements if the pseudo-classes are assumed to apply
1106
     */
1107
    private function removeUnsupportedOfTypePseudoClasses(string $selectorPart): string
67✔
1108
    {
1109
        if (!$this->selectorPartHasUnsupportedOfTypePseudoClass($selectorPart)) {
67✔
1110
            return $selectorPart;
44✔
1111
        }
1112

1113
        return $this->removeSelectorComponents(
67✔
1114
            ':(?:' . self::OF_TYPE_PSEUDO_CLASS_MATCHER . ')(?:\\([^\\)]*+\\))?+',
67✔
1115
            $selectorPart
67✔
1116
        );
67✔
1117
    }
1118

1119
    /**
1120
     * Applies `$this->matchingUninlinableCssRules` to `$this->domDocument` by placing them as CSS in a `<style>`
1121
     * element.
1122
     * If there are no uninlinable CSS rules to copy there, a `<style>` element will be created containing only the
1123
     * applicable at-rules from `$parsedCss`.
1124
     * If there are none of either, an empty `<style>` element will not be created.
1125
     *
1126
     * @param CssDocument $parsedCss
1127
     *        This may contain various at-rules whose content `CssInliner` does not currently attempt to inline or
1128
     *        process in any other way, such as `@import`, `@font-face`, `@keyframes`, etc., and which should precede
1129
     *        the processed but found-to-be-uninlinable CSS placed in the `<style>` element.
1130
     *        Note that `CssInliner` processes `@media` rules so that they can be ordered correctly with respect to
1131
     *        other uninlinable rules; these will not be duplicated from `$parsedCss`.
1132
     */
1133
    private function copyUninlinableCssToStyleNode(CssDocument $parsedCss): void
1,166✔
1134
    {
1135
        $css = $parsedCss->renderNonConditionalAtRules();
1,166✔
1136

1137
        // avoid including unneeded class dependency if there are no rules
1138
        if ($this->getMatchingUninlinableCssRules() !== []) {
1,166✔
1139
            $cssConcatenator = new CssConcatenator();
435✔
1140
            foreach ($this->getMatchingUninlinableCssRules() as $cssRule) {
435✔
1141
                $cssConcatenator->append([$cssRule['selector']], $cssRule['declarationsBlock'], $cssRule['media']);
435✔
1142
            }
1143
            $css .= $cssConcatenator->getCss();
435✔
1144
        }
1145

1146
        // avoid adding empty style element
1147
        if ($css !== '') {
1,166✔
1148
            $this->addStyleElementToDocument($css);
470✔
1149
        }
1150
    }
1151

1152
    /**
1153
     * Adds a style element with `$css` to `$this->domDocument`.
1154
     *
1155
     * This method is protected to allow overriding.
1156
     *
1157
     * @see https://github.com/MyIntervals/emogrifier/issues/103
1158
     */
1159
    protected function addStyleElementToDocument(string $css): void
470✔
1160
    {
1161
        $domDocument = $this->getDomDocument();
470✔
1162
        $styleElement = $domDocument->createElement('style', $css);
470✔
1163
        $styleAttribute = $domDocument->createAttribute('type');
470✔
1164
        $styleAttribute->value = 'text/css';
470✔
1165
        $styleElement->appendChild($styleAttribute);
470✔
1166

1167
        $headElement = $this->getHeadElement();
470✔
1168
        $headElement->appendChild($styleElement);
470✔
1169
    }
1170

1171
    /**
1172
     * Returns the `HEAD` element.
1173
     *
1174
     * This method assumes that there always is a HEAD element.
1175
     *
1176
     * @throws \UnexpectedValueException
1177
     */
1178
    private function getHeadElement(): \DOMElement
470✔
1179
    {
1180
        $node = $this->getDomDocument()->getElementsByTagName('head')->item(0);
470✔
1181
        if (!$node instanceof \DOMElement) {
470✔
1182
            throw new \UnexpectedValueException('There is no HEAD element. This should never happen.', 1617923227);
×
1183
        }
1184

1185
        return $node;
470✔
1186
    }
1187
}
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