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

MyIntervals / emogrifier / 24624496779

19 Apr 2026 08:08AM UTC coverage: 96.778% (+0.3%) from 96.445%
24624496779

Pull #1616

github

web-flow
Merge 730724dbf into 7d7ddf3d6
Pull Request #1616: [CLEANUP] Replace some exceptions with assertions

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

13 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
     * @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
        \assert($matches instanceof \DOMNodeList);
1,171✔
426
        /** @var \DOMNodeList<\DOMElement> $matches */
427

428
        return $matches;
1,171✔
429
    }
430

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

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

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

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

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

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

491
        return $css;
1,169✔
492
    }
493

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

512
        return $excludedNodes;
1,166✔
513
    }
514

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

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

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

566
        return $node;
466✔
567
    }
568

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

575
        return $this->cssSelectorConverter;
1,065✔
576
    }
577

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

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

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

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

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

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

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

659
        return $cssRules;
1,166✔
660
    }
661

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

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

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

686
        return false;
53✔
687
    }
688

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

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

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

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

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

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

746
        return $precedence;
75✔
747
    }
748

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

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

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

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

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

819
        $combinedStyles = \array_merge($oldStyles, $newStyles);
482✔
820

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

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

835
        return $trimmedStyle;
482✔
836
    }
837

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1043
    /**
1044
     * Helps `removeUnmatchablePseudoComponents()` replace or remove a selector `:not(...)` component if its argument
1045
     * contains pseudo-elements or dynamic pseudo-classes.
1046
     *
1047
     * @param array<mixed> $matches
1048
     *        This is an array of elements matched by the regular expression.
1049
     *        A narrower type cannot be specified because it's a callback that may be passed different types in the
1050
     *        array, depending on the flags provided to `preg_replace_callback()` (which are not actually used),
1051
     *        and `Safe\preg_replace_callback()` does not have type annotations to cater for this.
1052
     *
1053
     * @return string
1054
     *         the full match if there were no unmatchable pseudo components within; otherwise, any preceding combinator
1055
     *         followed by "*", or an empty string if there was no preceding combinator
1056
     */
1057
    private function replaceUnmatchableNotComponent(array $matches): string
60✔
1058
    {
1059
        [$notComponentWithAnyPrecedingCombinator, $anyPrecedingCombinator, $notArgumentInBrackets] = $matches;
60✔
1060
        \assert(\is_string($notComponentWithAnyPrecedingCombinator));
60✔
1061
        \assert(\is_string($anyPrecedingCombinator));
60✔
1062
        \assert(\is_string($notArgumentInBrackets));
60✔
1063

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

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

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

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

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

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

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

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

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

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

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

© 2026 Coveralls, Inc