Completed
Push — develop ( 90d434...5a25e9 )
by Michael
02:38
created

TypeCollection   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 1 Features 0
Metric Value
wmc 8
c 3
b 1
f 0
lcom 1
cbo 2
dl 0
loc 64
ccs 18
cts 18
cp 1
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
acceptsType() 0 1 ?
A __construct() 0 8 2
A add() 0 8 2
A set() 0 8 2
A doUnexpectedValueError() 0 7 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
        }
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
        ));
62
    }
63
64
    /**
65
     * @param $value
66
     *
67
     * @return bool
68
     */
69
    abstract public function acceptsType($value);
70
}
71