From 7a7505193d8d49934895058b5ef0c010ad9ff399 Mon Sep 17 00:00:00 2001 From: Dennis Eichhorn Date: Sat, 1 Dec 2018 21:42:22 +0100 Subject: [PATCH] Allow array multiple callbacks per trigger --- Event/EventManager.php | 37 +++++++++++++++++++++++++++++++++---- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/Event/EventManager.php b/Event/EventManager.php index db5812a3a..5ed6a53c4 100644 --- a/Event/EventManager.php +++ b/Event/EventManager.php @@ -14,6 +14,8 @@ declare(strict_types=1); namespace phpOMS\Event; +use phpOMS\Dispatcher\Dispatcher; + /** * EventManager class. * @@ -42,6 +44,31 @@ final class EventManager */ private $callbacks = []; + /** + * Dispatcher. + * + * @var Dispatcher|Object + * @since 1.0.0 + */ + private $dispatcher = null; + + /** + * Constructor. + * + * @param Dispatcher $dispatcher Dispatcher + * + * @since 1.0.0 + */ + public function __construct(Dispatcher $dispatcher = null) + { + $this->dispatcher = $dispatcher ?? new class { + function dispatch($func, array $data) + { + $func(...$data); + } + }; + } + /** * Attach new event * @@ -56,11 +83,11 @@ final class EventManager */ public function attach(string $group, $callback, bool $remove = false, bool $reset = false) : bool { - if (isset($this->callbacks[$group])) { - return false; + if (!isset($this->callbacks[$group])) { + $this->callbacks[$group] = ['remove' => $remove, 'reset' => $reset, 'callbacks' => []]; } - $this->callbacks[$group] = ['remove' => $remove, 'reset' => $reset, 'func' => $callback]; + $this->callbacks[$group]['callbacks'][] = $callback; return true; } @@ -112,7 +139,9 @@ final class EventManager } if (!$this->hasOutstanding($group)) { - $this->callbacks[$group]['func']($data); + foreach ($this->callbacks[$group]['callbacks'] as $func) { + $this->dispatcher->disptach($func, ...$data); + } if ($this->callbacks[$group]['remove']) { $this->detach($group);