-
Notifications
You must be signed in to change notification settings - Fork 158
Expand file tree
/
Copy pathCssVariableEvaluator.php
More file actions
209 lines (186 loc) · 7.74 KB
/
CssVariableEvaluator.php
File metadata and controls
209 lines (186 loc) · 7.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
<?php
declare(strict_types=1);
namespace Pelago\Emogrifier\HtmlProcessor;
use Pelago\Emogrifier\Utilities\DeclarationBlockParser;
use function Safe\preg_match;
use function Safe\preg_replace_callback;
/**
* This class can evaluate CSS custom properties that are defined and used in inline style attributes.
*/
final class CssVariableEvaluator extends AbstractHtmlProcessor
{
/**
* temporary collection used by {@see replaceVariablesInDeclarations} and callee methods
*
* @var array<non-empty-string, string>
*/
private $currentVariableDefinitions = [];
/**
* Replaces all CSS custom property references in inline style attributes with their corresponding values where
* defined in inline style attributes (either from the element itself or the nearest ancestor).
*
* @return $this
*
* @throws \UnexpectedValueException
*/
public function evaluateVariables(): self
{
/**
* @var list<array{element: \DOMElement, ancestorDefinitions: array<non-empty-string, string>}>
* $elementsToEvaluate
*/
$elementsToEvaluate = [['element' => $this->getHtmlElement(), 'ancestorDefinitions' => []]];
while (($currentElementData = \array_pop($elementsToEvaluate)) !== null) {
$currentElement = $currentElementData['element'];
$currentAncestorDefinitions = $currentElementData['ancestorDefinitions'];
$style = $currentElement->getAttribute('style');
// Avoid parsing declarations if none use or define a variable
if (preg_match('/(?<![\\w\\-])--[\\w\\-]/', $style) !== 0) {
$declarations = DeclarationBlockParser::parse($style);
$variableDefinitions =
$this->getVariableDefinitionsFromDeclarations($declarations) + $currentAncestorDefinitions;
$this->currentVariableDefinitions = $variableDefinitions;
$newDeclarations = $this->replaceVariablesInDeclarations($declarations);
if ($newDeclarations !== null) {
$currentElement->setAttribute('style', $this->getDeclarationsAsString($newDeclarations));
}
} else {
$variableDefinitions = $currentAncestorDefinitions;
}
foreach ($currentElement->childNodes as $child) {
if ($child instanceof \DOMElement) {
$elementsToEvaluate[] = ['element' => $child, 'ancestorDefinitions' => $variableDefinitions];
}
}
}
return $this;
}
/**
* @param array<non-empty-string, string> $declarations
*
* @return array<non-empty-string, string>
*/
private function getVariableDefinitionsFromDeclarations(array $declarations): array
{
return \array_filter(
$declarations,
static function (string $key): bool {
return \substr($key, 0, 2) === '--';
},
ARRAY_FILTER_USE_KEY
);
}
/**
* Callback function for {@see replaceVariablesInPropertyValue} performing regular expression replacement.
*
* @param array<int, string> $matches
*/
private function getPropertyValueReplacement(array $matches): string
{
$variableName = $matches[1];
if (isset($this->currentVariableDefinitions[$variableName])) {
$variableValue = $this->currentVariableDefinitions[$variableName];
} else {
$fallbackValueSeparator = $matches[2] ?? '';
if ($fallbackValueSeparator !== '') {
$fallbackValue = $matches[3];
// The fallback value may use other CSS variables, so recurse
$variableValue = $this->replaceVariablesInPropertyValue($fallbackValue);
} else {
$variableValue = $matches[0];
}
}
return $variableValue;
}
/**
* Regular expression based on {@see https://stackoverflow.com/a/54143883/2511031 a StackOverflow answer}.
*/
private function replaceVariablesInPropertyValue(string $propertyValue): string
{
$pattern = '/
var\\(
\\s*+
# capture variable name including `--` prefix
(
--[^\\s\\),]++
)
\\s*+
# capture optional fallback value
(?:
# capture separator to confirm there is a fallback value
(,)\\s*
# begin capture with named group that can be used recursively
(?<recursable>
# begin named group to match sequence without parentheses, except in strings
(?<noparentheses>
# repeated zero or more times:
(?:
# sequence without parentheses or quotes
[^\\(\\)\'"]++
|
# string in double quotes
"(?>[^"\\\\]++|\\\\.)*"
|
# string in single quotes
\'(?>[^\'\\\\]++|\\\\.)*\'
)*+
)
# repeated zero or more times:
(?:
# sequence in parentheses
\\(
# using the named recursable pattern
(?&recursable)
\\)
# sequence without parentheses, except in strings
(?&noparentheses)
)*+
)
)?+
\\)
/x';
$callable = \Closure::fromCallable([$this, 'getPropertyValueReplacement']);
if (\function_exists('Safe\\preg_replace_callback')) {
$result = preg_replace_callback($pattern, $callable, $propertyValue);
} else {
// @phpstan-ignore-next-line The safe version is only available in "thecodingmachine/safe" for PHP >= 8.1.
$result = \preg_replace_callback($pattern, $callable, $propertyValue);
}
\assert(\is_string($result));
return $result;
}
/**
* @param array<non-empty-string, string> $declarations
*
* @return array<non-empty-string, string>|null `null` is returned if no substitutions were made.
*/
private function replaceVariablesInDeclarations(array $declarations): ?array
{
$substitutionsMade = false;
$result = \array_map(
function (string $propertyValue) use (&$substitutionsMade): string {
$newPropertyValue = $this->replaceVariablesInPropertyValue($propertyValue);
if ($newPropertyValue !== $propertyValue) {
$substitutionsMade = true;
}
return $newPropertyValue;
},
$declarations
);
return $substitutionsMade ? $result : null;
}
/**
* @param array<non-empty-string, string> $declarations
*/
private function getDeclarationsAsString(array $declarations): string
{
$declarationStrings = \array_map(
static function (string $key, string $value): string {
return $key . ': ' . $value;
},
\array_keys($declarations),
\array_values($declarations)
);
return \implode('; ', $declarationStrings) . ';';
}
}