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

MyIntervals / emogrifier / 17135002785

21 Aug 2025 06:01PM UTC coverage: 96.885% (-0.09%) from 96.976%
17135002785

push

github

web-flow
[TASK] Streamline `CssInliner` (#1456)

Closes #1425

9 of 11 new or added lines in 2 files covered. (81.82%)

1 existing line in 1 file now uncovered.

871 of 899 relevant lines covered (96.89%)

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

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

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

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

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

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

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

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

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

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

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

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

567
        return $node;
466✔
568
    }
569

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

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

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

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

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

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

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

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

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

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

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

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

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

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

689
        return false;
53✔
690
    }
691

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

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

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

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

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

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

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

752
        return $precedence;
75✔
753
    }
754

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

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

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

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

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

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

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

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

843
        return $trimmedStyle;
482✔
844
    }
845

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

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

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

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

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

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

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

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

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

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

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

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

1029
        if (
1030
            $preg->match(
449✔
1031
                '/:(?:' . self::OF_TYPE_PSEUDO_CLASS_MATCHER . ')/i',
449✔
1032
                $selectorWithoutUnmatchablePseudoComponents
449✔
1033
            )
449✔
1034
            === 0
1035
        ) {
1036
            return $selectorWithoutUnmatchablePseudoComponents;
382✔
1037
        }
1038
        return \implode('', \array_map(
67✔
1039
            function (string $selectorPart): string {
67✔
1040
                return $this->removeUnsupportedOfTypePseudoClasses($selectorPart);
67✔
1041
            },
67✔
1042
            $preg->split(
67✔
1043
                '/(' . self::COMBINATOR_MATCHER . ')/',
67✔
1044
                $selectorWithoutUnmatchablePseudoComponents,
67✔
1045
                -1,
67✔
1046
                PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
67✔
1047
            )
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✔
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