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

MyIntervals / emogrifier / 17758905971

16 Sep 2025 07:59AM UTC coverage: 96.472% (-0.4%) from 96.885%
17758905971

Pull #1457

github

web-flow
Merge 688a67320 into e59cdcc21
Pull Request #1457: [TASK] Use Safe-PHP functions for regexp in `CssInliner`

27 of 31 new or added lines in 1 file covered. (87.1%)

875 of 907 relevant lines covered (96.47%)

246.78 hits per line

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

95.51
/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_replace;
15
use function Safe\preg_replace_callback;
16
use function Safe\preg_split;
17

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

28
    /**
29
     * @var int<0, 1>
30
     */
31
    private const CACHE_KEY_COMBINED_STYLES = 1;
32

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

44
    /**
45
     * This regular expression component matches an `...of-type` pseudo class name, without the preceding ":".  These
46
     * pseudo-classes can currently online be inlined if they have an associated type in the selector expression.
47
     *
48
     * @var non-empty-string
49
     */
50
    private const OF_TYPE_PSEUDO_CLASS_MATCHER = '(?:first|last|nth(?:-last)?+|only)-of-type';
51

52
    /**
53
     * regular expression component to match a selector combinator
54
     *
55
     * @var non-empty-string
56
     */
57
    private const COMBINATOR_MATCHER = '(?:\\s++|\\s*+[>+~]\\s*+)(?=[[:alpha:]_\\-.#*:\\[])';
58

59
    /**
60
     * options array key for `querySelectorAll`
61
     *
62
     * @var non-empty-string
63
     */
64
    private const QSA_ALWAYS_THROW_PARSE_EXCEPTION = 'alwaysThrowParseException';
65

66
    /**
67
     * @var array<non-empty-string, true>
68
     */
69
    private $excludedSelectors = [];
70

71
    /**
72
     * @var array<non-empty-string, true>
73
     */
74
    private $excludedCssSelectors = [];
75

76
    /**
77
     * @var array<non-empty-string, true>
78
     */
79
    private $allowedMediaTypes = ['all' => true, 'screen' => true, 'print' => true];
80

81
    /**
82
     * @var array{
83
     *         0: array<non-empty-string, int<0, max>>,
84
     *         1: array<non-empty-string, string>
85
     *      }
86
     */
87
    private $caches = [
88
        self::CACHE_KEY_SELECTOR => [],
89
        self::CACHE_KEY_COMBINED_STYLES => [],
90
    ];
91

92
    /**
93
     * @var CssSelectorConverter|null
94
     */
95
    private $cssSelectorConverter = null;
96

97
    /**
98
     * the visited nodes with the XPath paths as array keys
99
     *
100
     * @var array<non-empty-string, \DOMElement>
101
     */
102
    private $visitedNodes = [];
103

104
    /**
105
     * the styles to apply to the nodes with the XPath paths as array keys for the outer array
106
     * and the attribute names/values as key/value pairs for the inner array
107
     *
108
     * @var array<non-empty-string, array<string, string>>
109
     */
110
    private $styleAttributesForNodes = [];
111

112
    /**
113
     * Determines whether the "style" attributes of tags in the the HTML passed to this class should be preserved.
114
     * If set to false, the value of the style attributes will be discarded.
115
     *
116
     * @var bool
117
     */
118
    private $isInlineStyleAttributesParsingEnabled = true;
119

120
    /**
121
     * Determines whether the `<style>` blocks in the HTML passed to this class should be parsed.
122
     *
123
     * If set to true, the `<style>` blocks will be removed from the HTML and their contents will be applied to the HTML
124
     * via inline styles.
125
     *
126
     * If set to false, the `<style>` blocks will be left as they are in the HTML.
127
     *
128
     * @var bool
129
     */
130
    private $isStyleBlocksParsingEnabled = true;
131

132
    /**
133
     * For calculating selector precedence order.
134
     * Keys are a regular expression part to match before a CSS name.
135
     * Values are a multiplier factor per match to weight specificity.
136
     *
137
     * @var array<string, int<1, max>>
138
     */
