Passed
Pull Request — master (#172)
by David
02:33
created

Psr2Utils::psr2InlineVarExport()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 8
c 1
b 0
f 0
dl 0
loc 12
rs 10
cc 4
nc 4
nop 1
1
<?php
2
3
4
namespace TheCodingMachine\TDBM\Utils;
5
6
use function array_keys;
7
use function count;
8
use function implode;
9
use function is_array;
10
use function range;
11
use function var_export;
12
13
class Psr2Utils
14
{
15
    /**
16
     * @param mixed $var
17
     * @param string $indent
18
     * @return string
19
     */
20
    public static function psr2VarExport($var, string $indent=''): string
21
    {
22
        if (is_array($var)) {
23
            $indexed = array_keys($var) === range(0, count($var) - 1);
24
            $r = [];
25
            foreach ($var as $key => $value) {
26
                $r[] = "$indent    "
27
                    . ($indexed ? '' : self::psr2VarExport($key) . ' => ')
28
                    . self::psr2VarExport($value, "$indent    ");
29
            }
30
            return "[\n" . implode(",\n", $r) . "\n" . $indent . ']';
31
        }
32
        return var_export($var, true);
33
    }
34
35
    /**
36
     * @param mixed $var
37
     * @return string
38
     */
39
    public static function psr2InlineVarExport($var): string
40
    {
41
        if (is_array($var)) {
42
            $indexed = array_keys($var) === range(0, count($var) - 1);
43
            $r = [];
44
            foreach ($var as $key => $value) {
45
                $r[] = ($indexed ? '' : self::psr2InlineVarExport($key) . ' => ')
46
                    . self::psr2InlineVarExport($value);
47
            }
48
            return '[' . implode(',', $r) . ']';
49
        }
50
        return var_export($var, true);
51
    }
52
}
53