Repository navigation
Expand file tree
/
Copy pathDebugValue.php
More file actions
588 lines (508 loc) · 18.1 KB
/
Copy pathDebugValue.php
File metadata and controls
588 lines (508 loc) · 18.1 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
<?php
declare(strict_types=1);
namespace PHPForge\Debug\Storage;
use Closure;
use JsonSerializable;
use SensitiveParameter;
use SplObjectStorage;
use Stringable;
use Throwable;
use function base64_decode;
use function base64_encode;
use function get_object_vars;
use function get_resource_type;
use function in_array;
use function is_array;
use function is_bool;
use function is_finite;
use function is_float;
use function is_int;
use function is_nan;
use function is_object;
use function is_resource;
use function is_string;
use function mb_check_encoding;
use function sprintf;
/**
* Represents an arbitrary PHP value as JSON-safe tagged data.
*
* Hydration deliberately recreates this value object rather than executable objects, resources, or closures.
*
* @phpstan-type DebugValueType 'null'|'bool'|'int'|'float'|'special-float'|'string'|'binary'|'array'|'object'|'resource'|'truncated'|'recursion'|'unsupported'
*/
final readonly class DebugValue implements JsonSerializable
{
/**
* Defines the required fields for each encoded entry.
*
* @var list<string>
*/
private const array ENTRY_SHAPE = [
'keyType',
'key',
'value',
];
/**
* Limits the maximum nesting depth captured or hydrated.
*/
private const int MAX_DEPTH = 10;
/**
* Limits the maximum number of tagged values processed during capture.
*/
private const int MAX_NODES = 10000;
/**
* Maps each tagged value type to its required fields.
*
* @var array<string, list<string>>
*/
private const array SHAPES = [
'null' => ['type'],
'bool' => ['type', 'value'],
'int' => ['type', 'value'],
'float' => ['type', 'value'],
'special-float' => ['type', 'value'],
'string' => ['type', 'value'],
'binary' => ['type', 'encoding', 'data'],
'array' => ['type', 'entries'],
'object' => ['type', 'value', 'entries', 'class'],
'resource' => ['type', 'resourceType'],
'truncated' => ['type', 'value', 'reason'],
'recursion' => ['type', 'value', 'reason'],
'unsupported' => ['type', 'value', 'reason'],
];
/**
* Creates a tagged debug value from normalized fields.
*
* @param string $type Tagged value type.
* @param bool|float|int|string|null $value Captured scalar value or display label.
* @param list<array{keyType: 'int'|'string', key: int|string, value: self}> $entries Captured child values.
* @param string|null $className Captured object class or `null` for non-object values.
* @param string|null $resourceType Captured resource type or `null` for non-resource values.
* @param string|null $reason Truncation or unsupported-value reason, or `null` when not applicable.
*/
private function __construct(
public string $type,
public bool|float|int|string|null $value = null,
public array $entries = [],
public string|null $className = null,
public string|null $resourceType = null,
public string|null $reason = null,
) {}
/**
* Captures an arbitrary PHP value as JSON-safe tagged data.
*
* @param mixed $value PHP value to capture.
*
* @return self Tagged debug value.
*/
public static function capture(#[SensitiveParameter] mixed $value): self
{
$objects = new SplObjectStorage();
$nodes = 0;
return self::normalize($value, 0, $nodes, $objects);
}
/**
* Hydrates a tagged debug value from decoded JSON data.
*
* @param mixed $data Decoded tagged value.
* @param string $path Payload path used in hydration errors.
*
* @return self Hydrated debug value.
*/
public static function fromArray(mixed $data, string $path = '$'): self
{
$nodes = 0;
return self::hydrate($data, $path, 0, $nodes);
}
/**
* Returns the tagged value for JSON serialization.
*
* @return array<string, mixed> Tagged debug value payload.
*/
public function jsonSerialize(): array
{
$data = ['type' => $this->type];
if (in_array($this->type, ['bool', 'int', 'float', 'special-float', 'string'], true)) {
$data['value'] = $this->value;
}
if ($this->type === 'binary') {
$data['encoding'] = 'base64';
$data['data'] = base64_encode(is_string($this->value) ? $this->value : '');
}
if ($this->type === 'array' || $this->type === 'object') {
$data['entries'] = [];
foreach ($this->entries as $entry) {
$data['entries'][] = [
'keyType' => $entry['keyType'],
'key' => $entry['key'],
'value' => $entry['value']->jsonSerialize(),
];
}
}
if ($this->className !== null) {
$data['class'] = $this->className;
}
if ($this->resourceType !== null) {
$data['resourceType'] = $this->resourceType;
}
if ($this->reason !== null) {
$data['reason'] = $this->reason;
$data['value'] = is_string($this->value) ? $this->value : null;
}
if ($this->type === 'object') {
$data['value'] = is_string($this->value) ? $this->value : null;
}
return $data;
}
/**
* Returns the entries as a plain PHP array, keeping the key types captured from the original value.
*
* @return array<int|string, mixed> Display-safe child values retaining captured key types.
*/
public function toDisplayEntries(): array
{
$result = [];
foreach ($this->entries as $entry) {
$result[$entry['key']] = $entry['value']->toDisplayValue();
}
return $result;
}
/**
* Returns a safe PHP representation suitable for existing dump and table renderers.
*
* @return mixed Display-safe PHP value.
*/
public function toDisplayValue(): mixed
{
return match ($this->type) {
'null' => null,
'bool', 'int', 'float', 'string' => $this->value,
'special-float', 'binary', 'resource', 'truncated', 'recursion', 'unsupported' => $this->displayLabel(),
'array' => $this->toDisplayEntries(),
'object' => ['__class' => $this->className ?? 'object'] + $this->toDisplayEntries(),
default => '(unsupported)',
};
}
/**
* Returns the display label for a non-scalar tagged value.
*
* @return string Display-safe label.
*/
private function displayLabel(): string
{
return match ($this->type) {
'binary' => sprintf(
'(binary: base64 %s)',
base64_encode(is_string($this->value) ? $this->value : ''),
),
'resource' => sprintf('(resource: %s)', $this->resourceType ?? 'unknown'),
default => is_string($this->value) && $this->value !== ''
? $this->value
: sprintf('(%s: %s)', $this->type, $this->reason ?? 'unknown'),
};
}
/**
* Returns a decoded entry object with its exact required shape.
*
* @return array{keyType: mixed, key: mixed, value: mixed} Validated entry fields.
*/
private static function entryObject(mixed $value, string $path): array
{
$entry = Payload::object($value, $path)->shape(self::ENTRY_SHAPE);
return [
'keyType' => $entry->raw('keyType'),
'key' => $entry->raw('key'),
'value' => $entry->raw('value'),
];
}
/**
* Hydrates a base64-encoded binary value.
*
* @param Payload $payload Validated tagged value payload.
* @param string $path Payload path used in hydration errors.
*
* @return self Hydrated binary value.
*/
private static function fromBinary(Payload $payload, string $path): self
{
if ($payload->string('encoding') !== 'base64') {
throw HydrationException::at(
"{$path}.encoding",
'base64',
);
}
$decoded = base64_decode($payload->string('data'), true);
if ($decoded === false) {
throw HydrationException::at(
"{$path}.data",
'valid base64 data',
);
}
return new self(
'binary',
$decoded,
);
}
/**
* Hydrates a non-finite floating-point label.
*
* @param Payload $payload Validated tagged value payload.
* @param string $path Payload path used in hydration errors.
*
* @return self Hydrated non-finite floating-point value.
*/
private static function fromSpecialFloat(Payload $payload, string $path): self
{
$value = $payload->string('value');
if (!in_array($value, ['NAN', 'INF', '-INF'], true)) {
throw HydrationException::at(
"{$path}.value",
'NAN, INF, or -INF',
);
}
return new self(
'special-float',
$value,
);
}
/**
* Hydrates one tagged value while enforcing the same structural budget used during capture.
*
* @param mixed $data Decoded tagged value.
* @param string $path Payload path used in hydration errors.
* @param int $depth Current nesting depth.
* @param int $nodes Number of tagged values visited across the hydration operation.
*/
private static function hydrate(mixed $data, string $path, int $depth, int &$nodes): self
{
$type = '';
$payload = self::taggedObject($data, $path, $type);
if (++$nodes > self::MAX_NODES + 1) {
throw HydrationException::at(
$path,
'at most 10000 captured nodes',
);
}
if ($depth > self::MAX_DEPTH && $type !== 'truncated') {
throw HydrationException::at(
$path,
'at most 10 nested levels',
);
}
return match ($type) {
'null' => new self('null'),
'bool' => new self('bool', $payload->bool('value')),
'int' => new self('int', $payload->int('value')),
'float' => new self('float', $payload->number('value')),
'special-float' => self::fromSpecialFloat($payload, $path),
'string' => new self('string', $payload->string('value')),
'binary' => self::fromBinary($payload, $path),
'array' => new self('array', entries: self::hydrateEntries($payload, $path, $depth, $nodes)),
'object' => new self(
'object',
value: $payload->nullableString('value'),
entries: self::hydrateEntries($payload, $path, $depth, $nodes),
className: $payload->string('class'),
),
'resource' => new self(
'resource',
resourceType: $payload->string('resourceType'),
),
'truncated', 'recursion', 'unsupported' => new self(
$type,
value: $payload->nullableString('value'),
reason: $payload->string('reason'),
),
};
}
/**
* Hydrates tagged array or object entries.
*
* @param Payload $payload Validated tagged value payload.
* @param string $path Payload path used in hydration errors.
*
* @return list<array{keyType: 'int'|'string', key: int|string, value: self}> Hydrated entries.
*/
private static function hydrateEntries(Payload $payload, string $path, int $depth, int &$nodes): array
{
$entries = [];
foreach ($payload->list('entries') as $index => $rawEntry) {
$entryPath = "{$path}.entries[{$index}]";
$entry = self::entryObject($rawEntry, $entryPath);
$keyType = $entry['keyType'];
$key = $entry['key'];
if (!is_string($keyType)) {
throw HydrationException::at(
"{$entryPath}.keyType",
'a string',
);
}
if (
($keyType !== 'int' && $keyType !== 'string')
|| ($keyType === 'int' && !is_int($key))
|| ($keyType === 'string' && !is_string($key))
) {
throw HydrationException::at(
"{$entryPath}.key",
'a key matching keyType',
);
}
$entries[] = [
'keyType' => $keyType,
'key' => $key,
'value' => self::hydrate($entry['value'], "{$entryPath}.value", $depth + 1, $nodes),
];
}
return $entries;
}
/**
* Normalizes a PHP value while enforcing depth and node limits.
*
* @param mixed $value PHP value to normalize.
* @param int $depth Current nesting depth.
* @param int $nodes Number of values visited across the capture operation.
* @param SplObjectStorage<object, mixed> $objects Objects active in the current traversal path.
*
* @return self Normalized debug value.
*/
private static function normalize(
mixed $value,
int $depth,
int &$nodes,
SplObjectStorage $objects,
): self {
if (++$nodes > self::MAX_NODES) {
return new self('truncated', value: '*SKIPPED over 10000 nodes*', reason: 'size');
}
if ($depth > self::MAX_DEPTH) {
return new self('truncated', value: '*DEEP NESTED VALUE*', reason: 'depth');
}
if ($value === null) {
return new self('null');
}
if (is_bool($value)) {
return new self('bool', $value);
}
if (is_int($value)) {
return new self('int', $value);
}
if (is_float($value)) {
return is_finite($value)
? new self('float', $value)
: new self(
'special-float',
match (true) {
is_nan($value) => 'NAN',
$value === INF => 'INF',
default => '-INF',
},
);
}
if (is_string($value)) {
return mb_check_encoding($value, 'UTF-8')
? new self('string', $value)
: new self('binary', $value);
}
if (is_array($value)) {
$entries = [];
foreach ($value as $key => $entry) {
$entries[] = [
'keyType' => is_int($key) ? 'int' : 'string',
'key' => is_int($key) ? $key : Json::safeString($key),
'value' => self::normalize($entry, $depth + 1, $nodes, $objects),
];
if ($nodes > self::MAX_NODES) {
break;
}
}
return new self('array', entries: $entries);
}
if (is_object($value)) {
if ($objects->offsetExists($value)) {
return new self('recursion', value: $value::class, reason: 'object-cycle');
}
$objects->offsetSet($value);
$entries = [];
foreach (get_object_vars($value) as $key => $entry) {
$entries[] = [
'keyType' => 'string',
'key' => Json::safeString((string) $key),
'value' => self::normalize($entry, $depth + 1, $nodes, $objects),
];
if ($nodes > self::MAX_NODES) {
break;
}
}
$objects->offsetUnset($value);
return new self(
'object',
value: self::objectLabel($value),
entries: $entries,
className: $value::class,
);
}
if (is_resource($value)) {
return new self('resource', resourceType: get_resource_type($value));
}
// Closed resources report `false` from is_resource(), so they land here rather than in the branch above.
return new self('unsupported', value: '(unsupported)', reason: 'unknown-type');
}
/**
* Returns a safe display label for an object.
*
* @param object $value Object to describe.
*
* @return string Display-safe object label.
*/
private static function objectLabel(object $value): string
{
if ($value instanceof Closure) {
return '\\Closure';
}
if ($value instanceof Throwable) {
$class = $value::class;
$message = $value->getMessage();
return Json::safeString($class) . ': ' . Json::safeString($message);
}
if ($value instanceof Stringable) {
try {
return Json::safeString((string) $value);
} catch (Throwable) {
// Fall through to the class name when userland string conversion fails.
}
}
return Json::safeString($value::class);
}
/**
* Returns a decoded tagged-value object matching its type-specific shape.
*
* @param-out DebugValueType $type Validated tagged-value type.
*
* @return Payload Validated tagged-value reader.
*/
private static function taggedObject(mixed $value, string $path, string &$type): Payload
{
$payload = Payload::object($value, $path);
$rawType = $payload->raw('type');
if (!is_string($rawType)) {
throw HydrationException::at("{$path}.type", 'a string');
}
$type = match ($rawType) {
'null' => 'null',
'bool' => 'bool',
'int' => 'int',
'float' => 'float',
'special-float' => 'special-float',
'string' => 'string',
'binary' => 'binary',
'array' => 'array',
'object' => 'object',
'resource' => 'resource',
'truncated' => 'truncated',
'recursion' => 'recursion',
'unsupported' => 'unsupported',
default => throw HydrationException::at("{$path}.type", 'a known debug-value type'),
};
return $payload->shape(self::SHAPES[$type]);
}
}