139
    private $selectorPrecedenceMatchers = [
140
        // IDs: worth 10000
141
        '\\#' => 10000,
142
        // classes, attributes, pseudo-classes (not pseudo-elements) except `:not`: worth 100
143
        '(?:\\.|\\[|(?<!:):(?!not\\())' => 100,
144
        // elements (not attribute values or `:not`), pseudo-elements: worth 1
145
        '(?:(?<![="\':\\w\\-])|::)' => 1,
146
    ];
147

148
    /**
149
     * array of data describing CSS rules which apply to the document but cannot be inlined, in the format returned by
150
     * {@see collateCssRules}
151
     *
152
     * @var array<array-key, array{
153
     *          media: string,
154
     *          selector: non-empty-string,
155
     *          hasUnmatchablePseudo: bool,
156
     *          declarationsBlock: string,
157
     *          line: int<0, max>
158
     *      }>|null
159
     */
160
    private $matchingUninlinableCssRules = null;
161

162
    /**
163
     * Emogrifier will throw Exceptions when it encounters an error instead of silently ignoring them.
164
     *
165
     * @var bool
166
     */
167
    private $debug = false;
168

169
    /**
170
     * Inlines the given CSS into the existing HTML.
171
     *
172
     * @param string $css the CSS to inline, must be UTF-8-encoded
173
     *
174
     * @return $this
175
     *
176
     * @throws ParseException in debug mode, if an invalid selector is encountered
177
     * @throws \RuntimeException
178
     *         in debug mode, if an internal PCRE error occurs
179
     *         or `CssSelectorConverter::toXPath` returns an invalid XPath expression
180
     * @throws \UnexpectedValueException
181
     *         if a selector query result includes a node which is not a `DOMElement`
182
     */
183
    public function inlineCss(string $css = ''): self
1,170✔
184
    {
185
        $this->clearAllCaches();
1,170✔
186
        $this->purgeVisitedNodes();
1,170✔
187

188
        $this->normalizeStyleAttributesOfAllNodes();
1,170✔
189

190
        $combinedCss = $css;
1,170✔
191
        // grab any existing style blocks from the HTML and append them to the existing CSS
192
        // (these blocks should be appended so as to have precedence over conflicting styles in the existing CSS)
193
        if ($this->isStyleBlocksParsingEnabled) {
1,170✔
194
            $combinedCss .= $this->getCssFromAllStyleNodes();
1,168✔
195
        }
196
        $parsedCss = new CssDocument($combinedCss, $this->debug);
1,170✔
197

198
        $excludedNodes = $this->getNodesToExclude();
1,166✔
199
        $cssRules = $this->collateCssRules($parsedCss);
1,165✔
200
        foreach ($cssRules['inlinable'] as $cssRule) {
1,165✔
201
            foreach ($this->querySelectorAll($cssRule['selector']) as $node) {
519✔
202
                if (\in_array($node, $excludedNodes, true)) {
466✔
203
                    continue;
4✔
204
                }
205
                $this->copyInlinableCssToStyleAttribute($this->ensureNodeIsElement($node), $cssRule);
464✔
206
            }
207
        }
208

209
        if ($this->isInlineStyleAttributesParsingEnabled) {
1,165✔
210
            $this->fillStyleAttributesWithMergedStyles();
1,163✔
211
        }
212

213
        $this->removeImportantAnnotationFromAllInlineStyles();
1,165✔
214

215
        $this->determineMatchingUninlinableCssRules($cssRules['uninlinable']);
1,165✔
216
        $this->copyUninlinableCssToStyleNode($parsedCss);
1,164✔
217

218
        return $this;
1,164✔
219
    }
220

221
    /**
222
     * Disables the parsing of inline styles.
223
     *
224
     * @return $this
225
     */
226
    public function disableInlineStyleAttributesParsing(): self
3✔
227
    {
228
        $this->isInlineStyleAttributesParsingEnabled = false;
3✔
229

230
        return $this;
3✔
231
    }
232

233
    /**
234
     * Disables the parsing of `<style>` blocks.
235
     *
236
     * @return $this
237
     */
238
    public function disableStyleBlocksParsing(): self
3✔
239
    {
240
        $this->isStyleBlocksParsingEnabled = false;
3✔
241

242
        return $this;
3✔
243
    }
244

