-
Notifications
You must be signed in to change notification settings - Fork 0
/
Function.HTML-Build-Attributes.php
101 lines (87 loc) · 3.46 KB
/
Function.HTML-Build-Attributes.php
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
<?php
if (!function_exists('html_build_attributes')) {
/**
* Generate a string of HTML attributes.
*
* @param array|object $attributes
* Associative array or object containing properties,
* representing attribute names and values.
* @param callable|null $escape
* Callback function to escape the values for HTML attributes.
* Accepts two parameters: 1. attribute value, 2. attribute name.
* Defaults to `esc_attr()`, if available, otherwise `htmlspecialchars()`.
* @return string Returns a string of HTML attributes
* or a empty string if $attributes is invalid or empty.
*/
function html_build_attributes($attributes, callable $escape = null)
{
if (is_object($attributes) && !($attributes instanceof \Traversable)) {
$attributes = get_object_vars($attributes);
}
if (!is_array($attributes) || !count($attributes)) {
return '';
}
if (is_null($escape)) {
if (function_exists('esc_attr')) {
$escape = function ($value) {
return esc_attr($value);
};
} else {
$escape = function ($value) {
return htmlspecialchars($value, ENT_QUOTES, null, false);
};
}
}
$html = [];
foreach ($attributes as $attribute_name => $attribute_value) {
if (is_string($attribute_name)) {
$attribute_name = trim($attribute_name);
if (strlen($attribute_name) === 0) {
continue;
}
}
if (is_object($attribute_value) && is_callable($attribute_value)) {
$attribute_value = $attribute_value();
}
if (is_null($attribute_value)) {
continue;
}
if (is_object($attribute_value)) {
if (is_callable([ $attribute_value, 'toArray' ])) {
$attribute_value = $attribute_value->toArray();
} elseif (is_callable([ $attribute_value, '__toString' ])) {
$attribute_value = strval($attribute_value);
}
}
if (is_bool($attribute_value)) {
if ($attribute_value) {
$html[] = $attribute_name;
}
continue;
} elseif (is_array($attribute_value)) {
$attribute_value = implode(' ', array_reduce($attribute_value, function ($tokens, $token) {
if (is_string($token)) {
$token = trim($token);
if (strlen($token) > 0) {
$tokens[] = $token;
}
} elseif (is_numeric($token)) {
$tokens[] = $token;
}
return $tokens;
}, []));
if (strlen($attribute_value) === 0) {
continue;
}
} elseif (!is_string($attribute_value) && !is_numeric($attribute_value)) {
$attribute_value = json_encode($attribute_value, (JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
}
$html[] = sprintf(
'%1$s="%2$s"',
$attribute_name,
$escape($attribute_value, $attribute_name)
);
}
return implode(' ', $html);
}
}