Completed
Push — master ( 5cb805...ed9bb8 )
by Andrew
02:53 queued 12s
created

AbstractTypedArray::verifyValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 9.4285
cc 2
eloc 3
nc 2
nop 1
crap 2
1
<?php
2
3
namespace TypedArray;
4
5
abstract class AbstractTypedArray extends \ArrayIterator
6
{
7
    /**
8
     * @var callable
9
     */
10
    private $test;
11
12
    /**
13
     * @var string
14
     */
15
    private $type;
16
17
    /**
18
     * @param callable $test The validation test to perform on new array entries
19
     * @param string $type The name of the intended type
20
     * @param array|null The source array
21
     */
22 99
    public function __construct(callable $test, $type, array $source = null)
23
    {
24 99
        $this->test = $test;
25 99
        $this->type = $type;
26
27 99
        if (null !== $source) {
28 66
            $this->verify($source);
29
30 33
            parent::__construct($source);
31 33
        } else {
32 66
            parent::__construct();
33
        }
34 66
    }
35
36 66
    public function offsetSet($index, $newval)
37
    {
38 66
        $this->verifyValue($newval);
39
40 33
        return parent::offsetSet($index, $newval);
41
    }
42
43 66
    private function verify(array $source)
44
    {
45 66
        foreach ($source as $value) {
46 66
            $this->verifyValue($value);
47 33
        }
48 33
    }
49
50 99
    private function verifyValue($value)
51
    {
52 99
        if (!call_user_func($this->test, $value)) {
53 66
            throw new \InvalidArgumentException('Expected ' . $this->type . ', got ' . gettype($value));
54
        }
55 33
    }
56
}
57