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 | * @api |
||
41 | * @param EventDispatcherInterface $dispatcher |
||
42 | */ |
||
43 | public function setEventDispatcher(EventDispatcherInterface $dispatcher): void |
||
44 | { |
||
45 | $this->eventDispatcher = $dispatcher; |
||
46 | } |
||
47 | |||
48 | /** |
||
49 | * Invoke handlers. |
||
50 | * |
||
51 | * @api |
||
52 | * @param string|EventInterface $event Event name or object |
||
53 | * @param callable|null $until Invoke handlers until callback return value evaluate to true |
||
54 | * @param EventEmitterInterface|null $target |
||
55 | * @return EventInterface Event object |
||
56 | */ |
||
57 | public function emit($event, callable $until = null, EventEmitterInterface $target = null): EventInterface |
||
58 | { |
||
59 | return $this->getEventDispatcher()->emit($event, $until, $target ?: $this); |
||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
60 | } |
||
61 | |||
62 | /** |
||
63 | * Set event handler. |
||
64 | * |
||
65 | * @api |
||
66 | * @param string|EventInterface|EventHandlerInterface $event Event name, object or event handler |
||
67 | * @param callable|null $callback Event handler |
||
68 | * @param int $priority Handler invocation priority |
||
69 | * @return void |
||
70 | */ |
||
71 | public function on($event, $callback = null, int $priority = 0) |
||
72 | { |
||
73 | $this->getEventDispatcher()->on($event, $callback, $priority); |
||
74 | } |
||
75 | |||
76 | /** |
||
77 | * Remove event handler. |
||
78 | * |
||
79 | * @api |
||
80 | * @param callable|EventHandlerInterface|null $callback Event handler |
||
81 | * @param string|EventInterface|null $event Event name or object |
||
82 | * @return void |
||
83 | */ |
||
84 | public function off($callback = null, $event = null): void |
||
85 | { |
||
86 | $this->getEventDispatcher()->off($callback, $event); |
||
87 | } |
||
88 | } |
||
89 |