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