-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeepClone.php
More file actions
1681 lines (1523 loc) · 73.2 KB
/
DeepClone.php
File metadata and controls
1681 lines (1523 loc) · 73.2 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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Polyfill\DeepClone;
/**
* @author Nicolas Grekas <p@tchwork.com>
*
* @internal
*/
final class DeepClone
{
/** Internal classes that silently lose state through property restoration. */
private const NOT_ROUND_TRIPPABLE = [
'ZipArchive' => true,
'XMLWriter' => true,
'XMLReader' => true,
'SNMP' => true,
'tidy' => true,
];
private static array $reflectors = [];
private static array $prototypes = [];
private static array $cloneable = [];
private static array $instantiableWithoutConstructor = [];
private static array $needsFullUnserialize = [];
private static array $hydrators = [];
private static array $simpleHydrators = [];
private static array $scopeMaps = [];
private static array $propertyScopes = []; // [class][key] = [declaring class, real name]; key is bare name, "\0*\0name", or "\0class\0name"
private static array $protos = [];
private static array $classInfo = [];
private static \stdClass $sentinel;
/**
* @param list<string>|null $allowed_classes Classes that may be serialized
* (null = all, [] = none)
*/
public static function deepclone_to_array(mixed $value, ?array $allowed_classes = null): array
{
if (\is_resource($value)) {
throw new \DeepClone\NotInstantiableException('Type "'.get_resource_type($value).' resource" is not instantiable.');
}
if (!\is_object($value) && !(\is_array($value) && $value) || $value instanceof \UnitEnum) {
return ['value' => $value];
}
$allowedSet = null;
if (null !== $allowed_classes) {
$allowedSet = [];
foreach ($allowed_classes as $cls) {
if (!\is_string($cls)) {
throw new \ValueError('deepclone_to_array(): Argument $allowed_classes must be an array of class names, '.self::valueName($cls).' given');
}
$allowedSet[strtolower($cls)] = true;
}
}
$objectsPool = [];
$refsPool = [];
$objectsCount = 0;
$isStatic = true;
$refs = [];
$refMasks = [];
$topMask = null;
try {
$prepared = self::prepare([$value], $objectsPool, $refsPool, $objectsCount, $isStatic, $topMask, $allowedSet)[0];
} finally {
// Snapshot ref state while references still break cycles.
foreach ($refsPool as $i => $v) {
if ($v[0]->count) {
if ($v[1] instanceof \UnitEnum) {
$refs[1 + $i] = $v[1]::class.'::'.$v[1]->name;
$refMasks[1 + $i] = 'e';
} elseif (\is_object($v[1])) {
$oid = spl_object_id($v[1]);
$refs[1 + $i] = isset($objectsPool[$oid]) ? $objectsPool[$oid][0] : $v[2];
$refMasks[1 + $i] = true;
} elseif (\is_array($v[2])) {
$m = null;
$refs[1 + $i] = self::replaceRefs($v[2], $m);
if (null !== $m) {
$refMasks[1 + $i] = $m;
}
} else {
$refs[1 + $i] = $v[2];
}
}
$v[0] = $v[1];
}
}
if ($isStatic) {
return ['value' => $value];
}
$objectMeta = [];
$properties = [];
$resolve = [];
$states = [];
foreach ($objectsPool as [$id, $class, $props, $wakeup, $v, $propMask]) {
$objectMeta[$id] = [$class, $wakeup];
if (0 < $wakeup) {
$states[$wakeup] = $id;
} elseif (0 > $wakeup) {
$states[-$wakeup] = null !== $propMask ? [$id, $props, $propMask] : [$id, $props];
$props = [];
}
foreach ($props as $scope => $scopeProps) {
foreach ($scopeProps as $name => $propValue) {
$properties[$scope][$name][$id] = $propValue;
if (isset($propMask[$scope][$name])) {
$resolve[$scope][$name][$id] = $propMask[$scope][$name];
}
}
}
}
ksort($states);
// Unwrap remaining Reference objects into plain integers/arrays.
$preparedMask = \is_int($prepared) ? null : ($topMask[0] ?? null);
if (!\is_int($prepared)) {
$m = null;
$prepared = self::replaceRefs($prepared, $m);
if (\is_array($preparedMask)) {
if (null !== $m) {
$preparedMask = $m + array_filter($preparedMask, static fn ($v) => false !== $v);
} else {
$preparedMask = array_filter($preparedMask, static fn ($v) => false !== $v) ?: null;
}
} elseif (false === $preparedMask) {
$preparedMask = $m;
}
}
foreach ($resolve as $scope => $names) {
foreach ($names as $name => $ids) {
foreach ($ids as $id => $marker) {
if (false !== $marker) {
continue;
}
$v = $properties[$scope][$name][$id];
if (!$v instanceof Reference) {
$m = null;
$properties[$scope][$name][$id] = self::replaceRefs($v, $m);
if (null !== $m) {
$ids[$id] = $m;
} else {
unset($ids[$id]);
}
} elseif ($v->count) {
$properties[$scope][$name][$id] = $v->id;
$ids[$id] = true;
} else {
$m = null;
$properties[$scope][$name][$id] = self::replaceRefs($v->value, $m);
if (null !== $m) {
$ids[$id] = $m;
} else {
unset($ids[$id]);
}
}
}
$resolve[$scope][$name] = $ids;
}
}
foreach ($states as $k => $v) {
if (\is_array($v)) {
$m = null;
$states[$k][1] = self::replaceRefs($v[1], $m);
if ($m) {
$states[$k][2] = isset($v[2]) ? $v[2] + $m : $m;
}
}
}
// After unwrapping unshared hard refs, the value may have become static.
if (!$objectMeta && !$refs && null === $preparedMask) {
return ['value' => $prepared];
}
// Deduplicate class names in objectMeta.
$classes = [];
$classMap = [];
$metaOut = [];
foreach ($objectMeta as $id => [$class, $wakeup]) {
if (!isset($classMap[$class])) {
$classMap[$class] = \count($classes);
$classes[] = $class;
}
$metaOut[$id] = 0 !== $wakeup ? [$classMap[$class], $wakeup] : $classMap[$class];
}
// When all entries share class index 0 with wakeup 0, store just the count.
$n = \count($metaOut);
foreach ($metaOut as $v) {
if (0 !== $v) {
$n = $metaOut;
break;
}
}
$data = [
'classes' => 1 === \count($classes) ? $classes[0] : ($classes ?: ''),
'objectMeta' => $n,
'prepared' => $prepared,
];
if (null !== $preparedMask) {
$data['mask'] = $preparedMask;
}
if ($properties) {
$data['properties'] = $properties;
}
if ($resolve) {
$data['resolve'] = $resolve;
}
if ($states) {
$data['states'] = $states;
}
if ($refs) {
$data['refs'] = $refs;
}
if ($refMasks) {
$data['refMasks'] = $refMasks;
}
return $data;
}
/**
* @param list<string>|null $allowed_classes Classes that may be instantiated
* (null = all, [] = none)
*/
public static function deepclone_from_array(array $data, ?array $allowed_classes = null): mixed
{
if (\array_key_exists('value', $data)) {
return $data['value'];
}
if (!\array_key_exists('classes', $data)) {
throw new \ValueError('deepclone_from_array(): Argument #1 ($data) is missing required "classes" key');
}
if (!\array_key_exists('objectMeta', $data)) {
throw new \ValueError('deepclone_from_array(): Argument #1 ($data) is missing required "objectMeta" key');
}
if (!\array_key_exists('prepared', $data)) {
throw new \ValueError('deepclone_from_array(): Argument #1 ($data) is missing required "prepared" key');
}
$classes = $data['classes'];
if (!\is_string($classes) && !\is_array($classes)) {
throw new \ValueError('deepclone_from_array(): Argument #1 ($data) "classes" must be of type string|array, '.self::valueName($classes).' given');
}
$meta = $data['objectMeta'];
if (!\is_int($meta) && !\is_array($meta)) {
throw new \ValueError('deepclone_from_array(): Argument #1 ($data) "objectMeta" must be of type int|array, '.self::valueName($meta).' given');
}
foreach (['properties', 'resolve', 'states', 'refs', 'refMasks'] as $key) {
if (\array_key_exists($key, $data) && !\is_array($data[$key])) {
throw new \ValueError('deepclone_from_array(): Argument #1 ($data) "'.$key.'" must be of type array, '.self::valueName($data[$key]).' given');
}
}
if (\is_string($classes)) {
$classes = '' !== $classes ? [$classes] : [];
} else {
foreach ($classes as $cls) {
if (!\is_string($cls)) {
throw new \ValueError('deepclone_from_array(): Argument #1 ($data) "classes" entries must be of type string, '.self::valueName($cls).' given');
}
}
$classes = array_values($classes);
}
$numClasses = \count($classes);
if (null !== $allowed_classes) {
$allowed = array_change_key_case(array_flip($allowed_classes));
foreach ($classes as $cls) {
if (!isset($allowed[strtolower($cls)])) {
throw new \ValueError('deepclone_from_array(): class "'.$cls.'" is not allowed');
}
}
if (!isset($allowed['closure'])) {
foreach (['mask', 'refMasks'] as $key) {
if (isset($data[$key]) && self::maskHasClosure($data[$key])) {
throw new \ValueError('deepclone_from_array(): class "Closure" is not allowed');
}
}
if (isset($data['resolve'])) {
foreach ($data['resolve'] as $scope) {
if (\is_array($scope)) {
foreach ($scope as $name) {
if (self::maskHasClosure($name)) {
throw new \ValueError('deepclone_from_array(): class "Closure" is not allowed');
}
}
}
}
}
if (isset($data['states'])) {
foreach ($data['states'] as $state) {
if (\is_array($state) && isset($state[2]) && self::maskHasClosure($state[2])) {
throw new \ValueError('deepclone_from_array(): class "Closure" is not allowed');
}
}
}
}
}
// $expectedStates maps ids that flag a state replay to their wakeup
// sign (+1 / -1 is enough; the raw value is fine). Stays empty in
// the common no-wakeup case so the later validation pass is O(1).
$expectedStates = [];
if (\is_int($meta)) {
if ($meta < 0) {
throw new \ValueError('deepclone_from_array(): Argument #1 ($data) "objectMeta" count must be non-negative, '.$meta.' given');
}
// Sanity cap: the IS_LONG form specifies a count without the per-
// object payload, so a tiny input can demand huge allocations.
// Legitimate use never needs more than ~1M objects in a single
// payload — beyond that, use the array form which is naturally
// bounded by the hash-table size.
if ($meta > 0x100000) {
throw new \ValueError('deepclone_from_array(): Argument #1 ($data) "objectMeta" count out of range: '.$meta);
}
if ($meta > 0 && $numClasses < 1) {
throw new \ValueError('deepclone_from_array(): Argument #1 ($data) "objectMeta" references class index 0 but "classes" is empty');
}
$objectMeta = $meta ? array_fill(0, $meta, [$classes[0], 0]) : [];
$numObjects = $meta;
} else {
$numObjects = \count($meta);
$objectMeta = [];
foreach ($meta as $id => $v) {
if (!\is_int($id) || $id < 0 || $id >= $numObjects) {
throw new \ValueError('deepclone_from_array(): Argument #1 ($data) "objectMeta" entry index '.$id.' out of range');
}
if (\is_array($v)) {
$cidx = $v[0] ?? null;
$wakeup = $v[1] ?? null;
if (!\is_int($cidx) || !\is_int($wakeup)) {
throw new \ValueError('deepclone_from_array(): Argument #1 ($data) "objectMeta" entry '.$id.' must be [int, int]');
}
} elseif (\is_int($v)) {
$cidx = $v;
$wakeup = 0;
} else {
throw new \ValueError('deepclone_from_array(): Argument #1 ($data) "objectMeta" entry '.$id.' must be of type int|array, '.self::valueName($v).' given');
}
if ($cidx < 0 || $cidx >= $numClasses) {
throw new \ValueError('deepclone_from_array(): Argument #1 ($data) "objectMeta" entry '.$id.' has out-of-range class index '.$cidx);
}
$objectMeta[$id] = [$classes[$cidx], $wakeup];
if (0 !== $wakeup) {
$expectedStates[$id] = $wakeup;
}
}
}
return self::reconstruct(
$data['prepared'],
$objectMeta,
$numObjects,
$data['properties'] ?? [],
$data['resolve'] ?? [],
$data['states'] ?? [],
$data['refs'] ?? [],
$data['mask'] ?? null,
$data['refMasks'] ?? [],
$allowed_classes,
$expectedStates,
);
}
public static function deepclone_hydrate(object|string $object_or_class, array $vars = [], int $flags = 0): object
{
if ($flags & ~(\DEEPCLONE_HYDRATE_CALL_HOOKS | \DEEPCLONE_HYDRATE_NO_LAZY_INIT | \DEEPCLONE_HYDRATE_PRESERVE_REFS)) {
throw new \ValueError('deepclone_hydrate(): Argument #3 ($flags) contains unknown bits');
}
if (($flags & \DEEPCLONE_HYDRATE_CALL_HOOKS) && ($flags & \DEEPCLONE_HYDRATE_NO_LAZY_INIT)) {
throw new \ValueError('deepclone_hydrate(): Argument #3 ($flags) DEEPCLONE_HYDRATE_CALL_HOOKS and DEEPCLONE_HYDRATE_NO_LAZY_INIT are mutually exclusive');
}
if (\is_string($class = $object_or_class)) {
$r = self::$reflectors[$class] ??= self::getClassReflector($class);
if (self::$cloneable[$class]) {
$object = clone self::$prototypes[$class];
} elseif (self::$instantiableWithoutConstructor[$class]) {
$object = $r->newInstanceWithoutConstructor();
} elseif (null === self::$prototypes[$class]) {
throw new \DeepClone\NotInstantiableException('Class "'.$class.'" is not instantiable.');
} elseif ($r->implementsInterface('Serializable') && !method_exists($class, '__unserialize')) {
$object = unserialize('C:'.\strlen($class).':"'.$class.'":0:{}');
} else {
$object = unserialize('O:'.\strlen($class).':"'.$class.'":0:{}');
}
} else {
$r = null;
$object = $object_or_class;
$class = $object::class;
}
if (!$vars) {
return $object;
}
// "\0" = SPL internal state (SplObjectStorage / ArrayObject / ArrayIterator).
if ($hasSpecial = \array_key_exists("\0", $vars)) {
if (!\is_array($special = $vars["\0"])) {
throw new \ValueError('deepclone_hydrate(): Argument #2 ($vars) special key must be of type array, '.self::valueName($vars["\0"]).' given');
}
if ($object instanceof \SplObjectStorage) {
for ($i = 0, $c = \count($special); $i + 1 < $c; $i += 2) {
$object[$special[$i]] = $special[$i + 1];
}
} elseif ($object instanceof \ArrayObject || $object instanceof \ArrayIterator) {
$r ??= self::$reflectors[$class] ?? new \ReflectionClass($class);
$r->getConstructor()->invokeArgs($object, $special);
} else {
throw new \ValueError(\sprintf('deepclone_hydrate(): Argument #2 ($vars) uses the special "\\0" key, which is only supported for SplObjectStorage, ArrayObject, and ArrayIterator; got "%s"', $class));
}
if (1 === \count($vars)) {
return $object;
}
}
// Look up each key in the pre-built (propertyScopes) index, which
// handles all three mangled-key shapes uniformly — bare "foo",
// "\0*\0foo", "\0Class\0foo" — with a single hash lookup. Bare
// "foo" resolves to the most-derived declaring class; shadowed
// parent-privates are reachable via "\0Parent\0foo". Unknown
// keys fall through to the object's own class scope.
//
// Scan first: if every key maps to $class, hand $vars straight
// to the $class hydrator and skip the intermediate grouping.
// When $hasSpecial is set, the "\0" key is still in $vars and we
// must go through the grouping path to skip it.
$r ??= self::$reflectors[$class] ?? new \ReflectionClass($class);
$propertyScopes = self::$propertyScopes[$class] ??= self::getPropertyScopes($r);
if (!$needsGroup = $hasSpecial) {
foreach ($vars as $name => $_) {
if (\array_key_exists($name, $propertyScopes) ? $class !== $propertyScopes[$name][0] : "\0" === ($name[0] ?? '')) {
$needsGroup = true;
break;
}
}
}
$effectiveFlags = $flags & \DEEPCLONE_HYDRATE_CALL_HOOKS;
if (\PHP_VERSION_ID >= 80400 && ($flags & \DEEPCLONE_HYDRATE_NO_LAZY_INIT)) {
$r ??= self::$reflectors[$class] ?? new \ReflectionClass($class);
if ($r->isUninitializedLazyObject($object)) {
$effectiveFlags |= \DEEPCLONE_HYDRATE_NO_LAZY_INIT;
}
}
$hasRefs = false;
if ($flags & \DEEPCLONE_HYDRATE_PRESERVE_REFS) {
foreach ($vars as $k => $_) {
if (\ReflectionReference::fromArrayElement($vars, $k)) {
$hasRefs = true;
break;
}
}
}
if (!$needsGroup) {
// Fast path: every key resolves to $class. Hand $vars straight
// to the $class hydrator — no grouping, no re-keying.
$cacheKey = $effectiveFlags ? $effectiveFlags.$class : $class;
(self::$simpleHydrators[$cacheKey] ??= self::getSimpleHydrator($class, $effectiveFlags))($vars, $object, $hasRefs);
return $object;
}
// Full parse: group values by their write scope and real name. A
// NUL-prefixed key not in $propertyScopes cannot resolve to a
// declared property, so we reject it here — which in turn means
// every scope we hand to the hydrator is $class or a real parent.
$scoped = [];
foreach ($vars as $name => &$value) {
if ([$scopeName, $realName] = $propertyScopes[$name] ?? null) {
$scoped[$scopeName][$realName] = &$value;
continue;
}
if (!\is_string($name) || "\0" !== ($name[0] ?? '')) {
$scoped[$class][$name] = &$value;
continue;
}
if ("\0" === $name) {
// Already handled above as the SPL special key.
continue;
}
// NUL-prefixed key that isn't in $propertyScopes: either malformed
// syntax, an unknown scope class, or a valid scope + unknown prop.
// Differentiate to match the ext's error messages.
$sep = strpos($name, "\0", 1);
if (false === $sep || 1 === $sep || str_contains(substr($name, $sep + 1), "\0")) {
throw new \ValueError('deepclone_hydrate(): Argument #2 ($vars) contains an invalid mangled key');
}
$scopeName = substr($name, 1, $sep - 1);
$realName = substr($name, $sep + 1);
if ('*' !== $scopeName && 'stdClass' !== $scopeName
&& $scopeName !== $class
&& (!is_a($class, $scopeName, true) || interface_exists($scopeName, false))
) {
throw new \ValueError(\sprintf('deepclone_hydrate(): Argument #2 ($vars) key scope "%s" is not a parent of "%s"', $scopeName, $class));
}
// Valid scope, but the targeted slot isn't declared — reject
// instead of silently creating a dynamic property, since the
// mangled form specifically targets a declared protected/private slot.
throw new \ValueError(\sprintf('deepclone_hydrate(): Argument #2 ($vars) key scope "%s" does not declare a "%s" property', '*' === $scopeName ? $class : $scopeName, $realName));
}
unset($value);
foreach ($scoped as $scope => $properties) {
$cacheKey = $effectiveFlags ? $effectiveFlags.$scope : $scope;
(self::$simpleHydrators[$cacheKey] ??= self::getSimpleHydrator($scope, $effectiveFlags))($properties, $object, $hasRefs);
}
return $object;
}
/**
* Builds a per-class map keyed by every shape a caller might use to
* target a declared property:
* - bare "name" (public/protected inherited or own; for private
* declared on $class; also set to the most-derived
* private when a parent-private shares the name)
* - "\0*\0name" (for protected props — points to the declaring
* class entry)
* - "\0ClassName\0name" (for private props declared on ClassName, where
* ClassName is $class or a parent).
*
* Each entry is [$declaringClass, $propertyName] — the scope and real
* name to use for grouping + dispatch. Adapted from VarExporter's
* LazyObjectRegistry::getPropertyScopes().
*/
private static function getPropertyScopes(\ReflectionClass $class): array
{
$propertyScopes = [];
foreach ($class->getProperties() as $property) {
if ($property->isStatic()) {
continue;
}
$name = $property->name;
$entry = [$property->class, $name];
if ($property->isPrivate()) {
$propertyScopes["\0".$property->class."\0".$name] = $propertyScopes[$name] = $entry;
continue;
}
$propertyScopes[$name] = $entry;
if ($property->isProtected()) {
$propertyScopes["\0*\0".$name] = $entry;
}
}
while ($class = $class->getParentClass()) {
foreach ($class->getProperties(\ReflectionProperty::IS_PRIVATE) as $property) {
if ($property->isStatic()) {
continue;
}
$entry = [$property->class, $property->name];
$propertyScopes["\0".$property->class."\0".$property->name] = $entry;
$propertyScopes[$property->name] ??= $entry;
}
}
return $propertyScopes;
}
/**
* Returns a type name matching zend_zval_value_name() output for
* error messages compatible with the C extension.
*/
private static function valueName(mixed $value): string
{
if (null === $value) {
return 'null';
}
if (true === $value) {
return 'true';
}
if (false === $value) {
return 'false';
}
if (\is_object($value)) {
return $value::class;
}
return match (true) {
\is_int($value) => 'int',
\is_float($value) => 'float',
\is_string($value) => 'string',
\is_array($value) => 'array',
\is_resource($value) => 'resource',
default => get_debug_type($value),
};
}
private static function prepare($values, &$objectsPool, &$refsPool, &$objectsCount, &$valuesAreStatic, &$mask = null, ?array $allowedSet = null)
{
$sentinel = self::$sentinel ??= new \stdClass();
$refs = $values;
foreach ($values as $k => $value) {
if (\is_resource($value)) {
throw new \DeepClone\NotInstantiableException('Type "'.get_resource_type($value).' resource" is not instantiable.');
}
$refs[$k] = $sentinel;
if ($isRef = !$valueIsStatic = $values[$k] !== $sentinel) {
$values[$k] = &$value; // Break hard reference
unset($value);
$refs[$k] = $value = $values[$k];
if ($value instanceof Reference && 0 > $value->id) {
$valuesAreStatic = false;
++$value->count;
$mask[$k] = false;
continue;
}
$refsPool[] = [&$refs[$k], $value, &$value];
$refs[$k] = $values[$k] = new Reference(-\count($refsPool), $value);
}
if (\is_array($value)) {
if ($value) {
$m = null;
$value = self::prepare($value, $objectsPool, $refsPool, $objectsCount, $valueIsStatic, $m, $allowedSet);
if (null !== $m) {
$mask[$k] = $m;
}
}
goto handle_value;
} elseif (!\is_object($value) || $value instanceof \UnitEnum) {
goto handle_value;
}
$valueIsStatic = false;
$oid = spl_object_id($value);
if (isset($objectsPool[$oid])) {
++$objectsCount;
$value = $objectsPool[$oid][0];
$mask[$k] = true;
goto handle_value;
}
if ($value instanceof \Closure && ($r = new \ReflectionFunction($value)) && !(\PHP_VERSION_ID >= 80200 ? $r->isAnonymous() : str_contains($r->name, "@anonymous\0"))) {
if (null !== $allowedSet && !isset($allowedSet['closure'])) {
throw new \ValueError('deepclone_to_array(): class "Closure" is not allowed');
}
$callable = [$r->getClosureThis() ?? (\PHP_VERSION_ID >= 80111 ? $r->getClosureCalledClass() : $r->getClosureScopeClass())?->name, $r->name];
$rm = $callable[0] ? new \ReflectionMethod(...$callable) : null;
$unused = null;
$callable = self::prepare($callable, $objectsPool, $refsPool, $objectsCount, $valueIsStatic, $unused, $allowedSet);
$value = !($rm?->isPublic() ?? true) ? [$callable, $rm->class, $rm->name] : $callable;
$mask[$k] = 0;
goto handle_value;
}
$class = $value::class;
if (null !== $allowedSet && !isset($allowedSet[strtolower($class)])) {
throw new \ValueError('deepclone_to_array(): class "'.$class.'" is not allowed');
}
if ('stdClass' === $class) {
self::$reflectors[$class] ??= self::getClassReflector($class);
$arrayValue = (array) $value;
$objectsPool[$oid] = [$id = \count($objectsPool)];
$m = null;
$properties = $arrayValue ? self::prepare(['stdClass' => $arrayValue], $objectsPool, $refsPool, $objectsCount, $valueIsStatic, $m, $allowedSet) : [];
++$objectsCount;
$objectsPool[$oid] = [$id, 'stdClass', $properties, 0, $value, $m];
$value = $id;
$mask[$k] = true;
goto handle_value;
}
$reflector = self::$reflectors[$class] ??= self::getClassReflector($class);
$properties = [];
$sleep = null;
$proto = self::$prototypes[$class];
if (self::$classInfo[$class][2] ??= $reflector->hasMethod('__serialize') ? ($reflector->getMethod('__serialize')->isPublic() ?: $reflector->getMethod('__serialize')) : false) {
if (self::$classInfo[$class][2] instanceof \ReflectionMethod) {
throw new \Error('Call to '.(self::$classInfo[$class][2]->isProtected() ? 'protected' : 'private').' method "'.$class.'::__serialize()".');
}
if (!\is_array($arrayValue = $value->__serialize())) {
throw new \TypeError($class.'::__serialize() must return an array');
}
if ($hasUnserialize = self::$classInfo[$class][0] ??= $reflector->hasMethod('__unserialize')) {
$properties = $arrayValue;
goto prepare_value;
}
} elseif (($value instanceof \ArrayIterator || $value instanceof \ArrayObject) && null !== $proto) {
[$arrayValue, $properties] = self::getArrayObjectProperties($value, $proto);
// Re-create prototype consumed by (array) cast comparison above.
self::getClassReflector($class, self::$instantiableWithoutConstructor[$class], self::$cloneable[$class]);
} elseif ($value instanceof \SplObjectStorage && self::$cloneable[$class] && null !== $proto) {
// SplObjectStorage's Serializable interface breaks object references.
foreach (clone $value as $v) {
$properties[] = $v;
$properties[] = $value[$v];
}
$properties = ['SplObjectStorage' => ["\0" => $properties]];
$arrayValue = (array) $value;
} elseif ($value instanceof \Serializable || $value instanceof \__PHP_Incomplete_Class) {
++$objectsCount;
$objectsPool[$oid] = [$id = \count($objectsPool), serialize($value), [], 0, $value, null];
$value = $id;
$mask[$k] = true;
goto handle_value;
} else {
if (self::$classInfo[$class][3] ??= $reflector->hasMethod('__sleep')) {
if (!\is_array($sleep = $value->__sleep())) {
trigger_error('serialize(): __sleep should return an array only containing the names of instance-variables to serialize', \E_USER_NOTICE);
$value = null;
goto handle_value;
}
$sleep = array_flip($sleep);
}
$arrayValue = (array) $value;
}
$proto = self::$protos[$class] ??= (array) $proto;
if (null === $scopeMap = self::$scopeMaps[$class] ?? null) {
$scopeMap = [];
$parent = $reflector;
do {
foreach ($parent->getProperties() as $p) {
if (!$p->isStatic() && !isset($scopeMap[$p->name])) {
$scopeMap[$p->name] = !$p->isPublic() || (\PHP_VERSION_ID >= 80400 ? $p->isProtectedSet() || $p->isPrivateSet() : $p->isReadOnly()) ? $p->class : 'stdClass';
}
}
} while ($parent = $parent->getParentClass());
self::$scopeMaps[$class] = $scopeMap;
}
foreach ($arrayValue as $name => $v) {
$i = 0;
$n = (string) $name;
if ('' === $n || "\0" !== $n[0]) {
$c = $scopeMap[$n] ?? 'stdClass';
} elseif ('*' === $n[1]) {
$n = substr($n, 3);
$c = $scopeMap[$n] ?? $reflector->getProperty($n)->class;
} else {
$i = strpos($n, "\0", 2);
$c = substr($n, 1, $i - 1);
$n = substr($n, 1 + $i);
}
if (null !== $sleep) {
if (!isset($sleep[$name]) && (!isset($sleep[$n]) || ($i && $c !== $class))) {
unset($arrayValue[$name]);
continue;
}
unset($sleep[$name], $sleep[$n]);
}
if ("\x00Error\x00trace" === $name || "\x00Exception\x00trace" === $name || "\x00*\x00file" === $name || "\x00*\x00line" === $name || !\array_key_exists($name, $proto) || $proto[$name] !== $v) {
$properties[$c][$n] = $v;
}
}
if ($sleep) {
foreach ($sleep as $n => $v) {
if (\is_string($n) && $reflector->hasProperty($n)) {
continue;
}
trigger_error(\sprintf('serialize(): "%s" returned as member variable from __sleep() but does not exist', $n), \E_USER_NOTICE);
}
}
if ($hasUnserialize = self::$classInfo[$class][0] ??= $reflector->hasMethod('__unserialize')) {
$properties = $arrayValue;
}
prepare_value:
$objectsPool[$oid] = [$id = \count($objectsPool)];
$m = null;
$properties = self::prepare($properties, $objectsPool, $refsPool, $objectsCount, $valueIsStatic, $m, $allowedSet);
++$objectsCount;
$objectsPool[$oid] = [$id, $class, $properties, $hasUnserialize ? -$objectsCount : ((self::$classInfo[$class][1] ??= $reflector->hasMethod('__wakeup')) ? $objectsCount : 0), $value, $m];
$value = $id;
$mask[$k] = true;
handle_value:
if ($isRef) {
$mask[$k] = false;
unset($value); // Break the hard reference created above
} elseif (!$valueIsStatic) {
$values[$k] = $value;
}
$valuesAreStatic = $valueIsStatic && $valuesAreStatic;
}
return $values;
}
/**
* @param \ArrayIterator|\ArrayObject $value
* @param \ArrayIterator|\ArrayObject $proto
*/
private static function getArrayObjectProperties($value, $proto): array
{
$reflector = $value instanceof \ArrayIterator ? 'ArrayIterator' : 'ArrayObject';
$reflector = self::$reflectors[$reflector] ??= self::getClassReflector($reflector);
$properties = [
$arrayValue = (array) $value,
$reflector->getMethod('getFlags')->invoke($value),
$value instanceof \ArrayObject ? $reflector->getMethod('getIteratorClass')->invoke($value) : 'ArrayIterator',
];
$reflector = $reflector->getMethod('setFlags');
$reflector->invoke($proto, \ArrayObject::STD_PROP_LIST);
if ($properties[1] & \ArrayObject::STD_PROP_LIST) {
$reflector->invoke($value, 0);
$properties[0] = (array) $value;
} else {
$reflector->invoke($value, \ArrayObject::STD_PROP_LIST);
$arrayValue = (array) $value;
}
$reflector->invoke($value, $properties[1]);
if ([[], 0, 'ArrayIterator'] === $properties) {
$properties = [];
} else {
if ('ArrayIterator' === $properties[2]) {
unset($properties[2]);
}
$properties = [$reflector->class => ["\0" => $properties]];
}
return [$arrayValue, $properties];
}
private static function reconstruct($prepared, $objectMeta, $numObjects, $properties, $resolve, $states, $refs, $preparedMask = null, $refMasks = [], ?array $allowedClasses = null, array $expectedStates = [])
{
$objects = [];
foreach ($objectMeta as $id => [$class]) {
if (':' === ($class[1] ?? null)) {
$objects[$id] = unserialize($class, null !== $allowedClasses ? ['allowed_classes' => $allowedClasses] : []);
continue;
}
try {
self::$reflectors[$class] ??= self::getClassReflector($class);
} catch (\DeepClone\ClassNotFoundException) {
throw new \DeepClone\ClassNotFoundException('Class "'.$class.'" not found.');
}
if (self::$needsFullUnserialize[$class] ?? false) {
$objects[$id] = null; // placeholder — finalized below or in states loop
} elseif (self::$cloneable[$class]) {
$objects[$id] = clone self::$prototypes[$class];
} elseif (self::$instantiableWithoutConstructor[$class]) {
$objects[$id] = self::$reflectors[$class]->newInstanceWithoutConstructor();
} elseif (null === self::$prototypes[$class]) {
throw new \DeepClone\NotInstantiableException('Type "'.$class.'" is not instantiable.');
} elseif (self::$reflectors[$class]->implementsInterface('Serializable') && !method_exists($class, '__unserialize')) {
$objects[$id] = unserialize('C:'.\strlen($class).':"'.$class.'":0:{}');
} else {
$objects[$id] = unserialize('O:'.\strlen($class).':"'.$class.'":0:{}');
}
}
// Eagerly finalize deferred objects whose state has no object-ref masks,
// so they are real instances when the properties loop resolves references to them.
foreach ($states as $state) {
if (!\is_array($state) || null !== $objects[$state[0]] || isset($state[2])) {
continue;
}
$class = $objectMeta[$state[0]][0];
$ser = serialize($state[1] ?? []);
if (false === $obj = unserialize('O:'.\strlen($class).':"'.$class.'"'.substr($ser, strpos($ser, ':', 1)))) {
throw new \ValueError('deepclone_from_array(): could not reconstruct "'.$class.'" via __unserialize()');
}
$objects[$state[0]] = $obj;
}
foreach ($refMasks as $k => $m) {
$refs[$k] = self::resolveWithMask($refs[$k], $m, $objects, $refs);
}
foreach ($properties as $scope => $scopeProps) {
if (!\is_string($scope)) {
throw new \ValueError('deepclone_from_array(): Argument #1 ($data) "properties" keys must be of type string');
}
if (!\is_array($scopeProps)) {
throw new \ValueError('deepclone_from_array(): Argument #1 ($data) "properties" entry for scope "'.$scope.'" must be of type array, '.self::valueName($scopeProps).' given');
}
if ('stdClass' !== $scope && !class_exists($scope, false)) {
throw new \ValueError('deepclone_from_array(): Argument #1 ($data) "properties" scope "'.$scope.'" is not a loaded class name');
}
$resolveScope = null;
if (isset($resolve[$scope])) {
if (!\is_array($resolve[$scope])) {
throw new \ValueError('deepclone_from_array(): Argument #1 ($data) "resolve" entry for scope "'.$scope.'" must be of type array, '.self::valueName($resolve[$scope]).' given');
}
$resolveScope = $resolve[$scope];
}
foreach ($scopeProps as $name => $idValues) {
if (!\is_string($name)) {
throw new \ValueError('deepclone_from_array(): Argument #1 ($data) "properties" inner keys must be of type string');
}
if (!\is_array($idValues)) {
throw new \ValueError('deepclone_from_array(): Argument #1 ($data) "properties" value for "'.$scope.'::'.$name.'" must be of type array, '.self::valueName($idValues).' given');
}
$resolveIds = null;
if ($resolveScope && isset($resolveScope[$name])) {
if (!\is_array($resolveScope[$name])) {
throw new \ValueError('deepclone_from_array(): Argument #1 ($data) "resolve" value for "'.$scope.'::'.$name.'" must be of type array, '.self::valueName($resolveScope[$name]).' given');
}
$resolveIds = $resolveScope[$name];
}
if (null === $resolveIds) {
continue;
}
foreach ($resolveIds as $id => $marker) {
if (true === $marker) {
if (null === ($v = $scopeProps[$name][$id] ?? null) || !\is_int($v)) {
throw new \ValueError('deepclone_from_array(): Argument #1 ($data) malformed payload, object reference value must be of type int, '.self::valueName($v).' given');
}
if ($v >= 0) {
if (!isset($objects[$v])) {
throw new \ValueError('deepclone_from_array(): Argument #1 ($data) malformed payload, unknown object id '.$v);
}
$scopeProps[$name][$id] = $objects[$v];
} else {
if (\PHP_INT_MIN === $v) {
throw new \ValueError('deepclone_from_array(): Argument #1 ($data) malformed payload, ref id out of range');
}
if (!isset($refs[-$v])) {
throw new \ValueError('deepclone_from_array(): Argument #1 ($data) malformed payload, unknown ref id '.(-$v));
}
$scopeProps[$name][$id] = $refs[-$v];
}
} elseif (0 === $marker) {
$scopeProps[$name][$id] = self::resolveNamedClosureScalar($scopeProps[$name][$id] ?? null, $objects, $refs);
} else {
$scopeProps[$name][$id] = self::resolveWithMask($scopeProps[$name][$id] ?? null, $marker, $objects, $refs);
}
}
}
(self::$hydrators[$scope] ??= self::getHydrator($scope))($scopeProps, $objects);
}
foreach ($states as $state) {
if (\is_array($state)) {
$zid = $state[0] ?? null;
$sprops = $state[1] ?? null;
if (!\is_int($zid) || !\array_key_exists(1, $state)) {
throw new \ValueError('deepclone_from_array(): Argument #1 ($data) malformed "states" entry: expected [int, mixed, mixed?]');
}
if ($zid < 0 || $zid >= $numObjects) {
throw new \ValueError('deepclone_from_array(): Argument #1 ($data) "states" entry references unknown object id '.$zid);
}
if (!isset($expectedStates[$zid]) || $expectedStates[$zid] >= 0) {
throw new \ValueError('deepclone_from_array(): Argument #1 ($data) "states" has an __unserialize entry for object id '.$zid.' but "objectMeta" does not flag it for __unserialize');
}
unset($expectedStates[$zid]);
if (null === $obj = $objects[$zid]) {
// Internal final class with __unserialize that rejects empty unserialize
// reconstruct via the full O: serialization form (same as PHP's unserialize).
$class = $objectMeta[$zid][0];
$resolvedProps = isset($state[2]) ? self::resolveWithMask($sprops, $state[2], $objects, $refs) : $sprops;
$ser = serialize($resolvedProps);
if (false === $obj = unserialize('O:'.\strlen($class).':"'.$class.'"'.substr($ser, strpos($ser, ':', 1)))) {
throw new \ValueError('deepclone_from_array(): could not reconstruct "'.$class.'" via __unserialize()');
}
$objects[$zid] = $obj;
continue;
}
$objClass = $obj::class;