245
    /**
246
     * Marks a media query type to keep.
247
     *
248
     * @param non-empty-string $mediaName the media type name, e.g., "braille"
249
     *
250
     * @return $this
251
     */
252
    public function addAllowedMediaType(string $mediaName): self
2✔
253
    {
254
        $this->allowedMediaTypes[$mediaName] = true;
2✔
255

256
        return $this;
2✔
257
    }
258

259
    /**
260
     * Drops a media query type from the allowed list.
261
     *
262
     * @param non-empty-string $mediaName the tag name, e.g., "braille"
263
     *
264
     * @return $this
265
     */
266
    public function removeAllowedMediaType(string $mediaName): self
2✔
267
    {
268
        if (isset($this->allowedMediaTypes[$mediaName])) {
2✔
269
            unset($this->allowedMediaTypes[$mediaName]);
2✔
270
        }
271

272
        return $this;
2✔
273
    }
274

275
    /**
276
     * Adds a selector to exclude nodes from emogrification.
277
     *
278
     * Any nodes that match the selector will not have their style altered.
279
     *
280
     * @param non-empty-string $selector the selector to exclude, e.g., ".editor"
281
     *
282
     * @return $this
283
     */
284
    public function addExcludedSelector(string $selector): self
9✔
285
    {
286
        $this->excludedSelectors[$selector] = true;
9✔
287

288
        return $this;
9✔
289
    }
290

291
    /**
292
     * No longer excludes the nodes matching this selector from emogrification.
293
     *
294
     * @param non-empty-string $selector the selector to no longer exclude, e.g., ".editor"
295
     *
296
     * @return $this
297
     */
298
    public function removeExcludedSelector(string $selector): self
2✔
299
    {
300
        if (isset($this->excludedSelectors[$selector])) {
2✔
301
            unset($this->excludedSelectors[$selector]);
1✔
302
        }
303

304
        return $this;
2✔
305
    }
306

307
    /**
308
     * Adds a selector to exclude CSS selector from emogrification.
309
     *
310
     * @param non-empty-string $selector the selector to exclude, e.g., `.editor`
311
     *
312
     * @return $this
313
     */
314
    public function addExcludedCssSelector(string $selector): self
6✔
315
    {
316
        $this->excludedCssSelectors[$selector] = true;
6✔
317

318
        return $this;
6✔
319
    }
320

321
    /**
322
     * No longer excludes the CSS selector from emogrification.
323
     *
324
     * @param non-empty-string $selector the selector to no longer exclude, e.g., `.editor`
325
     *
326
     * @return $this
327
     */
328
    public function removeExcludedCssSelector(string $selector): self
2✔
329
    {
330
        if (isset($this->excludedCssSelectors[$selector])) {
2✔
331
            unset($this->excludedCssSelectors[$selector]);
1✔
332
        }
333

334
        return $this;
2✔
335
    }
336

337
    /**
338
     * Sets the debug mode.
339
     *
340
     * @param bool $debug set to true to enable debug mode
341
     *
342
     * @return $this
343
     */
344
    public function setDebug(bool $debug): self
1,167✔
345
    {
346
        $this->debug = $debug;
1,167✔
347

348
        return $this;
1,167✔
349
    }
350

351
    /**
352
     * Gets the array of selectors present in the CSS provided to `inlineCss()` for which the declarations could not be
353
     * applied as inline styles, but which may affect elements in the HTML.  The relevant CSS will have been placed in a
354
     * `<style>` element.  The selectors may include those used within `@media` rules or those involving dynamic
355
     * pseudo-classes (such as `:hover`) or pseudo-elements (such as `::after`).
356
     *
357
     * @return array<array-key, string>
358
     *
359
     * @throws \BadMethodCallException if `inlineCss` has not been called first
360
     */
361
    public function getMatchingUninlinableSelectors(): array
6✔
362
    {
363
        return \array_column($this->getMatchingUninlinableCssRules(), 'selector');
6✔
364
    }
365

366
    /**
367
     * @return array<array-key, array{
368
     *             media: string,
369
     *             selector: non-empty-string,
370
     *             hasUnmatchablePseudo: bool,
371
     *             declarationsBlock: string,
372
     *             line: int<0, max>
373
     *         }>
374
     *
375
     * @throws \BadMethodCallException if `inlineCss` has not been called first
376
     */
