forked from EqualifyEverything/equalify
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhooks.php
More file actions
62 lines (53 loc) · 1.67 KB
/
hooks.php
File metadata and controls
62 lines (53 loc) · 1.67 KB
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
54
55
56
57
58
59
60
61
62
<?php
/*
* A bare-bones implementation of an ordered hook system, similar to that of WordPress.
*
* Ordering between hooks comes from PHP's arrays being ordered dicts.
* Ordering within hooks comes from each action's priority number.
*
* This implementation doesn't include filters, but they wouldn't work too differently;
* filters are like actions, only their Closures must return a value,
* and a "run_filters" function would work like a reducer, chaining the filters together.
*
* Tested on PHP 8.1.
*
* Copyright (c) 2022 Ezra Bertuccelli
* MIT License
* https://gist.github.com/ebertucc/bda36c8125186d9c290596ab7a50939e
*/
class Action {
public function __construct(
public string $hook,
public Closure $action,
public int $priority = 100,
) {}
}
class HookSystem {
public function __construct(
private array $_hooks,
private array $_actions = []
) {}
public function add_action(Action $action): void {
$this->_actions[] = $action;
}
public function run_hook(string $hook): void {
// filter by hook
$filter = fn(Action $action) => $action->hook === $hook;
// order by priority
$sort = fn($a, $b) => $a->priority <=> $b->priority;
$actions_to_run = array_filter($this->_actions, $filter);
usort($actions_to_run, $sort);
foreach ($actions_to_run as $action) {
($action->action)();
}
}
}
// Initialize hooks.
$hook_system = new HookSystem([
'before_content' // everything before the app content
]);
// Set initial actions for hooks.
$hook_system->add_action(
new Action('before_content', function() {
})
);