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
|
|
|
* @template T |
18
|
|
|
* |
19
|
|
|
* @extends ArrayView<T> |
20
|
|
|
*/ |
21
|
|
|
class ArrayIndexListView extends ArrayView |
22
|
|
|
{ |
23
|
|
|
/** |
24
|
|
|
* @var array<int> The indexes array specifying the indexes of elements in the source array to include in the view. |
25
|
|
|
*/ |
26
|
|
|
protected array $indexes; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Constructs a new ArrayIndexListView instance with the specified source array or ArrayView and indexes array. |
30
|
|
|
* |
31
|
|
|
* @param array<T>|ArrayViewInterface<T> $source The source array or ArrayView to create a view from. |
32
|
|
|
* @param array<int> $indexes The indexes array specifying the indexes of elements in the source array. |
33
|
|
|
* @param bool|null $readonly Optional flag to indicate whether the view should be readonly. |
34
|
|
|
* |
35
|
|
|
* @throws ValueError if the array is not sequential. |
36
|
|
|
* @throws ReadonlyError if the source is readonly and trying to create a non-readonly view. |
37
|
|
|
*/ |
38
|
|
|
public function __construct(&$source, array $indexes, ?bool $readonly = null) |
39
|
|
|
{ |
40
|
|
|
parent::__construct($source, $readonly); |
41
|
|
|
$this->indexes = $indexes; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* {@inheritDoc} |
46
|
|
|
*/ |
47
|
|
|
public function toArray(): array |
48
|
|
|
{ |
49
|
|
|
/** @var Array<T> */ |
50
|
|
|
return array_map(fn(int $index) => $this[$index], array_keys($this->indexes)); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* {@inheritDoc} |
55
|
|
|
*/ |
56
|
|
|
public function count(): int |
57
|
|
|
{ |
58
|
|
|
return \count($this->indexes); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* {@inheritDoc} |
63
|
|
|
*/ |
64
|
|
|
protected function convertIndex(int $i): int |
65
|
|
|
{ |
66
|
|
|
return Util::normalizeIndex( |
67
|
|
|
$this->indexes[Util::normalizeIndex($i, \count($this->indexes))], |
68
|
|
|
$this->getParentSize() |
69
|
|
|
); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|