Issues (12)

src/Set/SetTrait.php (2 issues)

Severity
1
<?php
2
namespace SpareParts\Enum\Set;
3
4
use SpareParts\Enum\Enum;
5
use SpareParts\Enum\Exception\EnumSetMustContainEnumsException;
6
use SpareParts\Enum\Exception\InvalidEnumClassException;
7
8
trait SetTrait
9
{
10
    /**
11
     * @var Enum[]
12
     */
13
    protected $set = [];
14
15
    /**
16
     * @var string
17
     */
18
    protected $enumClass;
19
20
    /**
21
     * @param string $enumClass
22
     * @param Enum[] $set
23
     */
24 42
    public function __construct(string $enumClass, $set = [])
25
    {
26
        // if enum class was sent, we must make sure it is valid
27 42
        $this->setEnumClass($enumClass);
28
29 40
        if (!is_array($set)) {
0 ignored issues
show
The condition is_array($set) is always true.
Loading history...
30 2
            throw new EnumSetMustContainEnumsException(sprintf("Enum set must be initialized with array of enums."));
31
        }
32 38
        foreach ($set as $enum) {
33 36
            if (!($enum instanceof $this->enumClass)) {
34 6
                throw new EnumSetMustContainEnumsException(sprintf("Expected %s, got %s", $this->enumClass, get_class($enum)));
35
            }
36 32
            $this->set[(string) $enum] = $enum;
37
        }
38 32
    }
39
40 17
    public function getIterator(): \ArrayIterator
41
    {
42 17
        return new \ArrayIterator(array_values($this->set));
43
    }
44
45 14
    public function count(): int
46
    {
47 14
        return count($this->set);
48
    }
49
50 16
    public function contains(Enum $value): bool
51
    {
52 16
        if (in_array($value, $this->set)) {
53 16
            return true;
54
        }
55 10
        return false;
56
    }
57
58 42
    protected function setEnumClass(string $enumClass): void
59
    {
60 42
        if (!is_null($enumClass) && !is_subclass_of($enumClass, Enum::class)) {
0 ignored issues
show
The condition is_null($enumClass) is always false.
Loading history...
61 2
            throw new InvalidEnumClassException("Class ${enumClass} does not implement Enum (as it should). Maybe you forgot to specify correct enum class in constructor?");
62
        }
63
        $this->enumClass = $enumClass;
64
    }
65
}
66