AbstractTypedArray::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 4
dl 0
loc 6
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Diacdg\TypedArray;
5
6
abstract class AbstractTypedArray extends \ArrayObject
7
{
8
    protected $valueType;
9
10 18
    public function __construct(string $valueType, array $array = [], int $flags = 0, string $iteratorClass = "ArrayIterator") {
11 18
        $this->valueType = $valueType;
12
13 18
        $this->checkAllElements($array);
14
15 18
        parent::__construct($array, $flags, $iteratorClass);
16 18
    }
17
18 13
    public function offsetSet($offset, $value)
19
    {
20 13
        $this->checkType($value);
21
22 11
        $this->checkOffset($offset);
23
24 9
        parent::offsetSet($offset, $value);
25 9
    }
26
27 1
    public function exchangeArray($array)
28
    {
29 1
        $this->checkAllElements($array);
30
31 1
        parent::exchangeArray($array);
32 1
    }
33
34 18
    protected function checkType($value): void
35
    {
36 18
        if (gettype($value) !== strtolower($this->valueType) && !$value instanceof $this->valueType && !($this->valueType === 'callable' && is_callable($value))) {
37 2
            throw new \InvalidArgumentException('Value must be of type ' . $this->valueType . " but value of type " . gettype($value) . " given.");
38
        }
39 16
    }
40
41
    abstract protected function checkOffset($offset): void;
42
43 18
    private function checkAllElements(array $array): void
44
    {
45 18
        array_walk($array, function ($value, $offset) {
46 5
            $this->checkOffset($offset);
47 5
            $this->checkType($value);
48 18
        });
49
    }
50
}