-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathURLFormEncoder.php
More file actions
50 lines (44 loc) · 2.09 KB
/
URLFormEncoder.php
File metadata and controls
50 lines (44 loc) · 2.09 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
<?php
namespace Chargebee\ValueObjects\Encoders;
use Chargebee\Utils\Util;
use Exception;
class URLFormEncoder implements ParamEncoderInterface
{
/**
* @param array $params.
* @param array $jsonKeys.
* @return string raw request body
*/
public static function encode(array $params, array $jsonKeys = [])
{
return http_build_query(self::serialize($params, null, null, $jsonKeys));
}
private static function serialize($value, $prefix = null, $idx = null, $jsonKeys = null, $level = 0): array
{
if ($value && !is_array($value)) {
throw new Exception("only arrays are allowed as value");
}
$serialized = [];
foreach ($value as $k => $v) {
$camelCaseKey = Util::toCamelCaseFromUnderscore($k);
$shouldJsonEncode = isset($jsonKeys[$camelCaseKey]) && $jsonKeys[$camelCaseKey] === $level;
if ($shouldJsonEncode) {
$usK = Util::toUnderscoreFromCamelCase($k);
$key = (!is_null($prefix) ? $prefix : '') .
(!is_null($prefix) ? '[' . $usK . ']' : $usK) .
(!is_null($idx) ? '[' . $idx . ']' : '');
$serialized[$key] = is_string($v) ? $v : json_encode((is_array($v) && $v === []) ? (object)[] : $v);
} else if (is_array($v) && !is_int($k)) {
$tempPrefix = (!is_null($prefix)) ? $prefix . '[' . Util::toUnderscoreFromCamelCase($k) . ']' : Util::toUnderscoreFromCamelCase($k);
$serialized = array_merge($serialized, self::serialize($v, $tempPrefix, null, $jsonKeys, $level + 1));
} elseif (is_array($v) && is_int($k)) {
$serialized = array_merge($serialized, self::serialize($v, $prefix, $k, $jsonKeys, $level));
} else {
$usK = Util::toUnderscoreFromCamelCase($k);
$key = (!is_null($prefix) ? $prefix : '') . (!is_null($prefix) ? '[' . $usK . ']' : $usK) . (!is_null($idx) ? '[' . $idx . ']' : '');
$serialized[$key] = Util::asString($v);
}
}
return $serialized;
}
}