Completed
Pull Request — develop (#33)
by Michael
02:17
created

TypeCollection::set()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.4285
cc 2
eloc 4
nc 2
nop 2
crap 2
1
<?php
2
3
namespace Crummy\Phlack\Common\Collection;
4
5
use Crummy\Phlack\Common\Exception\UnexpectedValueException;
6
7
abstract class TypeCollection extends ArrayCollection
8
{
9
    /**
10
     * {@inheritdoc}
11
     *
12
     * @throws UnexpectedValueException
13
     */
14 61
    public function __construct(array $elements = [])
15
    {
16 61
        parent::__construct();
17
18 61
        foreach ($elements as $element) {
19 17
            $this->add($element);
20 61
        }
21 61
    }
22
23
    /**
24
     * {@inheritdoc}
25
     *
26
     * @throws UnexpectedValueException
27
     */
28 31
    public function add($value)
29
    {
30 31
        if (!$this->acceptsType($value)) {
31 2
            throw $this->doUnexpectedValueError($value);
32
        }
33
34 30
        return parent::add($value);
35
    }
36
37
    /**
38
     * {@inheritdoc}
39
     *
40
     * @throws UnexpectedValueException
41
     */
42 2
    public function set($key, $value)
43
    {
44 2
        if (!$this->acceptsType($value)) {
45 1
            throw $this->doUnexpectedValueError($value);
46
        }
47
48 1
        parent::set($key, $value);
49 1
    }
50
51
    /**
52
     * @param $element
53
     *
54
     * @return UnexpectedValueException
55
     */
56 3
    private function doUnexpectedValueError($element)
57
    {
58 3
        return new UnexpectedValueException(sprintf(
59 3
            '"%s" does not match the expected type.',
60 3
            is_object($element) ? get_class($element) : gettype($element)
61 3
        ));
62
    }
63
64
    /**
65
     * @param $value
66
     *
67
     * @return bool
68
     */
69
    abstract public function acceptsType($value);
70
}
71