Skip to content

Commit

Permalink
Coverage 100%!
Browse files Browse the repository at this point in the history
  • Loading branch information
Smoren committed Mar 12, 2024
1 parent 2ff6647 commit 20924c8
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 3 deletions.
7 changes: 4 additions & 3 deletions src/Util.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,14 @@ public static function normalizeIndex(int $index, int $containerLength, bool $th
* Check if an array is sequential (indexed from 0 to n-1).
*
* @param array<mixed> $source The array to check for sequential indexing.
* @param bool $forceCustomImplementation Flag only for tests.
*
* @return bool Returns true if the array has sequential indexing, false otherwise.
*/
public static function isArraySequential(array $source): bool
public static function isArraySequential(array $source, bool $forceCustomImplementation = false): bool
{
if (!function_exists('array_is_list')) {
return array_keys($source) === range(0, count($source) - 1);
if (!function_exists('array_is_list') || $forceCustomImplementation) {
return \count($source) === 0 || array_keys($source) === range(0, count($source) - 1);
}
return array_is_list($source);
}
Expand Down
58 changes: 58 additions & 0 deletions tests/unit/Utils/IsArraySequentialTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php

declare(strict_types=1);

namespace Smoren\ArrayView\Tests\Unit\Utils;

use Smoren\ArrayView\Exceptions\IndexError;
use Smoren\ArrayView\Util;

class IsArraySequentialTest extends \Codeception\Test\Unit
{
/**
* @dataProvider dataProviderForIsSequentialTrue
*/
public function testIsSequentialTrue(array $source)
{
$this->assertTrue(Util::isArraySequential($source));
$this->assertTrue(Util::isArraySequential($source, true));
}

/**
* @dataProvider dataProviderForIsSequentialFalse
*/
public function testIsSequentialFalse(array $source)
{
$this->assertFalse(Util::isArraySequential($source));
$this->assertFalse(Util::isArraySequential($source, true));
}

public function dataProviderForIsSequentialTrue(): array
{
return [
[[]],
[['']],
[[null]],
[[1]],
[['1']],
[['test']],
[[1, 2, 3]],
[[0 => 1, 1 => 2, 2 => 3]],
[['0' => 1, 1 => 2, 2 => 3]],
[['0' => 1, '1' => 2, '2' => 3]],
[[10, '20', 30.5]],
];
}

public function dataProviderForIsSequentialFalse(): array
{
return [
[['a' => 1]],
[[1 => 1]],
[[0 => 1, 1 => 2, 3 => 3]],
[[0 => 1, 1 => 2, 2 => 3, 'test' => 123]],
[[1 => 2, 2 => 3]],
[[1 => 2, 3 => 3, 'a' => 1000]],
];
}
}

0 comments on commit 20924c8

Please sign in to comment.