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

MyIntervals / emogrifier / 17710110037

14 Sep 2025 10:46AM UTC coverage: 96.906% (+0.02%) from 96.885%
17710110037

Pull #1457

github

web-flow
Merge 3baef0b02 into 3cc28b7e0
Pull Request #1457: [TASK] Use Safe-PHP functions for regexp in `CssInliner`

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

11 existing lines in 1 file now uncovered.

877 of 905 relevant lines covered (96.91%)

247.86 hits per line

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

96.55
/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
        $normalizedOriginalStyle = preg_replace_callback(
42✔
453
            '/-{0,2}+[_a-zA-Z][\\w\\-]*+(?=:)/S',
42✔
454
            /** @param array<array-key, string> $propertyNameMatches */
455
            static function (array $propertyNameMatches) use ($declarationBlockParser): string {
42✔
456
                return $declarationBlockParser->normalizePropertyName($propertyNameMatches[0]);
42✔
457
            },
42✔
458
            $node->getAttribute('style')
42✔
459
        );
42✔
460
        \assert(\is_string($normalizedOriginalStyle));
42✔
461

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

469
        $node->setAttribute('style', $normalizedOriginalStyle);
42✔
470
    }
471

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

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

493
        return $css;
1,168✔
494
    }
495

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

514
        return $excludedNodes;
1,165✔
515
    }
516

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

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

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

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

571
        return $node;
466✔
572
    }
573

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

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

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

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

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

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

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

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

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

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

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

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

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

693
        return false;
53✔
694
    }
695

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

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

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

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

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

741
        $precedence = 0;
75✔
742
        foreach ($this->selectorPrecedenceMatchers as $matcher => $value) {
75✔
743
            if (\trim($selector) === '') {
75✔
744
                break;
8✔
745
            }
746
            $count = 0;
75✔
747
            $selector = preg_replace('/' . $matcher . '\\w+/', '', $selector, -1, $count);
75✔
748
            \assert(\is_string($selector));
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✔
UNCOV
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
                \assert(\is_string($declaration));
38✔
910
                $importantStyleDeclarations[$property] = $declaration;
38✔
911
            } else {
912
                $regularStyleDeclarations[$property] = $value;
458✔
913
            }
914
        }
915
        $inlineStyleDeclarationsInNewOrder = \array_merge($regularStyleDeclarations, $importantStyleDeclarations);
482✔
916
        $node->setAttribute(
482✔
917
            'style',
482✔
918
            $this->generateStyleStringFromSingleDeclarationsArray($inlineStyleDeclarationsInNewOrder)
482✔
919
        );
482✔
920
    }
921

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

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

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

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

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

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

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

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

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

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

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

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

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

1093
        return $result;
449✔
1094
    }
1095

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

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

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

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

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

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

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

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

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

© 2025 Coveralls, Inc