EventHandlerTrait::detachEventEmitter()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 5
rs 10
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
 * Class EventHandlerTrait
15
 * @package event-emitter
16
 */
17
trait EventHandlerTrait
18
{
19
    /**
20
     * @var EventDispatcherInterface
21
     */
22
    private $emitter;
23
24
    /**
25
     * @var callable[]
26
     */
27
    private $handlers = [];
28
29
    /**
30
     * Initialize events.
31
     */
32
    abstract protected function initEvents(): void;
33
34
    /**
35
     * Handle an event.
36
     *
37
     * @param string|EventInterface $event Event name or object
38
     * @param string|callable|null $callback Event handler
39
     * @param int $priority
40
     * @return void
41
     */
42
    protected function on($event, $callback = null, $priority = 1): void
43
    {
44
        $handler = $this->createCallback($callback);
45
        $this->emitter->on($event, $handler, $priority);
46
        $this->handlers[] = $handler;
47
    }
48
49
    /**
50
     * Attach event emitter to handler.
51
     *
52
     * @api
53
     * @param EventDispatcherInterface $emitter Event emitter
54
     * @return void
55
     */
56
    public function attachEventEmitter(EventDispatcherInterface $emitter): void
57
    {
58
        $this->emitter = $emitter;
59
        $this->initEvents();
60
    }
61
62
    /**
63
     * Detach event emitter from handler.
64
     *
65
     * @api
66
     * @param EventDispatcherInterface $emitter Event emitter
67
     * @return void
68
     */
69
    public function detachEventEmitter(EventDispatcherInterface $emitter): void
70
    {
71
        foreach ($this->handlers as $index => $handler) {
72
            $emitter->off($handler);
73
            unset($this->handlers[$index]);
74
        }
75
    }
76
77
    /**
78
     * @param string|callable|null $callback
79
     * @return callable
80
     */
81
    private function createCallback($callback)
82
    {
83
        $callback = is_string($callback) ? [$this, $callback] : $callback;
84
        return is_callable($callback) ? $callback : function () {
85
        };
86
    }
87
}
88