src/SplFixedArrayStasis.php source

1 <?php
2
3 declare(strict_types=1);
4
5 namespace Serializor;
6
7 use SplFixedArray;
8
9 /**
10 * Stasis for SplFixedArray on PHP versions that lack __serialize()/__unserialize().
11 * PHP 8.2+ has native support; this handles PHP 8.1.
12 */
13 final class SplFixedArrayStasis extends Stasis
14 {
15 /**
16 * The array size.
17 */
18 private int $s;
19
20 /**
21 * The array elements.
22 */
23 public array $e = [];
24
25 public function __construct(int $size)
26 {
27 $this->s = $size;
28 }
29
30 public function __serialize(): array
31 {
32 return [$this->s, $this->e];
33 }
34
35 public function __unserialize(array $data): void
36 {
37 [$this->s, $this->e] = $data;
38 }
39
40 public function getClassName(): string
41 {
42 return SplFixedArray::class;
43 }
44
45 /**
46 * Get reference to elements array for transformation.
47 */
48 public function &getElements(): array
49 {
50 return $this->e;
51 }
52
53 public static function fromArray(SplFixedArray $source): self
54 {
55 $frozen = new self($source->getSize());
56 foreach ($source as $i => $v) {
57 $frozen->e[$i] = $v;
58 }
59 return $frozen;
60 }
61
62 public function &getInstance(): mixed
63 {
64 if ($this->hasInstance()) {
65 return $this->getCachedInstance();
66 }
67
68 $arr = new SplFixedArray($this->s);
69 foreach ($this->e as $i => $v) {
70 if ($v instanceof Stasis) {
71 if ($v->hasInstance()) {
72 $arr[$i] = $v->getInstance();
73 } else {
74 $v->whenResolved(function ($instance) use ($arr, $i) {
75 $arr[$i] = $instance;
76 });
77 }
78 } else {
79 $arr[$i] = $v;
80 }
81 }
82
83 $this->setInstance($arr);
84 return $arr;
85 }
86 }
87