UrlEncodedTypeEncoder::getValueAsString()   B
last analyzed

Complexity

Conditions 7
Paths 7

Size

Total Lines 24
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 7

Importance

Changes 0
Metric Value
cc 7
eloc 12
nc 7
nop 1
dl 0
loc 24
ccs 8
cts 8
cp 1
crap 7
rs 8.8333
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chubbyphp\Serialization\Encoder;
6
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
49 2
    {
50
        if (is_string($value)) {
51 1
            return $value;
52
        }
53
54 1
        if (is_bool($value)) {
55
            return $value ? 'true' : 'false';
56
        }
57
58
        if (is_float($value)) {
59
            $value = (string) $value;
60
            if (false === strpos($value, '.')) {
61
                $value .= '.0';
62
            }
63
64 2
            return $value;
65
        }
66 2
67 1
        if (is_int($value)) {
0 ignored issues
show
introduced by
The condition is_int($value) is always true.
Loading history...
68
            return (string) $value;
69
        }
70 2
71 1
        throw new \InvalidArgumentException(sprintf('Unsupported data type: %s', gettype($value)));
72
    }
73
}
74