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