Passed
Push — main ( fcd645...b00902 )
by Alexandra
02:38
created

ReceivedMap::create()   B

Complexity

Conditions 7
Paths 10

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 7

Importance

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