Passed
Push — master ( 744fa2...6e775d )
by Petr
10:23
created

Json::parseInput()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 5
eloc 13
c 1
b 0
f 1
nc 5
nop 1
dl 0
loc 23
ccs 14
cts 14
cp 1
crap 5
rs 9.5222
1
<?php
2
3
namespace kalanis\kw_input\Parsers;
4
5
6
/**
7
 * Class Json
8
 * @package kalanis\kw_input\Parsers
9
 * Parse input from Json data
10
 * Also accepts multiple params and returns them as array
11
 * Cannot fail due incompatible data from source - because that incoming data in input really might not be a JSON
12
 */
13
class Json extends AParser
14
{
15
    const FLAG_FILE = 'FILE';
16
17
    /**
18
     * @param int[]|string[] $input is path to json content
19
     * @return array<string|int, string|int|bool>|array<string|int, array<int|string, string|int|bool>>
20
     */
21 7
    public function parseInput(array $input): array
22
    {
23 7
        $target = reset($input);
24 7
        if (false === $target) {
25 1
            return [];
26
        }
27
28 6
        $content = @file_get_contents(strval($target));
29 6
        if (false === $content) {
30 1
            return [];
31
        }
32
33 5
        $array = @json_decode($content, true);
34 5
        if (is_null($array)) {
35 1
            return [];
36
        }
37
38 4
        $clearArray = [];
39
40 4
        foreach ((array) $array as $key => $posted) {
41 3
            $clearArray[strval($this->removeNullBytes($key))] = $this->deepClear($posted, 1);
42
        }
43 4
        return $clearArray;
44
    }
45
46
    /**
47
     * @param mixed $toClear
48
     * @param int $level
49
     * @return array<string, string>|string
50
     */
51 3
    protected function deepClear($toClear, int $level)
52
    {
53 3
        if (!is_array($toClear)) {
54 3
            return $this->removeNullBytes(strval($toClear));
55
        }
56 2
        $result = [];
57 2
        foreach ($toClear as $key => $item) {
58 2
            if ((1 === $level) && (static::FLAG_FILE === $key)) {
59 1
                $result[static::FLAG_FILE] = $item;
60
            } else {
61 2
                $result[$this->removeNullBytes($key)] = $this->deepClear($item, $level + 1);
62
            }
63
        }
64 2
        return $result;
65
    }
66
}
67