Skip to content

Commit 2f0390b

Browse files
committed
Improve escape callback parameter
Changed: - Moved escape function resolution outside of iteration of attributes to evaluate once. - Improved support for custom escape functions by passing attribute value and name.
1 parent 2c5adff commit 2f0390b

File tree

1 file changed

+14
-9
lines changed

1 file changed

+14
-9
lines changed

Function.HTML-Build-Attributes.php

+14-9
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
* representing attribute names and values.
1010
* @param callable|null $escape
1111
* Callback function to escape the values for HTML attributes.
12+
* Accepts two parameters: 1. attribute value, 2. attribute name.
1213
* Defaults to `esc_attr()`, if available, otherwise `htmlspecialchars()`.
1314
* @return string Returns a string of HTML attributes
1415
* or a empty string if $attributes is invalid or empty.
@@ -23,6 +24,18 @@ function html_build_attributes($attributes, callable $escape = null)
2324
return '';
2425
}
2526

27+
if (is_null($escape)) {
28+
if (function_exists('esc_attr')) {
29+
$escape = function ($value) {
30+
return esc_attr($value);
31+
};
32+
} else {
33+
$escape = function ($value) {
34+
return htmlspecialchars($value, ENT_QUOTES, null, false);
35+
};
36+
}
37+
}
38+
2639
$html = [];
2740
foreach ($attributes as $attribute_name => $attribute_value) {
2841
if (is_string($attribute_name)) {
@@ -76,18 +89,10 @@ function html_build_attributes($attributes, callable $escape = null)
7689
$attribute_value = json_encode($attribute_value, (JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
7790
}
7891

79-
if (is_callable($escape)) {
80-
$attribute_value = $escape($attribute_value);
81-
} elseif (function_exists('esc_attr')) {
82-
$attribute_value = esc_attr($attribute_value);
83-
} else {
84-
$attribute_value = htmlspecialchars($attribute_value, ENT_QUOTES);
85-
}
86-
8792
$html[] = sprintf(
8893
'%1$s="%2$s"',
8994
$attribute_name,
90-
$attribute_value
95+
$escape($attribute_value, $attribute_name)
9196
);
9297
}
9398

0 commit comments

Comments
 (0)