Completed
Push — master ( d8a1ad...d0379b )
by Dominik
02:06
created

UrlEncodedDecoderType::cleanRawData()   C

Complexity

Conditions 7
Paths 11

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
dl 0
loc 25
ccs 0
cts 22
cp 0
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 16
nc 11
nop 1
crap 56
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
    public function getContentType(): string
13
    {
14
        return 'application/x-www-form-urlencoded';
15
    }
16
17
    /**
18
     * @param string $data
19
     *
20
     * @return array
21
     *
22
     * @throws DecoderException
23
     */
24
    public function decode(string $data): array
25
    {
26
        $rawData = [];
27
        parse_str($data, $rawData);
28
29
        if ('' !== $data && [] === $rawData) {
30
            throw DecoderException::createNotParsable($this->getContentType());
31
        }
32
33
        return $this->cleanRawData($rawData);
0 ignored issues
show
Bug introduced by
It seems like $rawData can also be of type null; however, Chubbyphp\Deserializatio...derType::cleanRawData() 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
    private function cleanRawData(array $rawData): array
42
    {
43
        $data = [];
44
        foreach ($rawData as $rawKey => $value) {
45
            $key = (string) (int) $rawKey === $rawData ? (int) $rawKey : $rawKey;
46
47
            if (is_array($value)) {
48
                $data[$key] = $this->cleanRawData($value);
49
            } else {
50
                if (is_numeric($value)) {
51
                    if ((string) (int) $value === $value) {
52
                        $value = (int) $value;
53
                    } else {
54
                        $value = (float) $value;
55
                    }
56
                } elseif ('' === $value) {
57
                    $value = null;
58
                }
59
60
                $data[$key] = $value;
61
            }
62
        }
63
64
        return $data;
65
    }
66
}
67