Completed
Push — master ( 7e748b...ca1854 )
by Karsten
02:03
created

EmitterImpl::emit()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 15
ccs 7
cts 7
cp 1
rs 9.4285
cc 3
eloc 7
nc 3
nop 1
crap 3
1
<?php
2
/**
3
 * File was created 19.03.2015 08:39
4
 *
5
 * @author Karsten J. Gerber <[email protected]>
6
 */
7
8
namespace PeekAndPoke\Component\Emitter;
9
10
use PeekAndPoke\Component\Psi\UnaryFunction;
11
12
/**
13
 * Emitter
14
 *
15
 * @author Karsten J. Gerber <[email protected]>
16
 */
17
class EmitterImpl implements Emitter
18
{
19
    /** @var bool */
20
    private $enabled = true;
21
22
    /** @var \SplObjectStorage[] */
23
    private $bindings = [];
24
25
    /**
26
     * @param bool $enabled
27
     */
28 1
    public function enable($enabled = true)
29
    {
30 1
        $this->enabled = $enabled;
31 1
    }
32
33
    /**
34
     * {@inheritdoc}
35
     */
36 5
    public function bind($eventName, $handler)
37
    {
38 5
        if (! self::isListener($handler)) {
39 1
            throw new \LogicException('Invalid listener');
40
        }
41
42 4
        if (false === array_key_exists($eventName, $this->bindings)) {
43 4
            $this->bindings[$eventName] = new \SplObjectStorage();
44
        }
45
46 4
        $listeners = $this->bindings[$eventName];
47
48 4
        if (! $listeners->offsetExists($handler)) {
49 4
            $listeners->offsetSet($handler);
50
        }
51
52 4
        return $this;
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58 4
    public function emit(Event $event)
59
    {
60 4
        if ($this->enabled === false) {
61 1
            return $this;
62
        }
63
64
        /** @var callable[] $listeners */
65 3
        $listeners = $this->bindings[$event->getEventName()] ?? [];
66
67 3
        foreach ($listeners as $listener) {
68 3
            $listener($event);
69
        }
70
71 3
        return $this;
72
    }
73
74
    /**
75
     * @param Listener|UnaryFunction|callable $listener
76
     *
77
     * @return bool
78
     */
79 5
    public static function isListener($listener)
80
    {
81 5
        return $listener instanceof \Closure ||
82 2
               $listener instanceof Listener ||
83 5
               \is_callable($listener);
84
    }
85
}
86