Debian Codegraph @

lib/3rdParty/composer/spomky-labs/cbor-php/src/IndefiniteLengthListObject.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace CBOR;
6
7 use function array_key_exists;
8 use ArrayAccess;
9 use ArrayIterator;
10 use InvalidArgumentException;
11 use Iterator;
12 use IteratorAggregate;
13
14 /**
15 * @phpstan-implements ArrayAccess<int, CBORObject>
16 * @phpstan-implements IteratorAggregate<int, CBORObject>
17 * @final
18 */
19 class IndefiniteLengthListObject extends AbstractCBORObject implements IteratorAggregate, Normalizable, ArrayAccess
20 {
21 private const MAJOR_TYPE = self::MAJOR_TYPE_LIST;
22
23 private const ADDITIONAL_INFORMATION = self::LENGTH_INDEFINITE;
24
25 /**
26 * @var CBORObject[]
27 */
28 private array $data = [];
29
30 public function __construct()
31 {
32 parent::__construct(self::MAJOR_TYPE, self::ADDITIONAL_INFORMATION);
33 }
34
35 public function __toString(): string
36 {
37 $result = parent::__toString();
38 foreach ($this->data as $object) {
39 $result .= (string) $object;
40 }
41
42 return $result . "\xFF";
43 }
44
45 public static function create(CBORObject ...$items): self
46 {
47 $object = new self();
48 foreach ($items as $item) {
49 $object->add($item);
50 }
51
52 return $object;
53 }
54
55 /**
56 * @return mixed[]
57 */
58 public function normalize(): array
59 {
60 return array_map(
61 static fn (CBORObject $object) => $object instanceof Normalizable ? $object->normalize() : $object,
62 $this->data
63 );
64 }
65
66 public function add(CBORObject $item): self
67 {
68 $this->data[] = $item;
69
70 return $this;
71 }
72
73 public function has(int $index): bool
74 {
75 return array_key_exists($index, $this->data);
76 }
77
78 public function remove(int $index): self
79 {
80 if (! $this->has($index)) {
81 return $this;
82 }
83 unset($this->data[$index]);
84 $this->data = array_values($this->data);
85
86 return $this;
87 }
88
89 public function get(int $index): CBORObject
90 {
91 if (! $this->has($index)) {
92 throw new InvalidArgumentException('Index not found.');
93 }
94
95 return $this->data[$index];
96 }
97
98 public function set(int $index, CBORObject $object): self
99 {
100 if (! $this->has($index)) {
101 throw new InvalidArgumentException('Index not found.');
102 }
103
104 $this->data[$index] = $object;
105
106 return $this;
107 }
108
109 /**
110 * @return Iterator<int, CBORObject>
111 */
112 public function getIterator(): Iterator
113 {
114 return new ArrayIterator($this->data);
115 }
116
117 public function offsetExists($offset): bool
118 {
119 return $this->has($offset);
120 }
121
122 public function offsetGet($offset): CBORObject
123 {
124 return $this->get($offset);
125 }
126
127 public function offsetSet($offset, $value): void
128 {
129 if ($offset === null) {
130 $this->add($value);
131
132 return;
133 }
134
135 $this->set($offset, $value);
136 }
137
138 public function offsetUnset($offset): void
139 {
140 $this->remove($offset);
141 }
142 }