ArrayIndexListView::toArray()   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\Util;
11
12
/**
13
 * Class representing an index-based view of an array or another ArrayView for accessing elements at specific indexes.
14
 *
15
 * Each element in the view is based on the specified indexes.
16
 *
17
 * ```php
18
 * $source = [1, 2, 3, 4, 5];
19
 * $view = ArrayView::toView($source)->subview(new IndexListSelector([0, 2, 4]));
20
 * $view->toArray(); // [1, 3, 5]
21
 * ```
22
 *
23
 * @template T Type of array source elements.
24
 *
25
 * @extends ArrayView<T>
26
 */
27
class ArrayIndexListView extends ArrayView
28
{
29
    /**
30
     * @var array<int> The indexes array specifying the indexes of elements in the source array to include in the view.
31
     */
32
    protected array $indexes;
33
34
    /**
35
     * Constructs a new ArrayIndexListView instance with the specified source array or ArrayView and indexes array.
36
     *
37
     * @param array<T>|ArrayViewInterface<T> $source The source array or ArrayView to create a view from.
38
     * @param array<int> $indexes The indexes array specifying the indexes of elements in the source array.
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, array $indexes, ?bool $readonly = null)
45
    {
46
        parent::__construct($source, $readonly);
47
        $this->indexes = $indexes;
48
    }
49
50
    /**
51
     * {@inheritDoc}
52
     */
53
    public function toArray(): array
54
    {
55
        return array_map(fn (int $index) => $this->source[$index], $this->indexes);
56
    }
57
58
    /**
59
     * {@inheritDoc}
60
     */
61
    public function count(): int
62
    {
63
        return \count($this->indexes);
64
    }
65
66
    /**
67
     * {@inheritDoc}
68
     */
69
    protected function convertIndex(int $i): int
70
    {
71
        return Util::normalizeIndex(
72
            $this->indexes[Util::normalizeIndex($i, \count($this->indexes))],
73
            $this->getParentSize()
74
        );
75
    }
76
}
77