Skip to content

Commit 2523420

Browse files
committed
errors test in progress
1 parent 6260a8b commit 2523420

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

src/Views/ArrayView.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -268,7 +268,11 @@ public function offsetSet($offset, $value): void
268268
throw new ReadonlyError("Cannot modify a readonly view.");
269269
}
270270

271-
if (\is_numeric($offset) && $this->numericOffsetExists($offset)) {
271+
if (\is_numeric($offset)) {
272+
if (!$this->numericOffsetExists($offset)) {
273+
throw new IndexError("Index {$offset} is out of range.");
274+
}
275+
272276
// @phpstan-ignore-next-line
273277
$this->source[$this->convertIndex(\intval($offset))] = $value;
274278
return;

tests/unit/ArrayView/ErrorsTest.php

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,44 @@
22

33
namespace Smoren\ArrayView\Tests\Unit\ArrayView;
44

5+
use Smoren\ArrayView\Exceptions\IndexError;
56
use Smoren\ArrayView\Exceptions\ValueError;
67
use Smoren\ArrayView\Views\ArrayView;
78

89
class ErrorsTest extends \Codeception\Test\Unit
910
{
11+
/**
12+
* @dataProvider dataProviderForOutOfRangeIndexes
13+
*/
14+
public function testReadIndexError(array $source, array $indexes)
15+
{
16+
$view = ArrayView::toView($source);
17+
foreach ($indexes as $index) {
18+
try {
19+
$_ = $view[$index];
20+
$this->fail();
21+
} catch (IndexError $e) {
22+
$this->assertSame("Index {$index} is out of range.", $e->getMessage());
23+
}
24+
}
25+
}
26+
27+
/**
28+
* @dataProvider dataProviderForOutOfRangeIndexes
29+
*/
30+
public function testWriteIndexError(array $source, array $indexes)
31+
{
32+
$view = ArrayView::toView($source);
33+
foreach ($indexes as $index) {
34+
try {
35+
$view[$index] = 1;
36+
$this->fail();
37+
} catch (IndexError $e) {
38+
$this->assertSame("Index {$index} is out of range.", $e->getMessage());
39+
}
40+
}
41+
}
42+
1043
/**
1144
* @dataProvider dataProviderForNonSequentialError
1245
*/
@@ -17,6 +50,15 @@ public function testNonSequentialError(callable $arrayGetter)
1750
ArrayView::toView($nonSequentialArray);
1851
}
1952

53+
public function dataProviderForOutOfRangeIndexes(): array
54+
{
55+
return [
56+
[[], [-2, -1, 0, 1]],
57+
[[1], [-3, -2, 1, 2]],
58+
[[1, 2, 3], [-100, -5, 4, 100]],
59+
];
60+
}
61+
2062
public function dataProviderForNonSequentialError(): array
2163
{
2264
return [

0 commit comments

Comments
 (0)