From 3ea8d27a3bdcf7866119928b4e0ee9d498bfdfe3 Mon Sep 17 00:00:00 2001 From: "Dylan K. Taylor" Date: Fri, 7 Apr 2023 22:55:27 +0100 Subject: [PATCH] HandlerList: improve listener list development to make way for #5678 --- src/event/EventPriority.php | 2 ++ src/event/HandlerList.php | 22 ++++++++++++---------- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/src/event/EventPriority.php b/src/event/EventPriority.php index cdeb3136a..99c71faff 100644 --- a/src/event/EventPriority.php +++ b/src/event/EventPriority.php @@ -32,6 +32,8 @@ use function mb_strtoupper; * LOWEST -> LOW -> NORMAL -> HIGH -> HIGHEST -> MONITOR * * MONITOR events should not change the event outcome or contents + * + * WARNING: If these values are changed, handler sorting in HandlerList::getListenerList() may need to be updated. */ final class EventPriority{ diff --git a/src/event/HandlerList.php b/src/event/HandlerList.php index 7774ea840..0bc207560 100644 --- a/src/event/HandlerList.php +++ b/src/event/HandlerList.php @@ -24,8 +24,10 @@ declare(strict_types=1); namespace pocketmine\event; use pocketmine\plugin\Plugin; -use function array_fill_keys; +use function array_merge; +use function krsort; use function spl_object_id; +use const SORT_NUMERIC; class HandlerList{ /** @var RegisteredListener[][] */ @@ -48,8 +50,6 @@ class HandlerList{ for($list = $this; $list !== null; $list = $list->parentList){ $list->affectedHandlerCaches[spl_object_id($this->handlerCache)] = $this->handlerCache; } - - $this->handlerSlots = array_fill_keys(EventPriority::ALL, []); } /** @@ -94,7 +94,7 @@ class HandlerList{ } public function clear() : void{ - $this->handlerSlots = array_fill_keys(EventPriority::ALL, []); + $this->handlerSlots = []; $this->invalidateAffectedCaches(); } @@ -132,15 +132,17 @@ class HandlerList{ $handlerLists[] = $currentList; } - $listeners = []; - foreach(EventPriority::ALL as $priority){ - foreach($handlerLists as $currentList){ - foreach($currentList->getListenersByPriority($priority) as $registration){ - $listeners[] = $registration; - } + $listenersByPriority = []; + foreach($handlerLists as $currentList){ + foreach($currentList->handlerSlots as $priority => $listeners){ + $listenersByPriority[$priority] = array_merge($listenersByPriority[$priority] ?? [], $listeners); } } + //TODO: why on earth do the priorities have higher values for lower priority? + krsort($listenersByPriority, SORT_NUMERIC); + $listeners = array_merge(...$listenersByPriority); + return $this->handlerCache->list = $listeners; } }