Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 48 additions & 3 deletions src/Illuminate/Bus/Dispatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,13 @@ class Dispatcher implements QueueingDispatcher
*/
protected $pipes = [];

/**
* The command to handler mapping for non-self-handling events.
*
* @var array
*/
protected $handlers = [];

/**
* The queue resolver callback.
*
Expand Down Expand Up @@ -77,9 +84,33 @@ public function dispatch($command)
*/
public function dispatchNow($command)
{
return $this->pipeline->send($command)->through($this->pipes)->then(function ($command) {
return $this->container->call([$command, 'handle']);
});
if ($handler = $this->getCommandHandler($command)) {
$callback = function ($command) use ($handler) {
return $handler->handle($command);
};
} else {
$callback = function ($command) {
return $this->container->call([$command, 'handle']);
};
}

return $this->pipeline->send($command)->through($this->pipes)->then($callback);
}

/**
* Retrieve the handler for a command.
*
* @param mixed $command
*
* @return bool|mixed
*/
protected function getCommandHandler($command)
{
if (array_key_exists(get_class($command), $this->handlers)) {
return $this->container->make($this->handlers[get_class($command)]);
}

return false;
}

/**
Expand Down Expand Up @@ -154,4 +185,18 @@ public function pipeThrough(array $pipes)

return $this;
}

/**
* Map a command to a handler.
*
* @param string $command
* @param string $handler
* @return $this
*/
public function map($command, $handler)
{
$this->handlers[$command] = $handler;

return $this;
}
}
27 changes: 27 additions & 0 deletions tests/Bus/BusDispatcherTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,21 @@ public function testDispatchNowShouldNeverQueue()

$dispatcher->dispatch(new BusDispatcherBasicCommand);
}

public function testDispatcherCanDispatchStandAloneHandler()
{
$container = new Container;
$mock = m::mock('Illuminate\Contracts\Queue\Queue');
$dispatcher = new Dispatcher($container, function () use ($mock) {
return $mock;
});

$dispatcher->map(StandAloneCommand::class, StandAloneHandler::class);

$response = $dispatcher->dispatch(new StandAloneCommand);

$this->assertInstanceOf(StandAloneCommand::class, $response);
}
}

class BusInjectionStub
Expand Down Expand Up @@ -95,3 +110,15 @@ class BusDispatcherTestSpecificQueueAndDelayCommand implements Illuminate\Contra
public $queue = 'foo';
public $delay = 10;
}

class StandAloneCommand
{
}

class StandAloneHandler
{
public function handle(StandAloneCommand $command)
{
return $command;
}
}