Passed
Branch master (24fb29)
by Peter
02:25
created

EventEmitterTrait::setEventDispatcher()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Webino™ (http://webino.sk)
4
 *
5
 * @link        https://github.com/webino/event-emitter
6
 * @copyright   Copyright (c) 2019 Webino, s.r.o. (http://webino.sk)
7
 * @author      Peter Bačinský <[email protected]>
8
 * @license     BSD-3-Clause
9
 */
10
11
namespace Webino;
12
13
/**
14
 * Trait EventEmitterTrait
15
 * @package event-emitter
16
 */
17
trait EventEmitterTrait
18
{
19
    /**
20
     * @var EventDispatcherInterface|null
21
     */
22
    protected $eventDispatcher;
23
24
    /**
25
     * Returns event dispatcher.
26
     *
27
     * @return EventDispatcherInterface
28
     */
29
    public function getEventDispatcher(): EventDispatcherInterface
30
    {
31
        if (!$this->eventDispatcher) {
32
            $this->eventDispatcher = new EventDispatcher;
33
        }
34
        return $this->eventDispatcher;
35
    }
36
37
    /**
38
     * Inject event dispatcher.
39
     *
40
     * @param EventDispatcherInterface $dispatcher
41
     */
42
    public function setEventDispatcher(EventDispatcherInterface $dispatcher): void
43
    {
44
        $this->eventDispatcher = $dispatcher;
45
    }
46
47
    /**
48
     * Invoke handlers.
49
     *
50
     * @param string|EventInterface $event Event name or object
51
     * @param callable|null $until Invoke handlers until callback return value evaluate to true
52
     * @return EventInterface Event object
53
     * @throws InvalidEventException Invalid event
54
     */
55
    public function emit($event, callable $until = null): EventInterface
56
    {
57
        return $this->getEventDispatcher()->emit($event, $until);
58
    }
59
60
    /**
61
     * Set event handler.
62
     *
63
     * @param string|EventInterface|EventHandlerInterface $event Event name, object or event handler
64
     * @param callable|null $callback Event handler
65
     * @param int $priority Handler invocation priority
66
     * @return void
67
     */
68
    public function on($event, $callback = null, int $priority = 0)
69
    {
70
        $this->getEventDispatcher()->on($event, $callback, $priority);
71
    }
72
73
    /**
74
     * Remove event handler.
75
     *
76
     * @param callable|EventHandlerInterface|null $callback Event handler
77
     * @param string|EventInterface|null $event Event name or object
78
     * @return void
79
     */
80
    public function off($callback = null, $event = null): void
81
    {
82
        $this->getEventDispatcher()->off($callback, $event);
83
    }
84
}
85