Skip to content

Commit 14d5cb4

Browse files
author
Thorsten Suckow-Homberg
committed
refactor: extract offsetSet() implementation into separate methods
1 parent 32cf3e7 commit 14d5cb4

File tree

2 files changed

+41
-16
lines changed

2 files changed

+41
-16
lines changed

src/Core/AbstractList.php

Lines changed: 40 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -142,24 +142,37 @@ public function peek(): mixed
142142
}
143143

144144

145-
// -------------------------
146-
// ArrayAccess Interface
147-
// -------------------------
148-
149145
/**
150-
* @inheritdoc
146+
* @param mixed $offset
147+
* @param mixed $value
148+
* @return void
151149
*
152-
* @throws TypeError|OutOfBoundsException if $value is not of the type defined
153-
* with this getEntityType, or f $offset is not an int
150+
* @throws OutOfBoundsException
154151
*/
155-
public function offsetSet(mixed $offset, mixed $value): void
152+
protected function doInsert(mixed $offset, mixed $value)
156153
{
157-
if (!is_null($offset) && !is_int($offset)) { // @phpstan-ignore-line
154+
if (!is_null($offset) && !is_int($offset)) {
158155
throw new OutOfBoundsException(
159156
"expected integer key for \"offset\", " .
160-
"but got \"$offset\" (type: " . (gettype($offset)) . ")"
157+
"but got type: " . (gettype($offset))
161158
);
162159
}
160+
161+
if (is_null($offset)) {
162+
$this->data[] = $value;
163+
} else {
164+
$this->data[$offset] = $value;
165+
}
166+
}
167+
168+
/**
169+
* @param mixed $value
170+
* @return bool
171+
*
172+
* @throws TypeError
173+
*/
174+
protected function assertTypeFor(mixed $value): bool
175+
{
163176
$entityType = $this->getEntityType();
164177

165178
// instanceof has higher precedence, do
@@ -172,14 +185,26 @@ public function offsetSet(mixed $offset, mixed $value): void
172185
);
173186
}
174187

175-
if (is_null($offset)) {
176-
$this->data[] = $value;
177-
} else {
178-
$this->data[$offset] = $value;
179-
}
188+
return true;
180189
}
181190

182191

192+
// -------------------------
193+
// ArrayAccess Interface
194+
// -------------------------
195+
196+
/**
197+
* @inheritdoc
198+
*
199+
* @throws TypeError|OutOfBoundsException if $value is not of the type defined
200+
* with this getEntityType, or f $offset is not an int
201+
*/
202+
public function offsetSet(mixed $offset, mixed $value): void
203+
{
204+
$this->assertTypeFor($value);
205+
$this->doInsert($offset, $value);
206+
}
207+
183208

184209
/**
185210
* @inheritdoc

tests/Core/AbstractListTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ public function testOffsetSetWithStringAndOutOfBoundsException(): void
7272
$this->expectException(OutOfBoundsException::class);
7373

7474
$abstractList = $this->getMockForAbstractList();
75-
$abstractList["1"] = "foo";
75+
$abstractList["1"] = new stdClass();
7676
}
7777

7878

0 commit comments

Comments
 (0)