forked from Respect/Stringifier
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObjectStringifier.php
More file actions
107 lines (88 loc) · 2.98 KB
/
ObjectStringifier.php
File metadata and controls
107 lines (88 loc) · 2.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<?php
/*
* This file is part of Respect/Stringifier.
* Copyright (c) Henrique Moody <henriquemoody@gmail.com>
* SPDX-License-Identifier: MIT
*/
declare(strict_types=1);
namespace Respect\Stringifier\Stringifiers;
use ReflectionObject;
use ReflectionProperty;
use Respect\Stringifier\Helpers\ObjectHelper;
use Respect\Stringifier\Quoter;
use Respect\Stringifier\Stringifier;
use function count;
use function is_object;
use function sprintf;
use function trim;
final class ObjectStringifier implements Stringifier
{
use ObjectHelper;
private const LIMIT_EXCEEDED_PLACEHOLDER = '...';
public function __construct(
private readonly Stringifier $stringifier,
private readonly Quoter $quoter,
private readonly int $maximumDepth,
private readonly int $maximumNumberOfProperties
) {
}
public function stringify(mixed $raw, int $depth): ?string
{
if (!is_object($raw)) {
return null;
}
if ($depth >= $this->maximumDepth) {
return $this->quoter->quote($this->format($raw, self::LIMIT_EXCEEDED_PLACEHOLDER), $depth);
}
return $this->quoter->quote(
$this->format($raw, ...$this->getProperties(new ReflectionObject($raw), $raw, $depth + 1)),
$depth
);
}
/**
* @return array<int, string>
*/
private function getProperties(ReflectionObject $reflectionObject, object $object, int $depth): array
{
$reflectionProperties = [];
while ($reflectionObject) {
$reflectionProperties = [
...$reflectionProperties,
...$reflectionObject->getProperties(),
];
$reflectionObject = $reflectionObject->getParentClass();
}
if (count($reflectionProperties) === 0) {
return [];
}
$properties = [];
foreach ($reflectionProperties as $reflectionProperty) {
if (count($properties) >= $this->maximumNumberOfProperties) {
$properties[] = self::LIMIT_EXCEEDED_PLACEHOLDER;
break;
}
$properties[] = trim(sprintf(
'%s$%s=%s',
match (true) {
$reflectionProperty->isPrivate() => '-',
$reflectionProperty->isProtected() => '#',
default => '+',
},
$reflectionProperty->getName(),
$this->getPropertyValue($reflectionProperty, $object, $depth)
));
}
return $properties;
}
private function getPropertyValue(ReflectionProperty $reflectionProperty, object $object, int $depth): ?string
{
if (!$reflectionProperty->isInitialized($object)) {
return '*uninitialized*';
}
$value = $reflectionProperty->getValue($object);
if (is_object($value)) {
return $this->stringify($value, $depth);
}
return $this->stringifier->stringify($value, $depth);
}
}