377
    private function getMatchingUninlinableCssRules(): array
1,166✔
378
    {
379
        if (!\is_array($this->matchingUninlinableCssRules)) {
1,166✔
380
            throw new \BadMethodCallException('inlineCss must be called first', 1568385221);
1✔
381
        }
382

383
        return $this->matchingUninlinableCssRules;
1,165✔
384
    }
385

386
    /**
387
     * Clears all caches.
388
     */
389
    private function clearAllCaches(): void
1,170✔
390
    {
391
        $this->caches = [
1,170✔
392
            self::CACHE_KEY_SELECTOR => [],
1,170✔
393
            self::CACHE_KEY_COMBINED_STYLES => [],
1,170✔
394
        ];
1,170✔
395
    }
396

397
    /**
398
     * Purges the visited nodes.
399
     */
400
    private function purgeVisitedNodes(): void
1,170✔
401
    {
402
        $this->visitedNodes = [];
1,170✔
403
        $this->styleAttributesForNodes = [];
1,170✔
404
    }
405

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

426
    /**
427
     * Returns a list with all DOM nodes that have a style attribute.
428
     *
429
     * @return \DOMNodeList<\DOMElement>
430
     *
431
     * @throws \RuntimeException
432
     */
433
    private function getAllNodesWithStyleAttribute(): \DOMNodeList
1,170✔
434
    {
435
        $query = '//*[@style]';
1,170✔
436
        $matches = $this->getXPath()->query($query);
1,170✔
437
        if (!$matches instanceof \DOMNodeList) {
1,170✔
438
            throw new \RuntimeException('XPatch query failed: ' . $query, 1618577797);
×
439
        }
440
        /** @var \DOMNodeList<\DOMElement> $matches */
441

442
        return $matches;
1,170✔
443
    }
444

445
    /**
446
     * Normalizes the value of the "style" attribute and saves it.
447
     */
448
    private function normalizeStyleAttributes(\DOMElement $node): void
42✔
449
    {
450
        $declarationBlockParser = new DeclarationBlockParser();
42✔
451

452
        $pattern = '/-{0,2}+[_a-zA-Z][\\w\\-]*+(?=:)/S';
42✔
453
        /** @param array<array-key, string> $propertyNameMatches */
454
        $callback = static function (array $propertyNameMatches) use ($declarationBlockParser): string {
42✔
455
            return $declarationBlockParser->normalizePropertyName($propertyNameMatches[0]);
42✔
456
        };
42✔
457
        // The safe version is only available in "thecodingmachine/safe" for PHP >= 8.1.
458
        if (\function_exists('Safe\\preg_replace_callback')) {
42✔
459
            $normalizedOriginalStyle = preg_replace_callback($pattern, $callback, $node->getAttribute('style'));
42✔
460
            \assert(\is_string($normalizedOriginalStyle));
42✔
461
        } else {
NEW
462
            $normalizedOriginalStyle = \preg_replace_callback($pattern, $callback, $node->getAttribute('style'));
×
NEW
463
            \assert(\is_string($normalizedOriginalStyle));
×
464
        }
465

466
        // In order to not overwrite existing style attributes in the HTML, we have to save the original HTML styles.
467
        $nodePath = $node->getNodePath();
42✔
468
        if (\is_string($nodePath) && ($nodePath !== '') && !isset($this->styleAttributesForNodes[$nodePath])) {
42✔
469
            $this->styleAttributesForNodes[$nodePath] = $declarationBlockParser->parse($normalizedOriginalStyle);
42✔
470
            $this->visitedNodes[$nodePath] = $node;
42✔
471
        }
472

473
        $node->setAttribute('style', $normalizedOriginalStyle);
42✔
474
    }
475

476
    /**
477
     * Returns CSS content.
478
     */
479
    private function getCssFromAllStyleNodes(): string
