Skip to content

Commit 1680bba

Browse files
committed
minor #4663 Escaper performance: avoid static variables (gharlan)
This PR was squashed before being merged into the 3.x branch. Discussion ---------- Escaper performance: avoid static variables Replace two static variables with `match` expressions. And bypass a third static variable for the common charset `UTF-8`. Commits ------- 823f502 Escaper performance: avoid static variables
2 parents 115114b + 823f502 commit 1680bba

File tree

1 file changed

+12
-12
lines changed

1 file changed

+12
-12
lines changed

src/Runtime/EscaperRuntime.php

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,10 @@ public function escape($string, string $strategy = 'html', ?string $charset = nu
140140
case 'html':
141141
// see https://www.php.net/htmlspecialchars
142142

143+
if ('UTF-8' === $charset) {
144+
return htmlspecialchars($string, \ENT_QUOTES | \ENT_SUBSTITUTE, 'UTF-8');
145+
}
146+
143147
// Using a static variable to avoid initializing the array
144148
// each time the function is called. Moving the declaration on the
145149
// top of the function slow downs other escaping strategies.
@@ -195,18 +199,19 @@ public function escape($string, string $strategy = 'html', ?string $charset = nu
195199
* Escape sequences supported only by JavaScript, not JSON, are omitted.
196200
* \" is also supported but omitted, because the resulting string is not HTML safe.
197201
*/
198-
static $shortMap = [
202+
$short = match ($char) {
199203
'\\' => '\\\\',
200204
'/' => '\\/',
201205
"\x08" => '\b',
202206
"\x0C" => '\f',
203207
"\x0A" => '\n',
204208
"\x0D" => '\r',
205209
"\x09" => '\t',
206-
];
210+
default => false,
211+
};
207212

208-
if (isset($shortMap[$char])) {
209-
return $shortMap[$char];
213+
if ($short) {
214+
return $short;
210215
}
211216

212217
$codepoint = mb_ord($char, 'UTF-8');
@@ -288,18 +293,13 @@ public function escape($string, string $strategy = 'html', ?string $charset = nu
288293
* entities that XML supports. Using HTML entities would result in this error:
289294
* XML Parsing Error: undefined entity
290295
*/
291-
static $entityMap = [
296+
return match ($ord) {
292297
34 => '"', /* quotation mark */
293298
38 => '&', /* ampersand */
294299
60 => '<', /* less-than sign */
295300
62 => '>', /* greater-than sign */
296-
];
297-
298-
if (isset($entityMap[$ord])) {
299-
return $entityMap[$ord];
300-
}
301-
302-
return \sprintf('&#x%02X;', $ord);
301+
default => \sprintf('&#x%02X;', $ord),
302+
};
303303
}
304304

305305
/*

0 commit comments

Comments
 (0)