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

MyIntervals / emogrifier / 17151259206

22 Aug 2025 09:13AM UTC coverage: 96.889% (+0.004%) from 96.885%
17151259206

Pull #1457

github

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

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

11 existing lines in 1 file now uncovered.

872 of 900 relevant lines covered (96.89%)

248.04 hits per line

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

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

3
declare(strict_types=1);
4

5
namespace Pelago\Emogrifier;
6

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

230
        return $this;
3✔
231
    }
232

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

242
        return $this;
3✔
243
    }
244

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

256
        return $this;
2✔
257
    }
258

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

272
        return $this;
2✔
273
    }
274

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

288
        return $this;
9✔
289
    }
290

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

304
        return $this;
2✔
305
    }
306

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

318
        return $this;
6✔
319
    }
320

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

334
        return $this;
2✔
335
    }
336

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

571
        return $node;
466✔
572
    }
573

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

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

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

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

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

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

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

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

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

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

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

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

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

693
        return false;
53✔
694
    }
695

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

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

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

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

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

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

753
        return $precedence;
75✔
754
    }
755

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

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

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

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

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

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

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

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

844
        return $trimmedStyle;
482✔
845
    }
846

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1088
        return $result;
449✔
1089
    }
1090

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

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

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

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

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

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

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

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

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