Passed
Pull Request — main (#18)
by Dimitri
03:55
created

EventManager::off()   A

Complexity

Conditions 6
Paths 4

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
cc 6
eloc 8
nc 4
nop 2
dl 0
loc 16
ccs 0
cts 5
cp 0
crap 42
rs 9.2222
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * This file is part of Blitz PHP framework.
5
 *
6
 * (c) 2022 Dimitri Sitchet Tomkeu <[email protected]>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11
12
namespace BlitzPHP\Event;
13
14
use BlitzPHP\Contracts\Event\EventInterface;
15
use BlitzPHP\Contracts\Event\EventManagerInterface;
16
17
/**
18
 * EventManager
19
 *
20
 * @credit      https://www.phpclasses.org/package/9961-PHP-Manage-events-implementing-PSR-14-interface.html - Kiril Savchev <[email protected]>
21
 */
22
class EventManager implements EventManagerInterface
23
{
24
    /**
25
     * Le nom générique de l'événement
26
     */
27
    public const WILDCARD = '*';
28
29
    /**
30
     * @var array
31
     */
32
    protected $events;
33
34
    /**
35
     * Stocke des informations sur les événements
36
     * pour affichage dans la barre d'outils de débogage.
37
     *
38
     * @var array
39
     */
40
    protected static $performanceLog = [];
41
42
    /**
43
     * Créer un objet gestionnaire d'événements
44
     *
45
     * @param array $events [Optionnel]
46
     */
47
    public function __construct(array $events = [])
48
    {
49
        $this->events = $events;
50
        if (! array_key_exists(self::WILDCARD, $this->events)) {
51
            $this->events[self::WILDCARD] = [];
52
        }
53
    }
54
55
    /**
56
     * {@inheritDoc}
57
     */
58
    public function clearListeners(string $event): void
59
    {
60
        $this->events[$event] = [];
61
    }
62
63
    /**
64
     * {@inheritDoc}
65
     */
66
    public function on(string $event, callable $callback, int $priority = 0): bool
67
    {
68
        if (! array_key_exists($event, $this->events)) {
69
            $this->events[$event] = [];
70
        }
71
        if (! array_key_exists($priority, $this->events[$event])) {
72
            $this->events[$event][$priority] = [];
73
        }
74
75
        if (! in_array($callback, $this->events[$event][$priority], true)) {
76
            $this->events[$event][$priority][] = $callback;
77
78
            return true;
79
        }
80
81
        return false;
82
    }
83
84
    /**
85
     * @deprecated use on() instead
86
     */
87
    public function attach(string $event, callable $callback, int $priority = 0): bool
88
    {
89
        return $this->on($event, $callback, $priority);
90
    }
91
92
    /**
93
     * {@inheritDoc}
94
     */
95
    public function off(string $event, callable $callback): bool
96
    {
97
        if (! array_key_exists($event, $this->events) || ! $this->events[$event]) {
98
            return false;
99
        }
100
101
        $eventsAgregation = $this->events[$event];
102
103
        foreach ($eventsAgregation as $priority => $events) {
104
            if (is_array($events) && in_array($callback, $events, true)) {
105
                $key = array_search($callback, $events, true);
106
                unset($this->events[$event][$priority][$key]);
107
            }
108
        }
109
110
        return true;
111
    }
112
113
	/**
114
     * @deprecated use off() instead
115
     */
116
    public function detach(string $event, callable $callback, int $priority = 0): bool
117
    {
118
        return $this->off($event, $callback, $priority);
0 ignored issues
show
Unused Code introduced by
The call to BlitzPHP\Event\EventManager::off() has too many arguments starting with $priority. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

118
        return $this->/** @scrutinizer ignore-call */ off($event, $callback, $priority);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
119
    }
120
121
    /**
122
     * {@inheritDoc}
123
     */
124
    public function emit($event, $target = null, $argv = [])
125
    {
126
        if (! ($event instanceof EventInterface)) {
127 2
            $event = new Event($event, $target, $argv);
128
        } else {
129
            if ($target) {
130
                $event->setTarget($target);
131
            }
132
            if ($argv) {
133
                $event->setParams($argv);
134
            }
135
        }
136
137 2
        $eventName = $event->getName();
138
        if (! array_key_exists($eventName, $this->events)) {
139 2
            $this->events[$eventName] = [];
140
        }
141
142 2
        $events = array_merge($this->events[self::WILDCARD], $this->events[$eventName]);
143 2
        $result = null;
144
145
        foreach ($events as $priority) {
146
            if (! is_array($priority)) {
147
                continue;
148
            }
149
150
            foreach ($priority as $callback) {
151
                if ($event->isPropagationStopped()) {
152
                    break 2;
153
                }
154
155
                $start = microtime(true);
156
157
                $result = $callback($event, $result);
158
159
                static::$performanceLog[] = [
160
                    'start' => $start,
161
                    'end'   => microtime(true),
162
                    'event' => strtolower($eventName),
163
                ];
164
            }
165
        }
166
167 2
        return $result;
168
    }
169
170
	/**
171
	 * @deprecated use emit() instead
172
	 */
173
	public function trigger($event, $target = null, $argv = [])
174
    {
175 2
        return $this->emit($event, $target, $argv);
176
    }
177
178
    /**
179
     * Getter pour les enregistrements du journal des performances.
180
     */
181
    public static function getPerformanceLogs(): array
182
    {
183
        return static::$performanceLog;
184
    }
185
}
186