ArraySliceView::count()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Smoren\ArrayView\Views;
6
7
use Smoren\ArrayView\Exceptions\ReadonlyError;
8
use Smoren\ArrayView\Exceptions\ValueError;
9
use Smoren\ArrayView\Interfaces\ArrayViewInterface;
10
use Smoren\ArrayView\Structs\NormalizedSlice;
11
use Smoren\ArrayView\Structs\Slice;
12
13
/**
14
 * Class representing a slice-based view of an array or another ArrayView
15
 * for accessing elements within a specified slice range.
16
 *
17
 * ```php
18
 * $source = [1, 2, 3, 4, 5];
19
 * $view = ArrayView::toView($source)->subview(new SliceSelector('::2'));
20
 * $view->toArray(); // [1, 3, 5]
21
 * ```
22
 *
23
 * @template T Type of array source elements.
24
 *
25
 * @extends ArrayView<T>
26
 */
27
class ArraySliceView extends ArrayView
28
{
29
    /**
30
     * @var NormalizedSlice The normalized slice range defining the view within the source array or ArrayView.
31
     */
32
    protected NormalizedSlice $slice;
33
34
    /**
35
     * Constructs a new ArraySliceView instance with the specified source array or ArrayView and slice range.
36
     *
37
     * @param Array<T>|ArrayViewInterface<T> $source The source array or ArrayView to create a view from.
38
     * @param Slice $slice The slice range specifying the subset of elements to include in the view.
39
     * @param bool|null $readonly Optional flag to indicate whether the view should be readonly.
40
     *
41
     * @throws ValueError if the array is not sequential.
42
     * @throws ReadonlyError if the source is readonly and trying to create a non-readonly view.
43
     */
44
    public function __construct(&$source, Slice $slice, ?bool $readonly = null)
45
    {
46
        parent::__construct($source, $readonly);
47
        $this->slice = $slice->normalize(\count($source));
48
    }
49
50
    /**
51
     * {@inheritDoc}
52
     */
53
    public function count(): int
54
    {
55
        return \count($this->slice);
56
    }
57
58
    /**
59
     * {@inheritDoc}
60
     */
61
    protected function convertIndex(int $i): int
62
    {
63
        return $this->slice->convertIndex($i);
64
    }
65
}
66