Skip to content

Commit 5b35dda

Browse files
Llooplempociot
authored andcommitted
Allow BotMan to register the same callback to multiple events. (botman#849)
1 parent 051f6fd commit 5b35dda

File tree

2 files changed

+47
-6
lines changed

2 files changed

+47
-6
lines changed

src/BotMan.php

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -274,15 +274,23 @@ public function hears($pattern, $callback, $in = null)
274274
/**
275275
* Listen for messaging service events.
276276
*
277-
* @param string $name
277+
* @param array|string $names
278278
* @param Closure|string $callback
279279
*/
280-
public function on($name, $callback)
280+
public function on($names, $callback)
281281
{
282-
$this->events[] = [
283-
'name' => $name,
284-
'callback' => $this->getCallable($callback),
285-
];
282+
if (! is_array($names)) {
283+
$names = [$names];
284+
}
285+
286+
$callable = $this->getCallable($callback);
287+
288+
foreach ($names as $name) {
289+
$this->events[] = [
290+
'name' => $name,
291+
'callback' => $callable,
292+
];
293+
}
286294
}
287295

288296
/**

tests/BotManDriverEventTest.php

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,26 @@ public function it_calls_driver_events()
5252
$this->assertTrue($called);
5353
}
5454

55+
/** @test */
56+
public function it_can_assign_same_callback_for_events()
57+
{
58+
$called = 0;
59+
$this->fakeDriver->hasMatchingEvent = new TestEvent([]);
60+
$this->botman->on(['test_event', 'test_event_two'], function ($data, BotMan $bot) use (&$called) {
61+
$called++;
62+
});
63+
64+
$this->botman->listen();
65+
66+
$this->assertEquals(1, $called);
67+
68+
$this->fakeDriver->hasMatchingEvent = new TestEventTwo([]);
69+
70+
$this->botman->listen();
71+
72+
$this->assertEquals(2, $called);
73+
}
74+
5575
/** @test */
5676
public function it_calls_driver_events_without_closure()
5777
{
@@ -114,6 +134,19 @@ public function getPayload()
114134
}
115135
}
116136

137+
class TestEventTwo extends TestEvent
138+
{
139+
/**
140+
* Return the event name to match.
141+
*
142+
* @return string
143+
*/
144+
public function getName()
145+
{
146+
return 'test_event_two';
147+
}
148+
}
149+
117150
class TestEventClass
118151
{
119152
public function event($payload, $bot)

0 commit comments

Comments
 (0)