Completed
Branch 0.4-dev (54e67b)
by Evgenij
02:52
created

EventMultiHandler::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
ccs 6
cts 6
cp 1
rs 9.4285
cc 2
eloc 4
nc 2
nop 1
crap 2
1
<?php
2
/**
3
 * Async sockets
4
 *
5
 * @copyright Copyright (c) 2015-2016, Efimov Evgenij <[email protected]>
6
 *
7
 * This source file is subject to the MIT license that is bundled
8
 * with this source code in the file LICENSE.
9
 */
10
namespace AsyncSockets\RequestExecutor;
11
12
use AsyncSockets\Event\Event;
13
14
/**
15
 * Class EventMultiHandler
16
 */
17
class EventMultiHandler implements EventHandlerInterface
18
{
19
    /**
20
     * List of handlers
21
     *
22
     * @var EventHandlerInterface[]
23
     */
24
    private $handlers = [];
25
26
    /**
27
     * EventMultiHandler constructor.
28
     *
29
     * @param EventHandlerInterface[] $handlers List of handlers
30
     */
31 4
    public function __construct(array $handlers = [])
32
    {
33 4
        $this->handlers = [];
34 4
        foreach ($handlers as $handler) {
35 1
            $this->addHandler($handler);
36 4
        }
37 4
    }
38
39
    /** {@inheritdoc} */
40 4
    public function invokeEvent(Event $event)
41
    {
42 4
        foreach ($this->handlers as $handler) {
43 3
            $handler->invokeEvent($event);
44 4
        }
45 4
    }
46
47
    /**
48
     * Add handler to list
49
     *
50
     * @param EventHandlerInterface $handler Handler to add
51
     *
52
     * @return void
53
     */
54 4
    public function addHandler(EventHandlerInterface $handler)
55
    {
56 4
        $key = $this->getHandlerKey($handler);
57 4
        $this->handlers[$key] = $handler;
58 4
    }
59
60
    /**
61
     * Remove handler from list
62
     *
63
     * @param EventHandlerInterface $handler Handler to remove
64
     *
65
     * @return void
66
     */
67 1
    public function removeHandler(EventHandlerInterface $handler)
68
    {
69 1
        $key = $this->getHandlerKey($handler);
70 1
        if (isset($this->handlers[$key])) {
71 1
            unset($this->handlers[$key]);
72 1
        }
73 1
    }
74
75
    /**
76
     * Return key for given handler
77
     *
78
     * @param EventHandlerInterface $handler Handler to get key for
79
     *
80
     * @return string
81
     */
82 4
    private function getHandlerKey(EventHandlerInterface $handler)
83
    {
84 4
        return spl_object_hash($handler);
85
    }
86
}
87