Completed
Push — master ( 516597...0aeec3 )
by Dominik
04:41
created

UrlEncodedTypeEncoder   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 81
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 1 Features 0
Metric Value
eloc 28
dl 0
loc 81
ccs 30
cts 30
cp 1
rs 10
c 3
b 1
f 0
wmc 15

4 Methods

Rating   Name   Duplication   Size   Complexity  
B getValueAsString() 0 24 7
A encode() 0 3 1
A buildQuery() 0 22 6
A getContentType() 0 3 1
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 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
65
    {
66 2
        if (is_string($value)) {
67 1
            return $value;
68
        }
69
70 2
        if (is_bool($value)) {
71 1
            return $value ? 'true' : 'false';
72
        }
73
74 2
        if (is_float($value)) {
75 1
            $value = (string) $value;
76 1
            if (false === strpos($value, '.')) {
77 1
                $value .= '.0';
78
            }
79
80 1
            return $value;
81
        }
82
83 2
        if (is_int($value)) {
0 ignored issues
show
introduced by
The condition is_int($value) is always true.
Loading history...
84 1
            return (string) $value;
85
        }
86
87 1
        throw new \InvalidArgumentException(sprintf('Unsupported data type: %s', gettype($value)));
88
    }
89
}
90