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

Psr2Utils   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
eloc 17
c 1
b 0
f 0
dl 0
loc 38
rs 10

2 Methods

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