Skip to content

Commit

Permalink
Allow closure listeners (#81)
Browse files Browse the repository at this point in the history
* Allow clouse listeners

* Add documentation
Add test to avoid regression

* Avoid makeListener when you pass a closure

* Refactor listener closure

Co-authored-by: Alex Rubia <[email protected]>
  • Loading branch information
joskfg and Alex Rubia authored Dec 10, 2021
1 parent d67d79a commit 350564f
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 3 deletions.
3 changes: 2 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,8 @@ The `listen` property of `RabbitEventsServiceProvider` contains an array of all
protected $listen = [
'item.created' => [
'App\Listeners\SendItemCreatedNotification',
'App\Listeners\ChangeUserRole',
'App\Listeners\ChangeUserRole@process',
function($payload) { Log::info('Item created', $payload); },
],
];
```
Expand Down
4 changes: 4 additions & 0 deletions src/Dispatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ public function listen($events, $listener = null): void
*/
public function makeListener($listener, $wildcard = false): \Closure
{
if ($listener instanceof \Closure) {
return $listener;
}

return function ($event, $payload) use ($listener, $wildcard) {
$throughMiddleware = $this->extractMiddleware($listener);

Expand Down
10 changes: 8 additions & 2 deletions tests/DispatcherTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,11 @@ public function testListen()
public function testAddedClosureListeners()
{
$dispatcher = new Dispatcher();
$closure1 = function() {};
$closure2 = function() {};

$dispatcher->listen('item.event', function() {});
$dispatcher->listen('item.event', function() {});
$dispatcher->listen('item.event', $closure1);
$dispatcher->listen('item.event', $closure2);

$listeners = $dispatcher->getListeners('item.event');

Expand All @@ -50,6 +52,10 @@ public function testAddedClosureListeners()
self::assertEquals(['Closure'], array_keys($listeners));

self::assertCount(2, $listeners['Closure']);

self::assertSame($closure1, $listeners['Closure'][0]);

self::assertSame($closure2, $listeners['Closure'][1]);
}

public function testCorrectWildcardHandling()
Expand Down

0 comments on commit 350564f

Please sign in to comment.