Passed
Push — master ( 9fff06...1ba6fb )
by Smoren
02:33 queued 16s
created

ArrayMaskView::__construct()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 8
c 1
b 0
f 0
dl 0
loc 13
rs 10
cc 3
nc 2
nop 3
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\SizeError;
9
use Smoren\ArrayView\Exceptions\ValueError;
10
use Smoren\ArrayView\Interfaces\ArrayViewInterface;
11
12
/**
13
 * Class representing a mask-based view of an array or another ArrayView for accessing elements based on a boolean mask.
14
 *
15
 * Each element in the view is included or excluded based on the specified boolean mask.
16
 *
17
 * @template T
18
 *
19
 * @extends ArrayIndexListView<T>
20
 */
21
class ArrayMaskView extends ArrayIndexListView
22
{
23
    /**
24
     * @var array<bool> The boolean mask specifying whether each element in the source array
25
     * should be included in the view (true) or excluded (false).
26
     */
27
    protected array $mask;
28
29
    /**
30
     * Constructs a new ArrayMaskView instance with the specified source array or ArrayView and boolean mask.
31
     *
32
     * @param array<T>|ArrayViewInterface<T> $source The source array or ArrayView to create a view from.
33
     * @param array<bool> $mask Options for configuring the view.
34
     * @param bool|null $readonly The boolean mask for including or excluding elements from the source array.
35
     *
36
     * @throws ValueError if the array is not sequential.
37
     * @throws ReadonlyError if the source is readonly and trying to create a non-readonly view.
38
     */
39
    public function __construct(&$source, array $mask, ?bool $readonly = null)
40
    {
41
        [$sourceSize, $maskSize] = [\count($source), \count($mask)];
42
        if ($sourceSize !== $maskSize) {
43
            throw new SizeError("Mask size not equal to source length ({$maskSize} != {$sourceSize}).");
44
        }
45
46
        $indexes = array_filter(
47
            array_map(fn (bool $v, int $i) => $v ? $i : null, $mask, array_keys($mask)),
48
            fn ($v) => $v !== null
49
        );
50
        parent::__construct($source, array_values($indexes), $readonly);
51
        $this->mask = $mask;
52
    }
53
}
54