From 390895d71a8dde842805d052632edc85af2580b3 Mon Sep 17 00:00:00 2001 From: Aydin Hassan Date: Sat, 30 Jan 2016 18:00:54 +0000 Subject: [PATCH 1/2] Allow attaching to multiple events at same time --- src/Event/EventDispatcher.php | 17 ++++++++++++++++- test/Event/EventDispatcherTest.php | 15 +++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/Event/EventDispatcher.php b/src/Event/EventDispatcher.php index a503e89a..e2fc8e85 100644 --- a/src/Event/EventDispatcher.php +++ b/src/Event/EventDispatcher.php @@ -64,11 +64,26 @@ public function dispatch(EventInterface $event) return $event; } + /** + * @param string $eventNames + * @param callable $callback + */ + public function listen($eventNames, callable $callback) + { + if (!is_array($eventNames)) { + $eventNames = [$eventNames]; + } + + foreach ($eventNames as $eventName) { + $this->attachListener($eventName, $callback); + } + } + /** * @param string $eventName * @param callable $callback */ - public function listen($eventName, callable $callback) + private function attachListener($eventName, callable $callback) { if (!array_key_exists($eventName, $this->listeners)) { $this->listeners[$eventName] = [$callback]; diff --git a/test/Event/EventDispatcherTest.php b/test/Event/EventDispatcherTest.php index 2e6e380a..35d902ce 100644 --- a/test/Event/EventDispatcherTest.php +++ b/test/Event/EventDispatcherTest.php @@ -82,4 +82,19 @@ public function testVerifyReturnIsSkippedIfNotInstanceOfResult() $this->assertEquals([], iterator_to_array($this->results)); } + + public function testListenWithMultipleEvents() + { + $e1 = new Event('some-event', ['arg1' => 1, 'arg2' => 2]); + $e2 = new Event('some-event', ['arg1' => 1, 'arg2' => 2]); + $mockCallback1 = $this->getMock('stdClass', ['callback']); + $mockCallback1->expects($this->exactly(2)) + ->method('callback') + ->withConsecutive([$e1], [$e2]) + ->will($this->returnValue(true)); + + $this->eventDispatcher->listen(['some-event', 'second-event'], [$mockCallback1, 'callback']); + $this->eventDispatcher->dispatch($e1); + $this->eventDispatcher->dispatch($e2); + } } From 4265a56f00db9fde7f1cdedcd63b7067462019e2 Mon Sep 17 00:00:00 2001 From: Aydin Hassan Date: Sat, 30 Jan 2016 18:06:43 +0000 Subject: [PATCH 2/2] Fix typehint --- src/Event/EventDispatcher.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Event/EventDispatcher.php b/src/Event/EventDispatcher.php index e2fc8e85..c430a80b 100644 --- a/src/Event/EventDispatcher.php +++ b/src/Event/EventDispatcher.php @@ -80,7 +80,7 @@ public function listen($eventNames, callable $callback) } /** - * @param string $eventName + * @param string|array $eventName * @param callable $callback */ private function attachListener($eventName, callable $callback)