Test Setup Failed
Push — master ( 69e326...85dbbc )
by Dominik
02:09
created

UrlEncodedTypeEncoder::buildQuery()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 10
cts 10
cp 1
rs 8.7624
c 0
b 0
f 0
cc 5
eloc 13
nc 6
nop 2
crap 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chubbyphp\Serialization\Encoder;
6
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 1
    public function encode(array $data): string
23
    {
24 1
        return $this->buildQuery($data);
25
    }
26
27
    /**
28
     * @param array  $data
29
     * @param string $path
30
     *
31
     * @return string
32
     */
33 1
    private function buildQuery(array $data, string $path = ''): string
34
    {
35 1
        if ([] === $data) {
36 1
            return '';
37 1
        }
38 1
39 1
        $query = '';
40
        foreach ($data as $key => $value) {
41 1
            $subPath = '' !== $path ? $path.'['.$key.']' : $key;
42
            if (is_array($value)) {
43 1
                $query .= $this->buildQuery($value, $subPath);
44
            } else {
45 1
                $query .= $subPath.'='.urlencode($this->convertValueToString($value));
46
            }
47 1
            $query .= '&';
48
        }
49
50
        $query = substr($query, 0, -strlen('&'));
51
52
        return $query;
53
    }
54
55 1
    /**
56
     * @param null|bool|int|string $value
57 1
     *
58 1
     * @return string
59
     */
60
    private function convertValueToString($value): string
61 1
    {
62 1
        if (true === $value) {
63
            return 'true';
64
        }
65 1
66
        if (false === $value) {
67
            return 'false';
68
        }
69
70
        return (string) $value;
71
    }
72
}
73