1,168✔
480
    {
481
        $styleNodes = $this->getXPath()->query('//style');
1,168✔
482
        if ($styleNodes === false) {
1,168✔
483
            return '';
×
484
        }
485

486
        $css = '';
1,168✔
487
        foreach ($styleNodes as $styleNode) {
1,168✔
488
            if (\is_string($styleNode->nodeValue)) {
39✔
489
                $css .= "\n\n" . $styleNode->nodeValue;
39✔
490
            }
491
            $parentNode = $styleNode->parentNode;
39✔
492
            if ($parentNode instanceof \DOMNode) {
39✔
493
                $parentNode->removeChild($styleNode);
39✔
494
            }
495
        }
496

497
        return $css;
1,168✔
498
    }
499

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

518
        return $excludedNodes;
1,165✔
519
    }
520

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

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

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

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

575
        return $node;
466✔
576
    }
577

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

584
        return $this->cssSelectorConverter;
1,065✔
585
    }
586

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

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

622
            $mediaQuery = $cssRule->getContainingAtRule();
1,063✔
623
            $declarationsBlock = $cssRule->getDeclarationAsText();
1,063✔
624
            $selectors = $cssRule->getSelectors();
1,063✔
625

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

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

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

659
        \usort(
1,165✔
660
            $cssRules['inlinable'],
1,165✔
661
            /**
662
             * @param array{selector: non-empty-string, line: int<0, max>} $first
663
             * @param array{selector: non-empty-string, line: int<0, max>} $second
664
             */
665
            function (array $first, array $second): int {
1,165✔
666
                return $this->sortBySelectorPrecedence($first, $second);
75✔
667
            }
1,165✔
668
        );
1,165✔
669

670
        return $cssRules;
1,165✔
671
    }
672

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

686
        if (preg_match('/:(?:' . self::OF_TYPE_PSEUDO_CLASS_MATCHER . ')/i', $selector) === 0) {
788✔
687
            return false;
668✔
688
        }
689

690
        foreach (preg_split('/' . self::COMBINATOR_MATCHER . '/', $selector) as $selectorPart) {
120✔
691
            \assert(\is_string($selectorPart));
120✔
692
            if ($this->selectorPartHasUnsupportedOfTypePseudoClass($selectorPart)) {
120✔
693
                return true;
67✔
694
            }
695
        }
696

697
        return false;
53✔
698
    }
699

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

714
        return preg_match('/:(?:' . self::OF_TYPE_PSEUDO_CLASS_MATCHER . ')/i', $selectorPart) !== 0;
67✔
715
    }
716

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

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

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

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

758
        return $precedence;
75✔
759
    }
760

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

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

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

815
        // Unset the overridden styles to preserve order, important if shorthand and individual properties are mixed
816
        foreach ($oldStyles as $attributeName => $attributeValue) {
482✔
817
            if (!isset($newStyles[$attributeName])) {
87✔
818
                continue;
64✔
819
            }
820

821
            $newAttributeValue = $newStyles[$attributeName];
74✔
822
            if (
823
                $this->attributeValueIsImportant($attributeValue)
74✔
824
                && !$this->attributeValueIsImportant($newAttributeValue)
74✔
825
            ) {
826
                unset($newStyles[$attributeName]);
11✔
827
            } else {
828
                unset($oldStyles[$attributeName]);
63✔
829
            }
830
        }
831

832
        $combinedStyles = \array_merge($oldStyles, $newStyles);
482✔
833

834
        $declarationBlockParser = new DeclarationBlockParser();
482✔
835
        $style = '';
482✔
836
        foreach ($combinedStyles as $attributeName => $attributeValue) {
482✔
837
            $trimmedAttributeName = \trim($attributeName);
482✔
838
            if ($trimmedAttributeName === '') {
482✔
839
                throw new \UnexpectedValueException('An empty property name was encountered.', 1727046078);
×
840
            }
841
            $propertyName = $declarationBlockParser->normalizePropertyName($trimmedAttributeName);
482✔
842
            $propertyValue = \trim($attributeValue);
482✔
843
            $style .= $propertyName . ': ' . $propertyValue . '; ';
482✔
844
        }
845
        $trimmedStyle = \rtrim($style);
482✔
846

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

849
        return $trimmedStyle;
482✔
850
    }
851

852
    /**
853
     * Checks whether `$attributeValue` is marked as `!important`.
854
     */
855
    private function attributeValueIsImportant(string $attributeValue): bool
