ExportsValues::exportArray()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 3
nop 3
dl 0
loc 13
ccs 9
cts 9
cp 1
crap 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Cerbero\LaravelEnum;
4
5
/**
6
 * The exports values trait.
7
 *
8
 */
9
trait ExportsValues
10
{
11
    /**
12
     * Export the given value.
13
     *
14
     * @param mixed $value
15
     * @param int $initialPadding
16
     * @param int $incrementalPadding
17
     * @return string
18
     */
19 12
    protected function export($value, int $initialPadding = 0, int $incrementalPadding = 4) : string
20
    {
21 12
        if (is_array($value)) {
22 3
            return $this->exportArray($value, $initialPadding, $incrementalPadding);
23
        }
24
25 12
        return $this->exportScalar($value);
26
    }
27
28
    /**
29
     * Format the given scalar value to an exportable string.
30
     *
31
     * @param mixed $value
32
     * @return string
33
     */
34 12
    protected function exportScalar($value) : string
35
    {
36 12
        if (is_null($value)) {
37 3
            return 'null';
38
        }
39
40 12
        if (is_bool($value)) {
41 3
            return $value ? 'true' : 'false';
42
        }
43
44 12
        return is_string($value) ? "'{$value}'" : "{$value}";
45
    }
46
47
    /**
48
     * Format the given array to an exportable string
49
     *
50
     * @param array $array
51
     * @param int $initialPadding
52
     * @param int $incrementalPadding
53
     * @return string
54
     */
55 3
    protected function exportArray(array $array, int $initialPadding = 0, int $incrementalPadding = 4) : string
56
    {
57 3
        $padding = $initialPadding + $incrementalPadding;
58 3
        $indentation = str_repeat(' ', $padding);
59 3
        $exported = [];
60
61 3
        foreach ($array as $key => $value) {
62 3
            $exportedKey = is_int($key) ? '' : "'{$key}' => ";
63 3
            $exportedValue = $this->export($value, $padding, $incrementalPadding);
64 3
            $exported[] = $indentation . $exportedKey . $exportedValue;
65
        }
66
67 3
        return "[\n" . implode(",\n", $exported) . ",\n" . str_repeat(' ', $initialPadding) . ']';
68
    }
69
}
70