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

MyIntervals / emogrifier / 24654429321

20 Apr 2026 07:39AM UTC coverage: 96.778% (+0.3%) from 96.445%
24654429321

Pull #1616

github

web-flow
Merge e38165aca into 0bfe77e7a
Pull Request #1616: [CLEANUP] Replace some exceptions with assertions

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

10 existing lines in 1 file now uncovered.

841 of 869 relevant lines covered (96.78%)

256.81 hits per line

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

96.21
/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
    private function getAllNodesWithStyleAttribute(): \DOMNodeList
1,171✔
420
    {
421
        $query = '//*[@style]';
1,171✔
422
        $matches = $this->getXPath()->query($query);
1,171✔
423
        \assert($matches instanceof \DOMNodeList);
1,171✔
424
        /** @var \DOMNodeList<\DOMElement> $matches */
425

426
        return $matches;
1,171✔
427
    }
428

429
    /**
430
     * Normalizes the value of the "style" attribute and saves it.
431
     */
432
    private function normalizeStyleAttributes(\DOMElement $node): void
42✔
433
    {
434
        $pattern = '/-{0,2}+[_a-zA-Z][\\w\\-]*+(?=:)/S';
42✔
435
        $callback = \Closure::fromCallable([self::class, 'normalizePropertyNameCallback']);
42✔
436
        if (\function_exists('Safe\\preg_replace_callback')) {
42✔
437
            $normalizedOriginalStyle = preg_replace_callback($pattern, $callback, $node->getAttribute('style'));
42✔
438
        } else {
439
            // @phpstan-ignore-next-line The safe version is only available in "thecodingmachine/safe" for PHP >= 8.1.
440
            $normalizedOriginalStyle = \preg_replace_callback($pattern, $callback, $node->getAttribute('style'));
×
441
            \assert(\is_string($normalizedOriginalStyle));
×
442
        }
443

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

451
        $node->setAttribute('style', $normalizedOriginalStyle);
42✔
452
    }
453

454
    /**
455
     * @param array<mixed> $matches
456
     *        A narrower type cannot be specified because it's a callback that may be passed different types in the
457
     *        array, depending on the flags provided to `preg_replace_callback()` (which are not actually used),
458
     *        and `Safe\preg_replace_callback()` does not have type annotations to cater for this.
459
     */
460
    private static function normalizePropertyNameCallback(array $matches): string
42✔
461
    {
462
        \assert(\is_string($matches[0] ?? null));
42✔
463
        \assert($matches[0] !== '');
42✔
464
        return DeclarationBlockParser::normalizePropertyName($matches[0]);
42✔
465
    }
466

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

477
        $css = '';
1,169✔
478
        foreach ($styleNodes as $styleNode) {
1,169✔
479
            \assert($styleNode instanceof \DOMNode);
39✔
480
            if (\is_string($styleNode->nodeValue)) {
39✔
481
                $css .= "\n\n" . $styleNode->nodeValue;
39✔
482
            }
483
            $parentNode = $styleNode->parentNode;
39✔
484
            if ($parentNode instanceof \DOMNode) {
39✔
485
                $parentNode->removeChild($styleNode);
39✔
486
            }
487
        }
488

489
        return $css;
1,169✔
490
    }
491

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

510
        return $excludedNodes;
1,166✔
511
    }
512

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

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

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

564
        return $node;
466✔
565
    }
566

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

573
        return $this->cssSelectorConverter;
1,065✔
574
    }
575

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

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

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

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

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

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

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

657
        return $cssRules;
1,166✔
658
    }
659

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

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

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

684
        return false;
53✔
685
    }
686

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

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

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

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

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

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

744
        return $precedence;
75✔
745
    }
746

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

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

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

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

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

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

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
        foreach ($this->styleAttributesForNodes as $nodePath => $styleAttributesForNode) {
1,164✔
850
            $node = $this->visitedNodes[$nodePath];
42✔
851
            $currentStyleAttributes = DeclarationBlockParser::parse($node->getAttribute('style'));
42✔
852
            $node->setAttribute(
42✔
853
                'style',
42✔
854
                $this->generateStyleStringFromDeclarationsArrays(
42✔
855
                    $currentStyleAttributes,
42✔
856
                    $styleAttributesForNode
42✔
857
                )
42✔
858
            );
42✔
859
        }
860
    }
861

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

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

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

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

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

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

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

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

1013
        $selectorWithoutUnmatchablePseudoComponents = $this->removeSelectorComponents(
449✔
1014
            ':(?!' . self::PSEUDO_CLASS_MATCHER . '):?+[\\w\\-]++(?:\\([^\\)]*+\\))?+',
449✔
1015
            $selectorWithoutNots
449✔
1016
        );
449✔
1017

1018
        if (preg_match(
449✔
1019
            '/:(?:' . self::OF_TYPE_PSEUDO_CLASS_MATCHER . ')/i',
449✔
1020
            $selectorWithoutUnmatchablePseudoComponents
449✔
1021
        ) === 0) {
449✔
1022
            return $selectorWithoutUnmatchablePseudoComponents;
382✔
1023
        }
1024

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

1033
        return \implode('', \array_map(
67✔
1034
            function (string $selectorPart): string {
67✔
1035
                return $this->removeUnsupportedOfTypePseudoClasses($selectorPart);
67✔
1036
            },
67✔
1037
            $selectorParts
67✔
1038
        ));
67✔
1039
    }
1040

1041
    /**
1042
     * Helps `removeUnmatchablePseudoComponents()` replace or remove a selector `:not(...)` component if its argument
1043
     * contains pseudo-elements or dynamic pseudo-classes.
1044
     *
1045
     * @param array<mixed> $matches
1046
     *        This is an array of elements matched by the regular expression.
1047
     *        A narrower type cannot be specified because it's a callback that may be passed different types in the
1048
     *        array, depending on the flags provided to `preg_replace_callback()` (which are not actually used),
1049
     *        and `Safe\preg_replace_callback()` does not have type annotations to cater for this.
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
        \assert(\is_string($notComponentWithAnyPrecedingCombinator));
60✔
1059
        \assert(\is_string($anyPrecedingCombinator));
60✔
1060
        \assert(\is_string($notArgumentInBrackets));
60✔
1061

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

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

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

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

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

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

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

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

1155
        $headElement = $this->getHeadElement();
470✔
1156
        $headElement->appendChild($styleElement);
470✔
1157
    }
1158

1159
    /**
1160
     * Returns the `HEAD` element.
1161
     *
1162
     * This method assumes that there always is a HEAD element.
1163
     */
1164
    private function getHeadElement(): \DOMElement
470✔
1165
    {
1166
        $node = $this->getDomDocument()->getElementsByTagName('head')->item(0);
470✔
1167
        \assert($node instanceof \DOMElement);
470✔
1168

1169
        return $node;
470✔
1170
    }
1171
}
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