UrlEncodedTypeDecoder   A
last analyzed

Complexity

Total Complexity 14

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 25
c 0
b 0
f 0
dl 0
loc 62
ccs 20
cts 20
cp 1
rs 10
wmc 14

4 Methods

Rating   Name   Duplication   Size   Complexity  
B fixValue() 0 23 7
A decode() 0 10 3
A getContentType() 0 3 1
A fixValues() 0 12 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chubbyphp\Deserialization\Decoder;
6
7
use Chubbyphp\Deserialization\DeserializerRuntimeException;
8
9
final class UrlEncodedTypeDecoder implements TypeDecoderInterface
10
{
11
    public function getContentType(): string
12
    {
13
        return 'application/x-www-form-urlencoded';
14 2
    }
15
16 2
    /**
17
     * @throws DeserializerRuntimeException
18
     */
19
    public function decode(string $data): array
20
    {
21
        $rawData = [];
22
        parse_str($data, $rawData);
23
24
        if ('' !== $data && [] === $rawData) {
25
            throw DeserializerRuntimeException::createNotParsable($this->getContentType());
26 3
        }
27
28 3
        return $this->fixValues($rawData);
29 3
    }
30
31 3
    private function fixValues(array $rawData): array
32 1
    {
33
        $data = [];
34
        foreach ($rawData as $key => $value) {
35 2
            if (is_array($value)) {
36
                $data[$key] = $this->fixValues($value);
37
            } else {
38
                $data[$key] = $this->fixValue($value);
39
            }
40
        }
41
42
        return $data;
43 2
    }
44
45 2
    /**
46 2
     * @return mixed
47 2
     */
48 2
    private function fixValue(string $value)
49
    {
50 2
        if ('' === $value) {
51
            return null;
52
        }
53
54 2
        if ('true' === $value) {
55
            return true;
56
        }
57
58
        if ('false' === $value) {
59
            return false;
60
        }
61
62 2
        if (is_numeric($value) && '0' !== $value[0]) {
63
            if ((string) (int) $value === $value) {
64 2
                return (int) $value;
65 1
            }
66
67
            return (float) $value;
68 2
        }
69 1
70
        return $value;
71
    }
72
}
73