Passed
Push — feature/artisan-command ( f953e8...49b1ef )
by Andrea Marco
02:19
created

ExportsValues   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 17
dl 0
loc 59
ccs 19
cts 19
cp 1
rs 10
c 0
b 0
f 0
wmc 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A export() 0 7 2
A exportArray() 0 13 3
A exportScalar() 0 11 5
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