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

MyIntervals / emogrifier / 19615242042

23 Nov 2025 06:09PM UTC coverage: 96.213% (-0.003%) from 96.216%
19615242042

Pull #1517

github

web-flow
Merge b775ca529 into 37e1dbe49
Pull Request #1517: [TASK] Add PHPStan rules for Safe-PHP

7 of 10 new or added lines in 3 files covered. (70.0%)

1 existing line in 1 file now uncovered.

813 of 845 relevant lines covered (96.21%)

262.46 hits per line

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

95.42
/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
use function Safe\preg_match;
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
        if (\function_exists('Safe\\preg_replace_callback')) {
42✔
458
            $normalizedOriginalStyle = preg_replace_callback($pattern, $callback, $node->getAttribute('style'));
42✔
459
        } else {
460
            // @phpstan-ignore-next-line The safe version is only available in "thecodingmachine/safe" for PHP >= 8.1.
NEW
461
            $normalizedOriginalStyle = \preg_replace_callback($pattern, $callback, $node->getAttribute('style'));
×
462
            \assert(\is_string($normalizedOriginalStyle));
×
463
        }
464

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

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

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

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

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

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

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

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

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

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

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

574
        return $node;
466✔
575
    }
576

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

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

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

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

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

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

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

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

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

667
        return $cssRules;
1,165✔
668
    }
669

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

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

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

694
        return false;
53✔
695
    }
696

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

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

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

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

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

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

754
        return $precedence;
75✔
755
    }
756

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

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

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

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

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

828
        $combinedStyles = \array_merge($oldStyles, $newStyles);
482✔
829

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

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

845
        return $trimmedStyle;
482✔
846
    }
847

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

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

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

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

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

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

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

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

1000
        return $nodesMatchingSelector->length !== 0;
579✔
1001
    }
1002

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

1029
        $selectorWithoutUnmatchablePseudoComponents = $this->removeSelectorComponents(
449✔
1030
            ':(?!' . self::PSEUDO_CLASS_MATCHER . '):?+[\\w\\-]++(?:\\([^\\)]*+\\))?+',
449✔
1031
            $selectorWithoutNots
449✔
1032
        );
449✔
1033

1034
        if (preg_match(
449✔
1035
                '/:(?:' . self::OF_TYPE_PSEUDO_CLASS_MATCHER . ')/i',
449✔
1036
                $selectorWithoutUnmatchablePseudoComponents
449✔
1037
            ) === 0) {
449✔
1038
            return $selectorWithoutUnmatchablePseudoComponents;
382✔
1039
        }
1040

1041
        $selectorParts = preg_split(
67✔
1042
            '/(' . self::COMBINATOR_MATCHER . ')/',
67✔
1043
            $selectorWithoutUnmatchablePseudoComponents,
67✔
1044
            -1,
67✔
1045
            PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
67✔
1046
        );
67✔
1047
        /** @var list<string> $selectorParts */
1048

1049
        return \implode('', \array_map(
67✔
1050
            function (string $selectorPart): string {
67✔
1051
                return $this->removeUnsupportedOfTypePseudoClasses($selectorPart);
67✔
1052
            },
67✔
1053
            $selectorParts
67✔
1054
        ));
67✔
1055
    }
1056

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

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

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

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

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

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

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

1143
        // avoid adding empty style element
1144
        if ($css !== '') {
1,165✔
1145
            $this->addStyleElementToDocument($css);
470✔
1146
        }
1147
    }
1148

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

1164
        $headElement = $this->getHeadElement();
470✔
1165
        $headElement->appendChild($styleElement);
470✔
1166
    }
1167

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

1182
        return $node;
470✔
1183
    }
1184
}
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