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