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

TypeCollection::acceptsType()

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 1
ccs 0
cts 0
cp 0
nc 1
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