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

MyIntervals / emogrifier / 17135362778

21 Aug 2025 06:16PM UTC coverage: 96.868% (-0.02%) from 96.885%
17135362778

Pull #1457

github

web-flow
Merge 15f27a6fd into a787961b3
Pull Request #1457: [TASK] Use Safe-PHP functions for regexp in `CssInliner`

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

10 existing lines in 1 file now uncovered.

866 of 894 relevant lines covered (96.87%)

248.51 hits per line

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

96.45
/src/CssInliner.php
1
<?php
2

3
declare(strict_types=1);
4

5
namespace Pelago\Emogrifier;
6

7
use Pelago\Emogrifier\Css\CssDocument;
8
use Pelago\Emogrifier\HtmlProcessor\AbstractHtmlProcessor;
9
use Pelago\Emogrifier\Utilities\CssConcatenator;
10
use Pelago\Emogrifier\Utilities\DeclarationBlockParser;
11
use Symfony\Component\CssSelector\CssSelectorConverter;
12
use Symfony\Component\CssSelector\Exception\ParseException;
13

14
use function Safe\preg_replace;
15
use function Safe\preg_replace_callback;
16
use function Safe\preg_split;
17

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

230
        return $this;
3✔
231
    }
232

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

242
        return $this;
3✔
243
    }
244

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

256
        return $this;
2✔
257
    }
258

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

272
        return $this;
2✔
273
    }
274

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

288
        return $this;
9✔
289
    }
290

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

304
        return $this;
2✔
305
    }
306

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

318
        return $this;
6✔
319
    }
320

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

334
        return $this;
2✔
335
    }
336

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

570
        return $node;
466✔
571
    }
572

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

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

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

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

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

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

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

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

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

663
        return $cssRules;
1,165✔
664
    }
665

666
    /**
667
     * Tests if a selector contains a pseudo-class which would mean it cannot be converted to an XPath expression for
668
     * inlining CSS declarations.
669
     *
670
     * Any pseudo class that does not match {@see PSEUDO_CLASS_MATCHER} cannot be converted.  Additionally, `...of-type`
671
     * pseudo-classes cannot be converted if they are not associated with a type selector.
672
     */
673
    private function hasUnsupportedPseudoClass(string $selector): bool
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
        if (preg_match('/^[\\w\\-]/', $selectorPart) !== 0) {
120✔
703
            return false;
97✔
704
        }
705

706
        return preg_match('/:(?:' . self::OF_TYPE_PSEUDO_CLASS_MATCHER . ')/i', $selectorPart) !== 0;
67✔
707
    }
708

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

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

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

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

749
        return $precedence;
75✔
750
    }
751

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

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

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

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

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

823
        $combinedStyles = \array_merge($oldStyles, $newStyles);
482✔
824

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

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

840
        return $trimmedStyle;
482✔
841
    }
842

843
    /**
844
     * Checks whether `$attributeValue` is marked as `!important`.
845
     */
846
    private function attributeValueIsImportant(string $attributeValue): bool
482✔
847
    {
848
        return preg_match('/!\\s*+important$/i', $attributeValue) !== 0;
482✔
849
    }
850

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

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

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

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

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

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

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

995
        return $nodesMatchingSelector->length !== 0;
579✔
996
    }
997

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

1019
        $selectorWithoutUnmatchablePseudoComponents = $this->removeSelectorComponents(
449✔
1020
            ':(?!' . self::PSEUDO_CLASS_MATCHER . '):?+[\\w\\-]++(?:\\([^\\)]*+\\))?+',
449✔
1021
            $selectorWithoutNots
449✔
1022
        );
449✔
1023

1024
        if (
1025
            preg_match(
449✔
1026
                '/:(?:' . self::OF_TYPE_PSEUDO_CLASS_MATCHER . ')/i',
449✔
1027
                $selectorWithoutUnmatchablePseudoComponents
449✔
1028
            )
449✔
1029
            === 0
1030
        ) {
1031
            return $selectorWithoutUnmatchablePseudoComponents;
382✔
1032
        }
1033
        return \implode('', \array_map(
67✔
1034
            function (string $selectorPart): string {
67✔
1035
                return $this->removeUnsupportedOfTypePseudoClasses($selectorPart);
67✔
1036
            },
67✔
1037
            preg_split(
67✔
1038
                '/(' . self::COMBINATOR_MATCHER . ')/',
67✔
1039
                $selectorWithoutUnmatchablePseudoComponents,
67✔
1040
                -1,
67✔
1041
                PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
67✔
1042
            )
67✔
1043
        ));
67✔
1044
    }
1045

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

1060
        if ($this->hasUnsupportedPseudoClass($notArgumentInBrackets)) {
60✔
1061
            return $anyPrecedingCombinator !== '' ? $anyPrecedingCombinator . '*' : '';
54✔
1062
        }
1063
        return $notComponentWithAnyPrecedingCombinator;
8✔
1064
    }
1065

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

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

1099
        return $this->removeSelectorComponents(
67✔
1100
            ':(?:' . self::OF_TYPE_PSEUDO_CLASS_MATCHER . ')(?:\\([^\\)]*+\\))?+',
67✔
1101
            $selectorPart
67✔
1102
        );
67✔
1103
    }
1104

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

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

1132
        // avoid adding empty style element
1133
        if ($css !== '') {
1,165✔
1134
            $this->addStyleElementToDocument($css);
470✔
1135
        }
1136
    }
1137

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

1153
        $headElement = $this->getHeadElement();
470✔
1154
        $headElement->appendChild($styleElement);
470✔
1155
    }
1156

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

1171
        return $node;
470✔
1172
    }
1173
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc