diff --git a/Event.php b/Event.php index b97b986..9e1b896 100644 --- a/Event.php +++ b/Event.php @@ -79,6 +79,10 @@ class Event */ protected $_callable = []; + /** + * @var array + */ + protected $_priorities = []; /** @@ -186,10 +190,23 @@ public static function unregister($eventId, $hard = false) * @param mixed $callable Callable. * @return \Hoa\Event\Event */ - public function attach($callable) + public function attach($callable, $priority = 0) { - $callable = xcallable($callable); - $this->_callable[$callable->getHash()] = $callable; + $callable = xcallable($callable); + $hash = $callable->getHash(); + $this->_callable[$hash] = $callable; + $this->_priorities[$hash] = (int) $priority; + + uksort($this->_callable, function ($a, $b) { + $a = $this->_priorities[$a]; + $b = $this->_priorities[$b]; + + /*if (70000 <= PHP_VERSION_ID) { + return $this->_priorities[$ka] <=> $this->_priorities[$kb]; + }*/ + + return ($a < $b) ? 1 : (($a > $b) ? -1 : 0); + }); return $this; } diff --git a/Test/Unit/Event.php b/Test/Unit/Event.php index 769d22a..210aa6d 100644 --- a/Test/Unit/Event.php +++ b/Test/Unit/Event.php @@ -186,6 +186,47 @@ public function case_attach() ->isIdenticalTo($event) ->boolean($event->isListened()) ->isTrue(); + + $this + ->given( + $eventId = 'hoa://Event/Test', + $source = new \Mock\Hoa\Event\Source(), + $bucket = new LUT\Bucket(), + $called = '', + + SUT::register($eventId, $source), + SUT::getEvent($eventId)->attach( + function (LUT\Bucket $receivedBucket) use (&$called) { + $called .= '1'; + }, 100 + ), + SUT::getEvent($eventId)->attach( + function (LUT\Bucket $receivedBucket) use (&$called) { + $called .= '2'; + }, 10 + ), + SUT::getEvent($eventId)->attach( + function (LUT\Bucket $receivedBucket) use (&$called) { + $called .= '3'; + } + ), + SUT::getEvent($eventId)->attach( + function (LUT\Bucket $receivedBucket) use (&$called) { + $called .= '3'; + }, 0 + ), + SUT::getEvent($eventId)->attach( + function (LUT\Bucket $receivedBucket) use (&$called) { + $called .= '4'; + }, -1 + ) + ) + ->when($result = SUT::notify($eventId, $source, $bucket)) + ->then + ->variable($result) + ->isNull() + ->string($called) + ->isIdenticalTo('12334'); } public function case_detach()