diff --git a/src/Selectors/IndexListSelector.php b/src/Selectors/IndexListSelector.php index 360ad14..da6d40c 100644 --- a/src/Selectors/IndexListSelector.php +++ b/src/Selectors/IndexListSelector.php @@ -4,6 +4,7 @@ namespace Smoren\ArrayView\Selectors; +use Smoren\ArrayView\Exceptions\IndexError; use Smoren\ArrayView\Interfaces\ArrayViewInterface; use Smoren\ArrayView\Interfaces\IndexListSelectorInterface; use Smoren\ArrayView\Views\ArrayIndexListView; @@ -42,6 +43,10 @@ public function __construct($value) */ public function select(ArrayViewInterface $source, ?bool $readonly = null): ArrayIndexListView { + if (!$this->compatibleWith($source)) { + throw new IndexError('Some indexes are out of range.'); + } + return new ArrayIndexListView($source, $this->value, $readonly ?? $source->isReadonly()); } diff --git a/tests/unit/ArrayView/ErrorsTest.php b/tests/unit/ArrayView/ErrorsTest.php index 593e956..0e954cd 100644 --- a/tests/unit/ArrayView/ErrorsTest.php +++ b/tests/unit/ArrayView/ErrorsTest.php @@ -210,6 +210,33 @@ public function testNonSequentialError(callable $arrayGetter) ArrayView::toView($nonSequentialArray); } + /** + * @dataProvider dataProviderForBadIndexList + */ + public function testReadBadIndexList(array $source, array $indexes) + { + $view = ArrayView::toView($source); + $this->expectException(IndexError::class); + $this->expectExceptionMessage('Some indexes are out of range.'); + $_ = $view[new IndexListSelector($indexes)]; + } + + /** + * @dataProvider dataProviderForBadIndexList + */ + public function testWriteBadIndexList(array $source, array $indexes) + { + $initialSource = [...$source]; + $view = ArrayView::toView($source); + + try { + $view[new IndexListSelector($indexes)] = $indexes; + } catch (IndexError $e) { + $this->assertSame($initialSource, [...$view]); + $this->assertSame('Some indexes are out of range.', $e->getMessage()); + } + } + public function dataProviderForOutOfRangeIndexes(): array { return [ @@ -379,6 +406,25 @@ public function dataProviderForUnsetError(): array ]; } + public function dataProviderForBadIndexList(): array + { + return [ + [[1], [0, 1]], + [[1], [1, -1, -2]], + [[1], [0, 1, 0, -1, -2]], + [[1], [1, -1]], + [[1], [0, 0, -2]], + [[1, 2], [2]], + [[1, 2], [1, 2]], + [[1, 2], [0, 1, 2]], + [[1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 3, 5, -10]], + [[1, 2, 3, 4, 5, 6, 7, 8, 9], [9, 5, 3, 1]], + [[1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 10, 9, 7]], + [[1, 2, 3, 4, 5, 6, 7, 8, 9], [-10, 1, 7, 10]], + [[1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 1, 50, 5, 3]], + ]; + } + public function dataProviderForNonSequentialError(): array { return [