482✔
856
    {
857
        return preg_match('/!\\s*+important$/i', $attributeValue) !== 0;
482✔
858
    }
859

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

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

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

926
    /**
927
     * Generates a CSS style string suitable to be used inline from the $styleDeclarations property => value array.
928
     *
929
     * @param array<string, string> $styleDeclarations
930
     */
931
    private function generateStyleStringFromSingleDeclarationsArray(array $styleDeclarations): string
482✔
932
    {
933
        return $this->generateStyleStringFromDeclarationsArrays([], $styleDeclarations);
482✔
934
    }
935

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

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

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

1005
        return $nodesMatchingSelector->length !== 0;
579✔
1006
    }
1007

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

1035
        $selectorWithoutUnmatchablePseudoComponents = $this->removeSelectorComponents(
449✔
1036
            ':(?!' . self::PSEUDO_CLASS_MATCHER . '):?+[\\w\\-]++(?:\\([^\\)]*+\\))?+',
449✔
1037
            $selectorWithoutNots
449✔
1038
        );
449✔
1039

1040
        if (preg_match(
449✔
1041
            '/:(?:' . self::OF_TYPE_PSEUDO_CLASS_MATCHER . ')/i',
449✔
1042
            $selectorWithoutUnmatchablePseudoComponents
449✔
1043
        ) === 0) {
449✔
1044
            return $selectorWithoutUnmatchablePseudoComponents;
382✔
1045
        }
1046

1047
        $selectorParts = preg_split(
67✔
1048
            '/(' . self::COMBINATOR_MATCHER . ')/',
67✔
1049
            $selectorWithoutUnmatchablePseudoComponents,
67✔
1050
            -1,
67✔
1051
            PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
67✔
1052
        );
67✔
1053
        /** @var list<string> $selectorParts */
1054

1055
        return \implode('', \array_map(
67✔
1056
            function (string $selectorPart): string {
67✔
1057
                return $this->removeUnsupportedOfTypePseudoClasses($selectorPart);
67✔
1058
            },
67✔
1059
            $selectorParts
67✔
1060
        ));
67✔
1061
    }
1062

1063
    /**
1064
     * Helps `removeUnmatchablePseudoComponents()` replace or remove a selector `:not(...)` component if its argument
1065
     * contains pseudo-elements or dynamic pseudo-classes.
1066
     *
1067
     * @param array<array-key, string> $matches array of elements matched by the regular expression
1068
     *
1069
     * @return string
1070
     *         the full match if there were no unmatchable pseudo components within; otherwise, any preceding combinator
1071
     *         followed by "*", or an empty string if there was no preceding combinator
1072
     */
1073
    private function replaceUnmatchableNotComponent(array $matches): string
60✔
1074
    {
1075
        [$notComponentWithAnyPrecedingCombinator, $anyPrecedingCombinator, $notArgumentInBrackets] = $matches;
60✔
1076

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

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

1101
        return $result;
449✔
1102
    }
1103

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

1119
        return $this->removeSelectorComponents(
67✔
1120
            ':(?:' . self::OF_TYPE_PSEUDO_CLASS_MATCHER . ')(?:\\([^\\)]*+\\))?+',
67✔
1121
            $selectorPart
67✔
1122
        );
67✔
1123
    }
1124

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

1143
        // avoid including unneeded class dependency if there are no rules
1144
        if ($this->getMatchingUninlinableCssRules() !== []) {
1,165✔
1145
            $cssConcatenator = new CssConcatenator();
435✔
1146
            foreach ($this->getMatchingUninlinableCssRules() as $cssRule) {
435✔
1147
                $cssConcatenator->append([$cssRule['selector']], $cssRule['declarationsBlock'], $cssRule['media']);
435✔
1148
            }
1149
            $css .= $cssConcatenator->getCss();
435✔
1150
        }
1151

1152
        // avoid adding empty style element
1153
        if ($css !== '') {
1,165✔
1154
            $this->addStyleElementToDocument($css);
470✔
1155
        }
1156
    }
1157

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

1173
        $headElement = $this->getHeadElement();
470✔
1174
        $headElement->appendChild($styleElement);
470✔
1175
    }
1176

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

1191
        return $node;
470✔
1192
    }
1193
}
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