Skip to content

Commit

Permalink
Add DispatcherInterface::unregisterHandler + implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
burithetech authored and tomaj committed Apr 29, 2024
1 parent 99ca784 commit d33a508
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/Dispatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,22 @@ public function unregisterAllHandlers(): DispatcherInterface
return $this;
}

/**
* {@inheritdoc}
*/
public function unregisterHandler(string $type, HandlerInterface $handler): DispatcherInterface
{
if (!isset($this->handlers[$type])) {
return $this;
}
$this->handlers[$type] = array_filter(
$this->handlers[$type],
fn ($registeredHandler) => $registeredHandler !== $handler
);

return $this;
}

/**
* Serialize message to logger context
*
Expand Down
10 changes: 10 additions & 0 deletions src/DispatcherInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,16 @@ public function registerHandlers(string $type, array $handler): DispatcherInterf
*/
public function unregisterAllHandlers(): DispatcherInterface;

/**
* Will unregister a specific handler.
*
* @param string $type
* @param HandlerInterface $handler
*
* @return DispatcherInterface
*/
public function unregisterHandler(string $type, HandlerInterface $handler): DispatcherInterface;

/**
* Basic method for background job to star listening.
*
Expand Down
25 changes: 25 additions & 0 deletions tests/HandleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -184,4 +184,29 @@ public function testUnregisterAllHandlers(): void
$receivedMessages = $handler->getReceivedMessages();
$this->assertCount(1, $receivedMessages);
}

public function testUnregisterHandler(): void
{
$message1 = new Message('event1', ['a' => 'b']);
$message2 = new Message('event2', ['c' => 'd']);

$driver = new DummyDriver([$message1, $message2]);
$dispatcher = new Dispatcher($driver);

$firstHandler = new TestHandler();
$secondHandler = new TestHandler();

$dispatcher->registerHandler('event1', $firstHandler);
$dispatcher->registerHandler('event2', $secondHandler);
$dispatcher->handle();

$dispatcher->unregisterHandler('event2', $secondHandler);
$dispatcher->handle();

$firstHandlerReceivedMessages = $firstHandler->getReceivedMessages();
$this->assertCount(2, $firstHandlerReceivedMessages);

$secondHandlerReceivedMessages = $secondHandler->getReceivedMessages();
$this->assertCount(1, $secondHandlerReceivedMessages);
}
}

0 comments on commit d33a508

Please sign in to comment.