-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp-query-builder.php
More file actions
187 lines (168 loc) · 6.39 KB
/
http-query-builder.php
File metadata and controls
187 lines (168 loc) · 6.39 KB
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
<?php
declare(strict_types=1);
/**
* Build an HTTP query string from an (optionally nested) array with security guards.
*
* Security / robustness upgrades:
* - RFC 3986 encoding by default (rawurlencode, spaces => %20) to avoid ambiguity.
* - Key sorting for deterministic output (can disable).
* - Depth and pair-count guards to prevent runaway recursion and memory abuse.
* - Strict typing + input validation; rejects resources/unsupported objects.
* - Safe delimiter whitelist (& or ;) with graceful fallback.
* - Consistent scalar normalization (bools, nulls, floats, DateTimeInterface).
*
* Back-compat: keeps the original signature. New $options param is optional.
*
* @param array $query_data Input data.
* @param string $parent_key (Internal) Parent key for recursion.
* @param string $delimiter Delimiter between pairs. Only "&" and ";" allowed.
* @param bool $preserveNumericIndexes Preserve numeric indexes (e.g., preferences[0]=x) instead of [].
* @param array $options Optional behavior tweaks:
* - 'encode' => 'rfc3986'|'rfc1738' (default 'rfc3986')
* - 'bool_format' => 'int'|'word'|'string' (default 'int') // int: 1/0, word: true/false, string: "true"/"false"
* - 'null_format' => 'omit'|'empty'|'string' (default 'omit') // omit: skip pairs, empty: key=, string: "null"
* - 'datetime_format' => string DateTime format (default DATE_ATOM)
* - 'max_depth' => int (default 50)
* - 'max_pairs' => int (default 10000)
* - 'sort_keys' => bool (default true)
*
* @return array ['error' => bool, 'message' => string|null, 'query' => string|null]
*
* @example
* $result = build_http_query_from_array($data);
* if ($result['error']) { echo $result['message']; } else { echo $result['query']; }
*
* @author WERA AS
* @version 2.0.0
*/
function build_http_query_from_array(
array $query_data,
string $parent_key = '',
string $delimiter = '&',
bool $preserveNumericIndexes = false,
array $options = []
): array {
$opts = array_merge([
'encode' => 'rfc3986',
'bool_format' => 'int',
'null_format' => 'omit',
'datetime_format' => DATE_ATOM,
'max_depth' => 50,
'max_pairs' => 10000,
'sort_keys' => true,
], $options);
if (!in_array($delimiter, ['&', ';'], true)) {
$delimiter = '&';
}
if (!in_array($opts['encode'], ['rfc3986', 'rfc1738'], true)) {
$opts['encode'] = 'rfc3986';
}
if (!in_array($opts['bool_format'], ['int', 'word', 'string'], true)) {
$opts['bool_format'] = 'int';
}
if (!in_array($opts['null_format'], ['omit', 'empty', 'string'], true)) {
$opts['null_format'] = 'omit';
}
$maxDepth = max(1, (int)$opts['max_depth']);
$maxPairs = max(1, (int)$opts['max_pairs']);
$sortKeys = (bool)$opts['sort_keys'];
$encodeKey = function (string $s) use ($opts): string {
return $opts['encode'] === 'rfc1738' ? urlencode($s) : rawurlencode($s);
};
$encodeVal = $encodeKey;
$normalizeScalar = function ($v) use ($opts): ?string {
if (is_bool($v)) {
return match ($opts['bool_format']) {
'word' => $v ? 'true' : 'false',
'string' => $v ? 'true' : 'false',
default => $v ? '1' : '0',
};
}
if ($v === null) {
return match ($opts['null_format']) {
'empty' => '',
'string' => 'null',
'omit' => null,
};
}
if ($v instanceof \DateTimeInterface) {
return $v->format($opts['datetime_format']);
}
if (is_int($v)) {
return (string)$v;
}
if (is_float($v)) {
$s = number_format($v, 14, '.', '');
$s = rtrim(rtrim($s, '0'), '.');
return $s === '' ? '0' : $s;
}
if (is_string($v)) {
return $v;
}
if (is_resource($v) || is_object($v)) {
return null;
}
return (string)$v;
};
$pairs = [];
$pairCount = 0;
$build = function ($data, string $parent, int $depth) use (
&$build,
&$pairs,
&$pairCount,
$maxDepth,
$maxPairs,
$sortKeys,
$preserveNumericIndexes,
$encodeKey,
$encodeVal,
$normalizeScalar
): ?array {
if ($depth > $maxDepth) {
return ['error' => true, 'message' => "Max depth of {$maxDepth} exceeded."];
}
if (!is_array($data)) {
return ['error' => true, 'message' => 'Invalid input. Expected an array at current level.'];
}
if ($sortKeys) {
uksort($data, static function ($a, $b) {
return strcmp((string)$a, (string)$b);
});
}
foreach ($data as $key => $value) {
$keyStr = (string)$key;
$encodedKey = $parent === ''
? $encodeKey($keyStr)
: (
is_int($key) && !$preserveNumericIndexes
? $parent . '[]'
: $parent . '[' . $encodeKey($keyStr) . ']'
);
if (is_array($value)) {
$res = $build($value, $encodedKey, $depth + 1);
if ($res !== null && $res['error'] ?? false) {
return $res;
}
} else {
$normalized = $normalizeScalar($value);
if ($normalized === null) {
if (is_resource($value) || is_object($value)) {
return ['error' => true, 'message' => "Invalid type in query data at key '{$keyStr}'."];
}
continue;
}
$pairCount++;
if ($pairCount > $maxPairs) {
return ['error' => true, 'message' => "Max pair count of {$maxPairs} exceeded."];
}
$pairs[] = $encodedKey . '=' . $encodeVal($normalized);
}
}
return null;
};
$err = $build($query_data, $parent_key, 1);
if (is_array($err) && ($err['error'] ?? false)) {
return ['error' => true, 'message' => $err['message'] ?? 'Unknown error', 'query' => null];
}
return ['error' => false, 'message' => null, 'query' => implode($delimiter, $pairs)];
}