Skip to content

Commit

Permalink
Some indexes are out of range error added.
Browse files Browse the repository at this point in the history
  • Loading branch information
Smoren committed Mar 12, 2024
1 parent fc0f174 commit 646920a
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/Selectors/IndexListSelector.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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());
}

Expand Down
46 changes: 46 additions & 0 deletions tests/unit/ArrayView/ErrorsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 [
Expand Down Expand Up @@ -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 [
Expand Down

0 comments on commit 646920a

Please sign in to comment.