Util::isArraySequential()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 6
rs 10
cc 4
nc 3
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Smoren\ArrayView;
6
7
use Smoren\ArrayView\Exceptions\IndexError;
8
9
/**
10
 * Utility class containing static helper methods for array manipulation and index normalization.
11
 *
12
 * @internal
13
 */
14
class Util
15
{
16
    /**
17
     * Normalize a given index within the range of the container length.
18
     *
19
     * @param int $index The index to normalize.
20
     * @param int $containerLength The length of the container.
21
     * @param bool $throwError Flag to indicate if an IndexError should be thrown for out-of-range index.
22
     *
23
     * @return int The normalized index within the valid range of the container.
24
     *
25
     * @throws IndexError if the index is out of range and $throwError is true.
26
     */
27
    public static function normalizeIndex(int $index, int $containerLength, bool $throwError = true): int
28
    {
29
        $dist = $index >= 0 ? $index : \abs($index) - 1;
30
        if ($throwError && $dist >= $containerLength) {
31
            throw new IndexError("Index {$index} is out of range.");
32
        }
33
        return $index < 0 ? $containerLength + $index : $index;
34
    }
35
36
    /**
37
     * Check if an array is sequential (indexed from 0 to n-1).
38
     *
39
     * @param array<mixed> $source The array to check for sequential indexing.
40
     * @param bool $forceCustomImplementation Flag only for tests (to test custom implementation of array_is_list).
41
     *
42
     * @return bool Returns true if the array has sequential indexing, false otherwise.
43
     */
44
    public static function isArraySequential(array $source, bool $forceCustomImplementation = false): bool
45
    {
46
        if (!\function_exists('array_is_list') || $forceCustomImplementation) {
47
            return \count($source) === 0 || \array_keys($source) === \range(0, \count($source) - 1);
48
        }
49
        return \array_is_list($source);
50
    }
51
}
52