1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Genkgo\TestCamt\Unit; |
6
|
|
|
|
7
|
|
|
use DateTimeInterface; |
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 DateTimeInterface) { |
|
|
|
|
35
|
|
|
return ['__CLASS__' => $variable::class, $variable->format('c')]; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
if (is_object($variable)) { |
|
|
|
|
39
|
|
|
$properties = $this->castObject($variable); |
40
|
|
|
|
41
|
|
|
return $this->cast($properties); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
return $variable; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
private function castObject(object $object): array|string |
48
|
|
|
{ |
49
|
|
|
$key = spl_object_id($object); |
50
|
|
|
if (array_key_exists($key, $this->saw)) { |
51
|
|
|
return '__RECURSIVITY__'; |
52
|
|
|
} |
53
|
|
|
$this->saw[$key] = $object; |
54
|
|
|
|
55
|
|
|
$values = $this->getGetterValues($object); |
56
|
|
|
ksort($values); |
57
|
|
|
|
58
|
|
|
$values = array_merge(['__CLASS__' => $object::class], $values); |
59
|
|
|
|
60
|
|
|
return $values; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
private function getGetterValues(object $object): array |
64
|
|
|
{ |
65
|
|
|
$class = new ReflectionClass($object); |
66
|
|
|
|
67
|
|
|
$values = []; |
68
|
|
|
foreach ($class->getMethods(ReflectionMethod::IS_PUBLIC) as $method) { |
69
|
|
|
$name = $method->getName(); |
70
|
|
|
if (str_starts_with($name, 'get')) { |
71
|
|
|
$values[$name] = $method->invoke($object); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
return $values; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|