summaryrefslogtreecommitdiff
path: root/app/frontend/events/EventModule.php
blob: 355551038bbb49e887e10326c962c2bc84ec5082 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php

class EventModule extends TModule {

    public function init($config) {
        $reflection = new ReflectionClass($this);
        foreach ($reflection->getMethods() as $method) {
            if (is_a($method->class, get_class(), TRUE)) {
                $eventPattern = [];
                if (preg_match('/^on(.*)/', $method->name, $eventPattern)) {
                    $this->_registerEventHandler(
                        $eventPattern[1],
                        $method->getClosure($this)
                    );
                }
            }
        }
        if (get_class() === get_called_class()) {
            $directory = dirname(__FILE__);
            foreach (scandir($directory) as $dirEntry) {
                $classNameMatch = [];
                if (preg_match('/(.*)\.php$/', $dirEntry, $classNameMatch)) {
                    $className = $classNameMatch[1];
                    include_once($directory . DIRECTORY_SEPARATOR . $dirEntry);
                    if ($className != get_class()
                        && is_a($className, get_class(), TRUE)) {
                        $class = new $className();
                        $class->init(NULL);
                    }
                }
            }
        }
    }

    protected static $_handlers = [];
    private function _registerEventHandler(string $event, callable $handler) {
        if (!isset(self::$_handlers[$event])) {
            self::$_handlers[$event] = [];
        }
        self::$_handlers[$event][] = $handler;
    }

    public function raiseApplicationEvent(string $event, ...$params) {
        if (isset(self::$_handlers[$event])) {
            foreach (self::$_handlers[$event] as $handler) {
                call_user_func_array($handler, $params);
            }
        }
    }

}

?>