Completed
Push — master ( 0fb7a8...5895c8 )
by Dominik
04:44
created

UrlEncodedTypeEncoder::covertData()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 1
crap 3
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
36 1
        $query = '';
37 1
        foreach ($data as $key => $value) {
38 1
            $subPath = '' !== $path ? $path.'['.$key.']' : $key;
39 1
            if (is_array($value)) {
40 1
                $query .= $this->buildQuery($value, $subPath);
41
            } else {
42 1
                $query .= $subPath.'='.urlencode($this->covertData($value));
43
            }
44 1
            $query .= '&';
45
        }
46 1
        $query = substr($query, 0, -strlen('&'));
47
48 1
        return $query;
49
    }
50
51
    /**
52
     * @param null|bool|int|string $value
53
     * @return string
54
     */
55 1
    private function covertData($value): string
56
    {
57 1
        if (true === $value) {
58 1
            return 'true';
59
        }
60
61 1
        if (false === $value) {
62 1
            return 'false';
63
        }
64
65 1
        return (string) $value;
66
    }
67
}
68