Completed
Push — master ( bcc930...059858 )
by Guillermo
11s
created

customInvalidEntityIdException()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Atrapalo\PHPTools\Collection;
4
5
/**
6
 * Class UniqueEntityCollection
7
 * @package Collection
8
 */
9
abstract class UniqueEntityCollection extends EntityCollection
10
{
11
    /**
12
     * @param $entity
13
     * @return string
14
     */
15
    abstract public function entityUniqueId($entity): string;
16
17
    /**
18
     * @param $entity
19
     * @throws \Exception
20
     */
21 6
    public function add($entity)
22
    {
23 6
        if (!$this->isValid($entity)) {
24 1
            throw self::customInvalidEntityException();
25 5
        } elseif ($this->exist($entity)) {
26 2
            throw self::customDuplicateEntityException();
27
        }
28
29 4
        $this->set($this->uniqueId($entity), $entity);
30 4
    }
31
32
    /**
33
     * @param $entity
34
     * @return bool
35
     */
36 5
    public function exist($entity): bool
37
    {
38 5
        if (in_array($this->uniqueId($entity), $this->keys())) {
39 3
            return true;
40
        }
41
42 4
        return false;
43
    }
44
45
    /**
46
     * @param $entity
47
     * @return string
48
     * @throws \Exception
49
     */
50 5
    private function uniqueId($entity): string
51
    {
52 5
        $uniqueId = $this->entityUniqueId($entity);
53 5
        if (empty($uniqueId)) {
54 1
            throw static::customInvalidEntityIdException();
55
        }
56
57 4
        return $uniqueId;
58
    }
59
60
    /**
61
     * @return \Exception
62
     */
63 2
    public static function customDuplicateEntityException(): \Exception
64
    {
65 2
        return new \InvalidArgumentException("Entity already exists in collection");
66
    }
67
68
69
    /**
70
     * @return \Exception
71
     */
72 1
    public static function customInvalidEntityIdException(): \Exception
73
    {
74 1
        return new \InvalidArgumentException('Entity unique id can not be empty');
75
    }
76
}
77