Collection::setItemType()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
/*
4
 * This file is part of the Tidal/WampWatch package.
5
 *   (c) 2016 Timo Michna <timomichna/yahoo.de>
6
 *
7
 *  For the full copyright and license information, please view the LICENSE
8
 *  file that was distributed with this source code.
9
 *
10
 */
11
12
namespace Tidal\WampWatch\Model\Property;
13
14
use ArrayObject;
15
use InvalidArgumentException;
16
use Generator;
17
use Tidal\WampWatch\Model\Contract\Property\CollectionInterface;
18
19
class Collection extends ArrayObject implements CollectionInterface
20
{
21
    private $itemType;
22
23
    private $validationCallback;
24
25
    public function append($value)
26
    {
27
        $this->validate($value);
28
29
        parent::append($value);
30
    }
31
32
    private function validate($item)
33
    {
34
        $this->validateItemType($item);
35
        $this->validateCallback($item);
36
    }
37
38
    private function validateItemType($item)
39
    {
40
        if (isset($this->itemType) && $type = gettype($item) !== $this->itemType) {
41
            throw new InvalidArgumentException("Expected item of type '{$this->itemType}'. -> '$type' given.");
42
        }
43
    }
44
45
    private function validateCallback($item)
46
    {
47
        if (!isset($this->validationCallback)) {
48
            return;
49
        }
50
51
        $callback = $this->validationCallback;
52
53
        if (!$callback($item)) {
54
            throw new InvalidArgumentException('Item failed validation.');
55
        }
56
    }
57
58
    public function setItemType($type)
59
    {
60
        $this->itemType = (string) $type;
61
    }
62
63
    public function has($key)
64
    {
65
        return $this->offsetExists($key);
66
    }
67
68
    public function set($key, $value)
69
    {
70
        $this->offsetSet($key, $value);
71
    }
72
73
    public function offsetSet($index, $newValue)
74
    {
75
        $this->validate($newValue);
76
77
        parent::offsetSet($index, $newValue);
78
    }
79
80
    public function get($key)
81
    {
82
        return $this->offsetGet($key);
83
    }
84
85
    /**
86
     * @return Generator
87
     */
88
    public function getGenerator()
89
    {
90
        foreach ($this as $key => $value) {
91
            yield $key => $value;
92
        }
93
    }
94
95
    /**
96
     * Registers a callback function to validate new Collection entries.
97
     * The callback function must return a boolean value.
98
     * When the callback returns false the new item will not be added to the collection.
99
     *
100
     * @param callable $callback
101
     */
102
    public function setValidationCallback(callable $callback)
103
    {
104
        $this->validationCallback = $callback;
105
    }
106
}
107