Passed
Push — master ( 63f127...dbf653 )
by Dominik
01:54
created

UrlEncodedDecoderType::getContentType()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chubbyphp\Deserialization\Decoder;
6
7
final class UrlEncodedDecoderType implements DecoderTypeInterface
8
{
9
    /**
10
     * @return string
11
     */
12 2
    public function getContentType(): string
13
    {
14 2
        return 'application/x-www-form-urlencoded';
15
    }
16
17
    /**
18
     * @param string $data
19
     *
20
     * @return array
21
     *
22
     * @throws DecoderException
23
     */
24 2
    public function decode(string $data): array
25
    {
26 2
        $rawData = [];
27 2
        parse_str($data, $rawData);
28
29 2
        if ('' !== $data && [] === $rawData) {
30 1
            throw DecoderException::createNotParsable($this->getContentType());
31
        }
32
33 1
        return $this->fixValues($rawData);
0 ignored issues
show
Bug introduced by
It seems like $rawData can also be of type null; however, Chubbyphp\Deserializatio...ecoderType::fixValues() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
34
    }
35
36
    /**
37
     * @param array $rawData
38
     *
39
     * @return array
40
     */
41 1
    private function fixValues(array $rawData): array
42
    {
43 1
        $data = [];
44 1
        foreach ($rawData as $rawKey => $value) {
45 1
            $key = (string) (int) $rawKey === $rawData ? (int) $rawKey : $rawKey;
46
47 1
            if (is_array($value)) {
48 1
                $data[$key] = $this->fixValues($value);
49
            } else {
50 1
                $data[$key] = $this->fixValue($value);
51
            }
52
        }
53
54 1
        return $data;
55
    }
56
57
    /**
58
     * @param $value
59
     *
60
     * @return float|int|null|string
61
     */
62 1
    private function fixValue($value)
63
    {
64 1
        if (is_numeric($value)) {
65 1
            if ((string) (int) $value === $value) {
66 1
                return (int) $value;
67
            }
68
69 1
            return (float) $value;
70
        }
71
72 1
        if ('' === $value) {
73 1
            return null;
74
        }
75
76 1
        return $value;
77
    }
78
}
79