Completed
Pull Request — develop (#38)
by A.
02:33
created

ContactPersonList::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 6
rs 9.4286
cc 2
eloc 3
nc 2
nop 1
1
<?php
2
3
/**
4
 * Copyright 2015 SURFnet B.V.
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 *     http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18
19
namespace OpenConext\Profile\Value;
20
21
use ArrayIterator;
22
use Countable;
23
use IteratorAggregate;
24
use OpenConext\Profile\Exception\OutOfBoundsException;
25
use OpenConext\Profile\Exception\OutOfRangeException;
26
27
final class ContactPersonList implements IteratorAggregate, Countable
28
{
29
    /**
30
     * @var ContactPerson[]
31
     */
32
    private $contactPersons;
33
34
    public function __construct(array $contactPersons)
35
    {
36
        foreach ($contactPersons as $contactPerson) {
37
            $this->initializeWith($contactPerson);
38
        }
39
    }
40
41
    /**
42
     * @param ContactPerson $contactPerson
43
     */
44
    private function initializeWith(ContactPerson $contactPerson)
45
    {
46
        $this->contactPersons[] = $contactPerson;
47
    }
48
49
    /**
50
     * @param callable $predicate
51
     * @return ContactPersonList
52
     */
53
    public function filter(callable $predicate)
54
    {
55
        return new ContactPersonList(
56
            array_filter(
57
                $this->contactPersons,
58
                function (ContactPerson $contactPerson) use ($predicate) {
59
                    return $predicate($contactPerson);
60
                }
61
            )
62
        );
63
    }
64
65
    /**
66
     * @return ContactPerson
67
     */
68
    public function first()
69
    {
70
        if (!isset($this->contactPersons[0])) {
71
            throw new OutOfRangeException('Cannot get the first Contact Person of an empty Contact Person List');
72
        }
73
74
        return $this->contactPersons[0];
75
    }
76
77
    public function getIterator()
78
    {
79
        return new ArrayIterator($this->contactPersons);
80
    }
81
82
    public function count()
83
    {
84
        return count($this->contactPersons);
85
    }
86
87
    public function __toString()
88
    {
89
        return implode(', ', $this->contactPersons);
90
    }
91
}
92