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

MyIntervals / emogrifier / 17708928123

14 Sep 2025 08:52AM UTC coverage: 96.885%. Remained the same
17708928123

Pull #1469

github

web-flow
Merge c7c0040a5 into 3cc28b7e0
Pull Request #1469: [CLEANUP] Refactor preg usage in `CssInliner`

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

1 existing line in 1 file now uncovered.

871 of 899 relevant lines covered (96.89%)

250.29 hits per line

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

96.5
/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 Pelago\Emogrifier\Utilities\Preg;
12
use Symfony\Component\CssSelector\CssSelectorConverter;
13
use Symfony\Component\CssSelector\Exception\ParseException;
14

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

25
    /**
26
     * @var int<0, 1>
27
     */
28
    private const CACHE_KEY_COMBINED_STYLES = 1;
29

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

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

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

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

63
    /**
64
     * @var array<non-empty-string, true>
65
     */
66
    private $excludedSelectors = [];
67

68
    /**
69
     * @var array<non-empty-string, true>
70
     */
71
    private $excludedCssSelectors = [];
72

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

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

89
    /**
90
     * @var CssSelectorConverter|null
91
     */
92
    private $cssSelectorConverter = null;
93

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

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

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

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

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

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

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

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

185
        $this->normalizeStyleAttributesOfAllNodes();
1,170✔
186

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

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

206
        if ($this->isInlineStyleAttributesParsingEnabled) {
1,165✔
207
            $this->fillStyleAttributesWithMergedStyles();
1,163✔
208
        }
209

210
        $this->removeImportantAnnotationFromAllInlineStyles();
1,165✔
211

212
        $this->determineMatchingUninlinableCssRules($cssRules['uninlinable']);
1,165✔
213
        $this->copyUninlinableCssToStyleNode($parsedCss);
1,164✔
214

215
        return $this;
1,164✔
216
    }
217

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

227
        return $this;
3✔
228
    }
229

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

239
        return $this;
3✔
240
    }
241

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

253
        return $this;
2✔
254
    }
255

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

269
        return $this;
2✔
270
    }
271

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

285
        return $this;
9✔
286
    }
287

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

301
        return $this;
2✔
302
    }
303

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

315
        return $this;
6✔
316
    }
317

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

331
        return $this;
2✔
332
    }
333

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

345
        return $this;
1,167✔
346
    }
347

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

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

380
        return $this->matchingUninlinableCssRules;
1,165✔
381
    }
382

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

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

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

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

439
        return $matches;
1,170✔
440
    }
441

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

449
        $pattern = '/-{0,2}+[_a-zA-Z][\\w\\-]*+(?=:)/S';
42✔
450
        /** @param array<array-key, string> $propertyNameMatches */
451
        $callback = static function (array $propertyNameMatches) use ($declarationBlockParser): string {
42✔
452
            return $declarationBlockParser->normalizePropertyName($propertyNameMatches[0]);
42✔
453
        };
42✔
454
        $normalizedOriginalStyle = (new Preg())->throwExceptions($this->debug)
42✔
455
            ->replaceCallback($pattern, $callback, $node->getAttribute('style'));
42✔
456

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

464
        $node->setAttribute('style', $normalizedOriginalStyle);
42✔
465
    }
466

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

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

488
        return $css;
1,168✔
489
    }
490

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

509
        return $excludedNodes;
1,165✔
510
    }
511

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

528
            if ($result === false) {
1,061✔
529
                throw new \RuntimeException('query failed with selector \'' . $selectors . '\'', 1726533051);
×
530
            }
531
            /** @var \DOMNodeList<\DOMElement> $result */
532

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

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

566
        return $node;
466✔
567
    }
568

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

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

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

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

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

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

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

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

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

660
        return $cssRules;
1,165✔
661
    }
662

663
    /**
664
     * Tests if a selector contains a pseudo-class which would mean it cannot be converted to an XPath expression for
665
     * inlining CSS declarations.
666
     *
667
     * Any pseudo class that does not match {@see PSEUDO_CLASS_MATCHER} cannot be converted.  Additionally, `...of-type`
668
     * pseudo-classes cannot be converted if they are not associated with a type selector.
669
     */
670
    private function hasUnsupportedPseudoClass(string $selector): bool
1,006✔
671
    {
672
        $preg = (new Preg())->throwExceptions($this->debug);
1,006✔
673

674
        if ($preg->match('/:(?!' . self::PSEUDO_CLASS_MATCHER . ')[\\w\\-]/i', $selector) !== 0) {
1,006✔
675
            return true;
323✔
676
        }
677

678
        if ($preg->match('/:(?:' . self::OF_TYPE_PSEUDO_CLASS_MATCHER . ')/i', $selector) === 0) {
788✔
679
            return false;
668✔
680
        }
681

682
        foreach ($preg->split('/' . self::COMBINATOR_MATCHER . '/', $selector) as $selectorPart) {
120✔
683
            if ($this->selectorPartHasUnsupportedOfTypePseudoClass($selectorPart)) {
120✔
684
                return true;
67✔
685
            }
686
        }
687

688
        return false;
53✔
689
    }
690

