Skip to content

Instantly share code, notes, and snippets.

@guiwoda
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guiwoda/331c058a66ea8441583c to your computer and use it in GitHub Desktop.
Save guiwoda/331c058a66ea8441583c to your computer and use it in GitHub Desktop.
Expectation in Commands
<?php
use Laracasts\Commander\CommandBus;
class ExpectationCommandBus implements CommandBus
{
/*
* Constructor injects the resolver...
*/
protected $expectationResolver;
public function execute($command, array $expectations)
{
$this->executeDecorators($command);
$handler = $this->commandTranslator->toCommandHandler($command);
$output = $this->app->make($handler)->handle($command);
return $this->expectationResolver->resolve($expectations, $output);
}
}
<?php
class ExpectationResolver
{
public function resolve(array $expectations, array $output)
{
$resolvedExpectations = [];
foreach ($expectations as $key => $expectedClass)
{
$resolvedExpectations[$key] = $this->resolveExpectation($expectedClass, $output);
}
return $resolvedExpectations;
}
protected function resolveExpectation($expectedClass, array $output)
{
foreach ($output as $potentialResolver)
{
if ($potentialResolver instanceof $expectedClass)
{
return $potentialResolver;
}
}
throw new UnresolvedExpectationException("Unable to resolve expectation $expectedClass");
}
}
<?php
class FooController
{
use CommanderTrait;
public function index()
{
$resolvedExpectations = $this->execute(
JobListingCommand::class,
[
'aLoggedUser' => User::class,
'aJobCollection' => JobCollection::class,
'aBarBaz' => BarBaz::class
]
);
return View::make('foo.index', $resolvedExpectations);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment