Skip to content

Commit a270cf8

Browse files
committed
Merge pull request #87 from php-school/attach-to-multiple-events
Allow attaching to multiple events at same time
2 parents 9070509 + 4265a56 commit a270cf8

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

src/Event/EventDispatcher.php

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,10 +65,25 @@ public function dispatch(EventInterface $event)
6565
}
6666

6767
/**
68-
* @param string $eventName
68+
* @param string $eventNames
69+
* @param callable $callback
70+
*/
71+
public function listen($eventNames, callable $callback)
72+
{
73+
if (!is_array($eventNames)) {
74+
$eventNames = [$eventNames];
75+
}
76+
77+
foreach ($eventNames as $eventName) {
78+
$this->attachListener($eventName, $callback);
79+
}
80+
}
81+
82+
/**
83+
* @param string|array $eventName
6984
* @param callable $callback
7085
*/
71-
public function listen($eventName, callable $callback)
86+
private function attachListener($eventName, callable $callback)
7287
{
7388
if (!array_key_exists($eventName, $this->listeners)) {
7489
$this->listeners[$eventName] = [$callback];

test/Event/EventDispatcherTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,4 +82,19 @@ public function testVerifyReturnIsSkippedIfNotInstanceOfResult()
8282

8383
$this->assertEquals([], iterator_to_array($this->results));
8484
}
85+
86+
public function testListenWithMultipleEvents()
87+
{
88+
$e1 = new Event('some-event', ['arg1' => 1, 'arg2' => 2]);
89+
$e2 = new Event('some-event', ['arg1' => 1, 'arg2' => 2]);
90+
$mockCallback1 = $this->getMock('stdClass', ['callback']);
91+
$mockCallback1->expects($this->exactly(2))
92+
->method('callback')
93+
->withConsecutive([$e1], [$e2])
94+
->will($this->returnValue(true));
95+
96+
$this->eventDispatcher->listen(['some-event', 'second-event'], [$mockCallback1, 'callback']);
97+
$this->eventDispatcher->dispatch($e1);
98+
$this->eventDispatcher->dispatch($e2);
99+
}
85100
}

0 commit comments

Comments
 (0)