src/SplObjectStorageStasis.php source

1 <?php
2
3 declare(strict_types=1);
4
5 namespace Serializor;
6
7 use SplObjectStorage;
8
9 /**
10 * Stasis for SplObjectStorage objects.
11 * Uses objects as keys with associated data values.
12 */
13 final class SplObjectStorageStasis extends Stasis
14 {
15 private array $objects = [];
16 private array $data = [];
17
18 private function __construct() {}
19
20 public function __serialize(): array
21 {
22 return ['o' => $this->objects, 'd' => $this->data];
23 }
24
25 public function __unserialize(array $data): void
26 {
27 $this->objects = $data['o'];
28 $this->data = $data['d'];
29 }
30
31 public function getClassName(): string
32 {
33 return SplObjectStorage::class;
34 }
35
36 public static function fromStorage(SplObjectStorage $value): SplObjectStorageStasis
37 {
38 $frozen = new SplObjectStorageStasis();
39
40 foreach ($value as $obj) {
41 $frozen->objects[] = $obj;
42 $frozen->data[] = $value[$obj];
43 }
44
45 return $frozen;
46 }
47
48 /**
49 * Get the objects for transformation.
50 */
51 public function &getObjects(): array
52 {
53 return $this->objects;
54 }
55
56 /**
57 * Get the data for transformation.
58 */
59 public function &getData(): array
60 {
61 return $this->data;
62 }
63
64 public function &getInstance(): mixed
65 {
66 if ($this->hasInstance()) {
67 return $this->getCachedInstance();
68 }
69
70 $storage = new SplObjectStorage();
71
72 for ($i = 0, $len = count($this->objects); $i < $len; $i++) {
73 $storage[$this->objects[$i]] = $this->data[$i];
74 }
75
76 $this->setInstance($storage);
77 return $storage;
78 }
79 }
80