Completed
Push — master ( 2b894b...836484 )
by Gaetano
05:34
created

AbstractCollection::isValidElement()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 2
1
<?php
2
3
namespace Kaliop\eZMigrationBundle\API\Collection;
4
5
/**
6
 * Implements a 'typed array' structure
7
 */
8
class AbstractCollection extends \ArrayObject
9
{
10
    protected $allowedClass;
11
12
    /**
13
     * AbstractCollection constructor.
14
     * @param array $input
15
     * @param int $flags
16
     * @param string $iterator_class
17
     */
18
    public function __construct($input = array(), $flags = 0, $iterator_class = "ArrayIterator")
19
    {
20
        foreach ($input as $value) {
21
            if (!$this->isValidElement($value)) {
22
                $this->throwInvalid($value);
23
            }
24
        }
25
26
        parent::__construct($input, $flags, $iterator_class);
27
    }
28
29
    /**
30
     * @param mixed $value
31
     */
32
    public function append($value)
33
    {
34
        if (!$this->isValidElement($value)) {
35
            $this->throwInvalid($value);
36
        }
37
38
        parent::append($value);
39
    }
40
41
    /**
42
     * @param mixed $input
43
     * @return array the old array
44
     */
45
    public function exchangeArray($input)
46
    {
47
        foreach ($input as $value) {
48
            if (!$this->isValidElement($value)) {
49
                $this->throwInvalid($value);
50
            }
51
        }
52
53
        return parent::exchangeArray($input);
54
    }
55
56
    /**
57
     * @param mixed $index
58
     * @param mixed $value
59
     */
60
    public function offsetSet($index, $value)
61
    {
62
        if (!$this->isValidElement($value)) {
63
            $this->throwInvalid($value);
64
        }
65
66
        parent::offsetSet($index, $value);
67
    }
68
69
    protected function isValidElement($value)
70
    {
71
        return is_a($value, $this->allowedClass);
72
    }
73
74
    protected function throwInvalid($value)
75
    {
76
        throw new \InvalidArgumentException("Can not add element of type '" . (is_object($value) ? get_class($value) : gettype($value)) . "' to Collection of type '" . get_class($this) . "'");
77
    }
78
79
    /**
80
     * Allow the class to be serialized to php using var_export
81
     * @param array $data
82
     * @return static
83
     */
84
    public static function __set_state(array $data)
85
    {
86
        return new static($data);
87
    }
88
}
89