EntitySet::__construct()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 1
1
<?php
2
3
namespace OpenConext\Value\Saml;
4
5
use ArrayIterator;
6
use Assert\Assertion;
7
use Countable;
8
use IteratorAggregate;
9
use OpenConext\Value\Serializable;
10
11
final class EntitySet implements Countable, IteratorAggregate, Serializable
12
{
13
    /**
14
     * @var Entity[]
15
     */
16
    private $entities = array();
17
18
    /**
19
     * @param Entity[] $entities
20
     */
21
    public function __construct(array $entities = array())
22
    {
23
        Assertion::allIsInstanceOf($entities, '\OpenConext\Value\Saml\Entity');
24
25
        foreach ($entities as $entity) {
26
            if ($this->contains($entity)) {
27
                continue;
28
            }
29
30
            $this->entities[] = $entity;
31
        }
32
    }
33
34
    /**
35
     * @param Entity $entity The entity to search for.
36
     * @return boolean 'true' if the collection contains the element, 'false' otherwise.
37
     */
38
    public function contains(Entity $entity)
39
    {
40
        foreach ($this->entities as $existingEntity) {
41
            if ($entity->equals($existingEntity)) {
42
                return true;
43
            }
44
        }
45
46
        return false;
47
    }
48
49
    /**
50
     * @param EntitySet $other
51
     * @return bool
52
     */
53
    public function equals(EntitySet $other)
54
    {
55
        if (count($this->entities) !== count($other->entities)) {
56
            return false;
57
        }
58
59
        foreach ($this->entities as $entity) {
60
            if (!$other->contains($entity)) {
61
                return false;
62
            }
63
        }
64
65
        return true;
66
    }
67
68
    public function getIterator()
69
    {
70
        return new ArrayIterator($this->entities);
71
    }
72
73
    public function count()
74
    {
75
        return count($this->entities);
76
    }
77
78
    public static function deserialize($data)
79
    {
80
        Assertion::isArray($data);
81
82
        $entities = array_map(function ($entity) {
83
            return Entity::deserialize($entity);
84
        }, $data);
85
86
        return new self($entities);
87
    }
88
89
    public function serialize()
90
    {
91
        return array_map(function (Entity $entity) {
92
            return $entity->serialize();
93
        }, $this->entities);
94
    }
95
96
    public function __toString()
97
    {
98
        return sprintf('EntitySet["%s"]', implode('", "', $this->entities));
99
    }
100
}
101