1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
|
4
|
|
|
namespace suda\framework\debug; |
5
|
|
|
|
6
|
|
|
use ReflectionProperty; |
7
|
|
|
|
8
|
|
|
class DebugObject implements \JsonSerializable |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* @var DebugObjectContext |
12
|
|
|
*/ |
13
|
|
|
protected $context; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @var mixed |
17
|
|
|
*/ |
18
|
|
|
protected $value; |
19
|
|
|
|
20
|
|
|
public function __construct($value, DebugObjectContext $context = null) |
21
|
|
|
{ |
22
|
|
|
$this->context = $context ?: new DebugObjectContext(); |
23
|
|
|
$this->value = $value; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @param array $value |
28
|
|
|
* @return array |
29
|
|
|
*/ |
30
|
|
|
protected function parseArray(array $value) |
31
|
|
|
{ |
32
|
|
|
foreach ($value as $key => $val) { |
33
|
|
|
$value[$key] = new DebugObject($val, $this->context); |
34
|
|
|
} |
35
|
|
|
return $value; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @param DebugObject $object |
40
|
|
|
* @return array |
41
|
|
|
*/ |
42
|
|
|
protected function parseObject($object) |
43
|
|
|
{ |
44
|
|
|
$objectHash = spl_object_hash($object); |
45
|
|
|
if ($this->context->isObjectExported($objectHash)) { |
46
|
|
|
return ['_type' => get_class($object), '_hash' => $objectHash]; |
47
|
|
|
} |
48
|
|
|
$this->context->setObjectIsExported($objectHash); |
49
|
|
|
return [ |
50
|
|
|
'_type' => get_class($object), |
51
|
|
|
'_hash' => $objectHash, |
52
|
|
|
'_properties' => $this->getObjectProp($object) |
53
|
|
|
]; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @param $object |
58
|
|
|
* @return string|array |
59
|
|
|
*/ |
60
|
|
|
protected function getObjectProp($object) |
61
|
|
|
{ |
62
|
|
|
try { |
63
|
|
|
$oR = new \ReflectionClass($object); |
64
|
|
|
$props = $oR->getProperties( |
65
|
|
|
ReflectionProperty::IS_PUBLIC |
66
|
|
|
| ReflectionProperty::IS_PROTECTED |
67
|
|
|
| ReflectionProperty::IS_PRIVATE |
68
|
|
|
); |
69
|
|
|
$exported = []; |
70
|
|
|
foreach ($props as $value) { |
71
|
|
|
$name = dechex($value->getModifiers()) . '$' . $value->getName(); |
72
|
|
|
$value->setAccessible(true); |
73
|
|
|
$exported[$name] = new DebugObject($value->getValue($object), $this->context); |
74
|
|
|
} |
75
|
|
|
return $exported; |
76
|
|
|
} catch (\ReflectionException $e) { |
77
|
|
|
return 'Err:' . $e->getMessage(); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
|
82
|
|
|
|
83
|
|
|
public function jsonSerialize() |
84
|
|
|
{ |
85
|
|
|
if (is_object($this->value)) { |
86
|
|
|
return $this->parseObject($this->value); |
87
|
|
|
} |
88
|
|
|
if (is_array($this->value)) { |
89
|
|
|
return $this->parseArray($this->value); |
90
|
|
|
} |
91
|
|
|
if (is_resource($this->value)) { |
92
|
|
|
return ['_resource' => get_resource_type($this->value)]; |
93
|
|
|
} |
94
|
|
|
return $this->value; |
95
|
|
|
} |
96
|
|
|
} |
97
|
|
|
|