Failed Conditions
Pull Request — master (#138)
by Adrien
01:51
created

Dumper::dump()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 6
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Genkgo\TestCamt\Unit;
6
7
use DateTimeZone;
8
use ReflectionClass;
9
use ReflectionMethod;
10
11
class Dumper
12
{
13
    private array $saw = [];
14
15
    public function dump(object|array|string|float|int|bool|null $variable): string
16
    {
17
        $this->saw = [];
18
        $a = $this->cast($variable);
19
20
        return json_encode($a, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . PHP_EOL;
21
    }
22
23
    private function cast(object|array|string|float|int|bool|null $variable): array|string|float|int|bool|null
24
    {
25
        if ((is_iterable($variable))) {
26
            $values = [];
27
            foreach ($variable as $k => $v) {
28
                $values[$k] = $this->cast($v);
29
            }
30
31
            return $values;
32
        }
33
34
        if ($variable instanceof \DateTimeImmutable) {
0 ignored issues
show
introduced by
$variable is never a sub-type of DateTimeImmutable.
Loading history...
35
            return [
36
                '__CLASS__' => $variable::class,
37
                $variable->setTimezone(new DateTimeZone('UTC'))->format('c'),
38
            ];
39
        }
40
41
        if (is_object($variable)) {
0 ignored issues
show
introduced by
The condition is_object($variable) is always false.
Loading history...
42
            $properties = $this->castObject($variable);
43
44
            return $this->cast($properties);
45
        }
46
47
        return $variable;
48
    }
49
50
    private function castObject(object $object): array|string
51
    {
52
        $key = spl_object_id($object);
53
        if (array_key_exists($key, $this->saw)) {
54
            return '__RECURSIVITY__';
55
        }
56
        $this->saw[$key] = $object;
57
58
        $values = $this->getGetterValues($object);
59
        ksort($values);
60
61
        $values = array_merge(['__CLASS__' => $object::class], $values);
62
63
        return $values;
64
    }
65
66
    private function getGetterValues(object $object): array
67
    {
68
        $class = new ReflectionClass($object);
69
70
        $values = [];
71
        foreach ($class->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
72
            $name = $method->getName();
73
            if (str_starts_with($name, 'get')) {
74
                $values[$name] = $method->invoke($object);
75
            }
76
        }
77
78
        return $values;
79
    }
80
}
81