TypedCollection::validateType()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 4
nc 3
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Linio\Collection;
6
7
use Doctrine\Common\Collections\ArrayCollection;
8
9
abstract class TypedCollection extends ArrayCollection
10
{
11
    /**
12
     * {@inheritdoc}
13
     */
14
    public function __construct(array $elements = [])
15
    {
16
        foreach ($elements as $value) {
17
            $this->validateType($value);
18
        }
19
20
        parent::__construct($elements);
21
    }
22
23
    /**
24
     * {@inheritdoc}
25
     */
26
    public function offsetSet($offset, $value)
27
    {
28
        $this->validateType($value);
29
        parent::offsetSet($offset, $value);
30
    }
31
32
    /**
33
     * {@inheritdoc}
34
     */
35
    public function add($value)
36
    {
37
        $this->validateType($value);
38
        parent::add($value);
39
    }
40
41
    /**
42
     * @param mixed $value
43
     *
44
     * @throws InvalidArgumentException
45
     */
46
    protected function validateType($value)
47
    {
48
        if (!$this->isValidType($value)) {
49
            $type = is_object($value) ? get_class($value) : gettype($value);
50
            throw new \InvalidArgumentException('Unsupported type: ' . $type);
51
        }
52
    }
53
54
    /**
55
     * @param mixed $value
56
     *
57
     * @return bool
58
     */
59
    abstract public function isValidType($value);
60
}
61