EventTrait::bind()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 2
crap 1
1
<?php
2
3
/**
4
 * @author Marwan Al-Soltany <[email protected]>
5
 * @copyright Marwan Al-Soltany 2020
6
 * For the full copyright and license information, please view
7
 * the LICENSE file that was distributed with this source code.
8
 */
9
10
declare(strict_types=1);
11
12
namespace MAKS\AmqpAgent\Helper;
13
14
use Closure;
15
16
/**
17
 * A trait containing events handling functions (adds events triggering and binding capabilities) to a class.
18
 * @since 2.0.0
19
 */
20
trait EventTrait
21
{
22
    /**
23
     * Here lives all bindings.
24
     * @var array
25
     */
26
    protected static $events = [];
27
28
    /**
29
     * Executes callbacks attached to the passed event with the passed arguments.
30
     * @param string $event Event name.
31
     * @param array $arguments [optional] Arguments array. Note that the arguments will be spread (`...$args`) on the callback.
32
     * @return void
33
     */
34 12
    protected static function trigger(string $event, array $arguments = []): void
35
    {
36 12
        if (isset(self::$events[$event]) && count(self::$events[$event])) {
37 7
            $callbacks = &self::$events[$event];
38 7
            foreach ($callbacks as $callback) {
39 7
                call_user_func_array($callback, array_values($arguments));
40
            }
41
        } else {
42 12
            self::$events[$event] = [];
43
        }
44 12
    }
45
46
    /**
47
     * Binds the passed function to the passed event.
48
     * @param string $event Event name.
49
     * @param Closure $function A closure to process the event.
50
     * @return void
51
     */
52 4
    protected static function bind(string $event, Closure $function): void
53
    {
54 4
        self::$events[$event][] = $function;
55 4
    }
56
57
    /**
58
     * Returns array of all registered events as an array `['event.name' => [$cb1, $cb2, ...]]`.
59
     * @return array
60
     */
61 1
    public static function getEvents(): array
62
    {
63 1
        return self::$events;
64
    }
65
}
66