From dc17b701da053e04bfa64e21be9247a4f07505e1 Mon Sep 17 00:00:00 2001 From: slawkens Date: Sat, 29 Jun 2024 14:05:06 +0200 Subject: [PATCH] feat: Hooks priority --- plugins/example.json | 5 +++-- system/src/Plugins.php | 17 ++++++++++++++++- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/plugins/example.json b/plugins/example.json index 24c608c9..68805cb9 100644 --- a/plugins/example.json +++ b/plugins/example.json @@ -25,7 +25,8 @@ "hooks": { "Example Hook": { "type": "BEFORE_PAGE", - "file": "plugins/example/before.php" + "file": "plugins/example/before.php", + "priority": 1000 } }, "routes": { @@ -33,7 +34,7 @@ "pattern": "/YourAwesomePage/{name:string}/{page:int}", "file": "plugins/your-plugin/your-awesome-page.php", "method": "GET", - "priority": "130" + "priority": 130 }, "Redirect Example": { "redirect_from": "/redirectExample", diff --git a/system/src/Plugins.php b/system/src/Plugins.php index b0d58afe..97604af4 100644 --- a/system/src/Plugins.php +++ b/system/src/Plugins.php @@ -218,14 +218,20 @@ class Plugins { $hooks = []; foreach(self::getAllPluginsJson() as $plugin) { if (isset($plugin['hooks'])) { + $priority = 1000; + foreach ($plugin['hooks'] as $_name => $info) { if (str_contains($info['type'], 'HOOK_')) { $info['type'] = str_replace('HOOK_', '', $info['type']); } + if (isset($info['priority'])) { + $priority = (int)$info['priority']; + } + if (defined('HOOK_'. $info['type'])) { $hook = constant('HOOK_'. $info['type']); - $hooks[] = ['name' => $_name, 'type' => $hook, 'file' => $info['file']]; + $hooks[] = ['name' => $_name, 'type' => $hook, 'file' => $info['file'], 'priority' => $priority]; } else { self::$warnings[] = 'Plugin: ' . $plugin['name'] . '. Unknown event type: ' . $info['type']; } @@ -233,6 +239,15 @@ class Plugins { } } + usort($hooks, function ($a, $b) + { + if ($a['priority'] == $b['priority']) { + return 0; + } + + return ($a['priority'] < $b['priority']) ? -1 : 1; + }); + if ($cache->enabled()) { $cache->set('plugins_hooks', serialize($hooks), 600); }