Passed
Push — master ( 433232...5adbcd )
by Viktor
03:10
created

EventCollection::addEvent()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 10
nc 3
nop 1
dl 0
loc 17
ccs 10
cts 10
cp 1
crap 4
rs 9.2
c 0
b 0
f 0
1
<?php
2
/**
3
 * @link https://github.com/Izumi-kun/yii2-longpoll
4
 * @copyright Copyright (c) 2017 Viktor Khokhryakov
5
 * @license http://opensource.org/licenses/BSD-3-Clause
6
 */
7
8
namespace izumi\longpoll;
9
10
use Yii;
11
use yii\base\BaseObject;
12
use yii\base\InvalidConfigException;
13
14
/**
15
 * Class EventCollection
16
 * @property EventInterface[] $events array of events.
17
 * @author Viktor Khokhryakov <[email protected]>
18
 */
19
class EventCollection extends BaseObject implements EventCollectionInterface
20
{
21
    /**
22
     * @var EventInterface[] array of events (key => event).
23
     */
24
    private $_events = [];
25
    /**
26
     * @var string event class name.
27
     */
28
    public $eventClass = 'izumi\longpoll\Event';
29
30
    /**
31
     * @inheritdoc
32
     */
33 22
    public function addEvent($event)
34
    {
35 22
        if (!$event instanceof EventInterface) {
36 15
            if (!is_array($event)) {
37
                $event = [
38 13
                    'class' => $this->eventClass,
39 13
                    'key' => $event,
40
                ];
41
            }
42 15
            $event = Yii::createObject($event);
43 15
            if (!$event instanceof EventInterface) {
44 1
                throw new InvalidConfigException('The event should be an instance of "\izumi\longpoll\EventInterface".');
45
            }
46
        }
47 21
        $this->_events[$event->getKey()] = $event;
48
49 21
        return $event;
50
    }
51
52
    /**
53
     * @inheritdoc
54
     */
55 22
    public function getEvents()
56
    {
57 22
        return $this->_events;
58
    }
59
60
    /**
61
     * @inheritdoc
62
     */
63 23
    public function setEvents($events)
64
    {
65 23
        $this->_events = [];
66 23
        if (!is_array($events)) {
67 7
            $events = [$events];
68
        }
69 23
        foreach ($events as $event) {
70 18
            $this->addEvent($event);
71
        }
72 22
    }
73
}
74