ReceivedMap::create()   B
last analyzed

Complexity

Conditions 7
Paths 10

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 7

Importance

Changes 2
Bugs 1 Features 1
Metric Value
cc 7
eloc 12
c 2
b 1
f 1
nc 10
nop 3
dl 0
loc 23
ccs 12
cts 12
cp 1
crap 7
rs 8.8333
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AHJ\ApprovalTests;
6
7
final class ReceivedMap
8
{
9 14
    public function create(array $input, $output, bool $plain = false): string
10
    {
11 14
        $receivedMap = [];
12
13 14
        if (!empty($input)) {
14 12
            foreach ($input as $inputKey => $inputValue) {
15 12
                $receivedMap[$inputKey] = '[' . $this->serializeMixedType($inputValue) . '] -> ';
16
            }
17
        }
18
19 14
        if ($plain) {
20 2
            return 'string' === gettype($output) ? $output : json_encode($output);
21
        }
22
23 12
        foreach ($output as $outputKey => $outputValue) {
24 12
            if (!empty($input)) {
25 11
                $receivedMap[$outputKey] = $receivedMap[$outputKey] . '[' . $this->serializeMixedType($outputValue) . ']';
26
            } else {
27 1
                $receivedMap[$outputKey] = '[' . $this->serializeMixedType($outputValue) . ']';
28
            }
29
        }
30
31 12
        return $this->cleanAndFlatten($receivedMap);
32
    }
33
34 13
    private function serializeMixedType($inputValue, string $currentConcatenations = ''): string
35
    {
36 13
        $concatenations = '';
37
38 13
        if ('string' === gettype($inputValue)) {
39
            return $currentConcatenations . $inputValue;
40
        }
41
42 13
        foreach ($inputValue as $item) {
43 13
            if ('array' === gettype($item) || 'object' === gettype($item)) {
44 7
                $concatenations .= '[' . $this->serializeMixedType($item, $concatenations) . ']';
45
            } else {
46 13
                $concatenations .= $item . ', ';
47
            }
48
        }
49
50 13
        return $concatenations;
51
    }
52
53
    /**
54
     * @param array $received Example:
55
     *                        [
56
     *                        [0] => '[foo, 0, [bar, 10, ]] -> [foo, 10, [bar, 60, ]]',
57
     *                        [1] => '[foo, 10, [bar, 100, ]] -> [foo, 100, [bar, 600, ]]'
58
     *                        ]
59
     *
60
     * @return string Example:
61
     *                '[foo, 0, [bar, 10]] -> [foo, 10, [bar, 60]]\n
62
     *                [foo, 10, [bar, 100]] -> [foo, 100, [bar, 600]]'
63
     */
64 12
    private function cleanAndFlatten(array $received): string
65
    {
66 12
        return str_replace(', ]', ']', implode("\n", $received));
67
    }
68
}
69