Completed
Push — master ( bb98fa...b1dd66 )
by Beñat
08:36
created

Collection::type()

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 1
c 0
b 0
f 0
nc 1
1
<?php
2
3
/*
4
 * This file is part of the Shared Kernel library.
5
 *
6
 * Copyright (c) 2016-2017 LIN3S <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace LIN3S\SharedKernel\Domain\Model\Collection;
13
14
use Doctrine\Common\Collections\ArrayCollection;
15
16
/**
17
 * @author Beñat Espiña <[email protected]>
18
 */
19
abstract class Collection extends ArrayCollection
20
{
21
    abstract protected function type();
22
23
    public function __construct(array $elements = [])
24
    {
25
        foreach ($elements as $element) {
26
            $this->validate($element);
27
        }
28
        parent::__construct($elements);
29
    }
30
31
    public function add($element)
32
    {
33
        if ($this->contains($this->validate($element))) {
34
            throw new CollectionElementAlreadyAddedException();
35
        }
36
        parent::add($element);
37
    }
38
39
    public function removeElement($element)
40
    {
41
        if (!$this->contains($element)) {
42
            throw new CollectionElementAlreadyRemovedException();
43
        }
44
        parent::removeElement($element);
45
    }
46
47
    private function validate($element)
48
    {
49
        if (is_scalar($element)
50
            || false === (is_subclass_of($element, $this->type())
51
                || (get_class($element) === $this->type())
52
            )
53
        ) {
54
            throw new CollectionElementInvalidException();
55
        }
56
57
        return $element;
58
    }
59
}
60