Skip to content

Commit f38b49a

Browse files
committed
Optimize Handlebars::escapeExpression
Also micro-optimize a few runtime functions.
1 parent 45fe8ae commit f38b49a

2 files changed

Lines changed: 16 additions & 8 deletions

File tree

src/Handlebars.php

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,14 @@ public static function createFrame(array $data): array
6666
*/
6767
public static function escapeExpression(string $string): string
6868
{
69-
$search = ['&', '<', '>', '"', "'", '`', '='];
70-
$replace = ['&amp;', '&lt;', '&gt;', '&quot;', '&#x27;', '&#x60;', '&#x3D;'];
71-
return str_replace($search, $replace, $string);
69+
return strtr($string, [
70+
'&' => '&amp;',
71+
'<' => '&lt;',
72+
'>' => '&gt;',
73+
'"' => '&quot;',
74+
"'" => '&#x27;',
75+
'`' => '&#x60;',
76+
'=' => '&#x3D;',
77+
]);
7278
}
7379
}

src/Runtime.php

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -188,8 +188,9 @@ public static function createContext(mixed $context, array $options, array $comp
188188
}
189189

190190
$data = $options['data'] ?? [];
191+
$extraHelpers = $options['helpers'] ?? [];
191192
return new RuntimeContext(
192-
helpers: array_replace(Runtime::defaultHelpers(), $options['helpers'] ?? []),
193+
helpers: $extraHelpers ? array_replace(Runtime::defaultHelpers(), $extraHelpers) : Runtime::defaultHelpers(),
193194
partials: array_replace($compiledPartials, $options['partials'] ?? []),
194195
data: ['root' => $data['root'] ?? $context],
195196
frame: $data,
@@ -251,8 +252,8 @@ public static function ifvar(mixed $v, bool $zero = false): bool
251252
&& $v !== false
252253
&& ($zero || ($v !== 0 && $v !== 0.0))
253254
&& $v !== ''
254-
&& (!$v instanceof \Stringable || (string) $v !== '')
255-
&& (!is_array($v) || $v);
255+
&& (!is_array($v) || $v)
256+
&& (!$v instanceof \Stringable || (string) $v !== '');
256257
}
257258

258259
/**
@@ -305,8 +306,9 @@ public static function raw(mixed $value): string
305306
*/
306307
public static function sec(RuntimeContext $cx, mixed $value, mixed $in, ?\Closure $cb, ?\Closure $else = null, ?string $helperName = null): string
307308
{
308-
if ($helperName !== null && isset($cx->helpers[$helperName])) {
309-
return static::hbbch($cx, $cx->helpers[$helperName], $helperName, [], [], $in, $cb, $else);
309+
$helper = $helperName !== null ? ($cx->helpers[$helperName] ?? null) : null;
310+
if ($helper !== null) {
311+
return static::hbbch($cx, $helper, $helperName, [], [], $in, $cb, $else);
310312
}
311313

312314
// Lambda functions in block position: simple-path identifiers ($helperName set) receive

0 commit comments

Comments
 (0)