Total Complexity | 15 |
Total Lines | 65 |
Duplicated Lines | 0 % |
Coverage | 100% |
Changes | 3 | ||
Bugs | 1 | Features | 0 |
1 | <?php |
||
7 | final class UrlEncodedTypeEncoder implements TypeEncoderInterface |
||
8 | { |
||
9 | public function getContentType(): string |
||
10 | { |
||
11 | return 'application/x-www-form-urlencoded'; |
||
12 | 1 | } |
|
13 | |||
14 | 1 | public function encode(array $data): string |
|
15 | { |
||
16 | return $this->buildQuery($data); |
||
17 | } |
||
18 | |||
19 | private function buildQuery(array $data, string $path = ''): string |
||
20 | { |
||
21 | if ([] === $data) { |
||
22 | 2 | return ''; |
|
23 | } |
||
24 | 2 | ||
25 | $query = ''; |
||
26 | foreach ($data as $key => $value) { |
||
27 | if (null === $value) { |
||
28 | continue; |
||
29 | } |
||
30 | |||
31 | $subPath = '' !== $path ? $path.'['.$key.']' : (string) $key; |
||
32 | if (is_array($value)) { |
||
33 | 2 | $query .= $this->buildQuery($value, $subPath); |
|
34 | } else { |
||
35 | 2 | $query .= $subPath.'='.urlencode($this->getValueAsString($value)); |
|
36 | 1 | } |
|
37 | $query .= '&'; |
||
38 | } |
||
39 | 2 | ||
40 | 2 | return substr($query, 0, -strlen('&')); |
|
41 | 2 | } |
|
42 | 1 | ||
43 | /** |
||
44 | * @param bool|int|float|string $value |
||
45 | 2 | * |
|
46 | 2 | * @throws \InvalidArgumentException |
|
47 | 1 | */ |
|
48 | private function getValueAsString($value): string |
||
72 | } |
||
73 | } |
||
74 |