Passed
Push — main ( e0d381...c6e32b )
by Pranjal
02:29
created

Event::subscribeTo()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 2
eloc 3
c 1
b 1
f 0
nc 2
nop 3
dl 0
loc 6
rs 10
1
<?php
2
declare(strict_types=1);
3
4
namespace Scrawler\Arca;
5
6
7
/**
8
 * A simple event system for any PHP Project
9
 */
10
class Event
11
{
12
    static $events;
13
14
    /**
15
     * Register an event before it becoming available for use
16
     */
17
    private static function register(string $eventname): void
18
    {
19
        if (!isset(self::$events[$eventname])) {
20
            self::$events[$eventname] = array();
21
        }
22
    }
23
24
    /**
25
     * Subscribe to a defined event.
26
     */
27
    public static function subscribeTo(string $eventname, callable $callback, int $priority = 0): void
28
    {
29
        if (!self::isEvent($eventname)) {
30
            self::register($eventname);
31
        }
32
        self::$events[$eventname][$priority][] = $callback;
33
    }
34
35
    /**
36
     * Trigger an event, and call all subscribers, giving an array of params.
37
     * returns the data returned by the last subscriber.
38
     */
39
    public static function dispatch($eventname, $params) : mixed
40
    {
41
        $data = null;
42
        if (!self::isEvent($eventname)) {
43
            self::register($eventname);
44
        }
45
        foreach (self::$events[$eventname] as $key => $weight) {
46
            foreach ($weight as $callback) {
47
                $data = call_user_func_array($callback, $params);
48
            }
49
        }
50
51
        return $data;
52
    }
53
54
    /**
55
     * Check that an event is valid before interacting with it.
56
     *
57
     */
58
    private static function isEvent($eventname)
59
    {
60
        if (!isset(self::$events[$eventname]) || !is_array(self::$events[$eventname])) {
61
            return false;
62
        }
63
        return true;
64
    }
65
}
66
67