691
    /**
692
     * Tests if part of a selector contains an `...of-type` pseudo-class such that it cannot be converted to an XPath
693
     * expression.
694
     *
695
     * @param string $selectorPart part of a selector which has been split up at combinators
696
     *
697
     * @return bool `true` if the selector part does not have a type but does have an `...of-type` pseudo-class
698
     */
699
    private function selectorPartHasUnsupportedOfTypePseudoClass(string $selectorPart): bool
120✔
700
    {
701
        $preg = (new Preg())->throwExceptions($this->debug);
120✔
702

703
        if ($preg->match('/^[\\w\\-]/', $selectorPart) !== 0) {
120✔
704
            return false;
97✔
705
        }
706

707
        return $preg->match('/:(?:' . self::OF_TYPE_PSEUDO_CLASS_MATCHER . ')/i', $selectorPart) !== 0;
67✔
708
    }
709

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

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

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

738
        $preg = (new Preg())->throwExceptions($this->debug);
75✔
739
        $precedence = 0;
75✔
740
        foreach ($this->selectorPrecedenceMatchers as $matcher => $value) {
75✔
741
            if (\trim($selector) === '') {
75✔
742
                break;
8✔
743
            }
744
            $count = 0;
75✔
745
            $selector = $preg->replace('/' . $matcher . '\\w+/', '', $selector, -1, $count);
75✔
746
            $precedence += ($value * $count);
75✔
747
            \assert($precedence >= 0);
75✔
748
        }
749
        $this->caches[self::CACHE_KEY_SELECTOR][$selectorKey] = $precedence;
75✔
750

751
        return $precedence;
75✔
752
    }
753

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

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

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

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

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

825
        $combinedStyles = \array_merge($oldStyles, $newStyles);
482✔
826

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

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

842
        return $trimmedStyle;
482✔
843
    }
844

845
    /**
846
     * Checks whether `$attributeValue` is marked as `!important`.
847
     */
848
    private function attributeValueIsImportant(string $attributeValue): bool
482✔
849
    {
850
        return (new Preg())->throwExceptions($this->debug)->match('/!\\s*+important$/i', $attributeValue) !== 0;
482✔
851
    }
852

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

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

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

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

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

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

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

997
        return $nodesMatchingSelector->length !== 0;
579✔
998
    }
999

1000
    /**
1001
     * Removes pseudo-elements and dynamic pseudo-classes from a CSS selector, replacing them with "*" if necessary.
1002
     * If such a pseudo-component is within the argument of `:not`, the entire `:not` component is removed or replaced.
1003
     *
1004
     * @return string
1005
     *         selector which will match the relevant DOM elements if the pseudo-classes are assumed to apply, or in the
1006
     *         case of pseudo-elements will match their originating element
1007
     */
1008
    private function removeUnmatchablePseudoComponents(string $selector): string
449✔
1009
    {
1010
        $preg = (new Preg())->throwExceptions($this->debug);
449✔
1011

1012
        // The regex allows nested brackets via `(?2)`.
1013
        // A space is temporarily prepended because the callback can't determine if the match was at the very start.
1014
        $pattern = '/([\\s>+~]?+):not(\\([^()]*+(?:(?2)[^()]*+)*+\\))/i';
449✔
1015
        /** @param array<array-key, string> $matches */
1016
        $callback = function (array $matches): string {
449✔
1017
            return $this->replaceUnmatchableNotComponent($matches);
60✔
1018
        };
449✔
1019
        $selectorWithoutNots = (new Preg())->throwExceptions($this->debug)
449✔
1020
            ->replaceCallback($pattern, $callback, ' ' . $selector);
449✔
1021
        $trimmedSelectorWithoutNots = \ltrim($selectorWithoutNots);
449✔
1022

1023
        $selectorWithoutUnmatchablePseudoComponents = $this->removeSelectorComponents(
449✔
1024
            ':(?!' . self::PSEUDO_CLASS_MATCHER . '):?+[\\w\\-]++(?:\\([^\\)]*+\\))?+',
449✔
1025
            $trimmedSelectorWithoutNots
449✔
1026
        );
449✔
1027

1028
        if ($preg->match(
449✔
1029
            '/:(?:' . self::OF_TYPE_PSEUDO_CLASS_MATCHER . ')/i',
449✔
1030
            $selectorWithoutUnmatchablePseudoComponents
449✔
1031
        ) === 0) {
449✔
1032
            return $selectorWithoutUnmatchablePseudoComponents;
382✔
1033
        }
1034

1035
        $selectorParts = $preg->split(
67✔
1036
            '/(' . self::COMBINATOR_MATCHER . ')/',
67✔
1037
            $selectorWithoutUnmatchablePseudoComponents,
67✔
1038
            -1,
67✔
1039
            PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
67✔
1040
        );
67✔
1041
        /** @var list<string> $selectorParts */
1042

1043
        return \implode('', \array_map(
67✔
1044
            function (string $selectorPart): string {
67✔
1045
                return $this->removeUnsupportedOfTypePseudoClasses($selectorPart);
67✔
1046
            },
67✔
1047
            $selectorParts
67✔
1048
        ));
67✔
1049
    }
1050

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

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

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

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

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

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

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

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

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

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

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

1176
        return $node;
470✔
1177
    }
1178
}
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