CallableLocator.php
55 lines
| 1 | <?php |
| 2 | namespace League\Tactician\Handler\Locator; |
| 3 | |
| 4 | use League\Tactician\Exception\MissingHandlerException; |
| 5 | |
| 6 | /** |
| 7 | * This locator loads Handlers from a provided callable. |
| 8 | * |
| 9 | * At first glance, this might seem fairly useless but it's actually very |
| 10 | * useful to encapsulate DI containers without having to write a custom adapter |
| 11 | * for each one. |
| 12 | * |
| 13 | * Let's say you have a Symfony container or similar that works via a 'get' |
| 14 | * method. You can pass in an array style callable such as: |
| 15 | * |
| 16 | * $locator = new CallableLocator([$container, 'get']) |
| 17 | * |
| 18 | * This is easy to set up and will now automatically pipe the command name |
| 19 | * straight through to the $container->get() method without having to write |
| 20 | * the custom locator. |
| 21 | * |
| 22 | * Naturally, you can also pass in closures for further behavior tweaks. |
| 23 | */ |
| 24 | class CallableLocator implements HandlerLocator |
| 25 | { |
| 26 | /** |
| 27 | * @var callable |
| 28 | */ |
| 29 | private $callable; |
| 30 | |
| 31 | /** |
| 32 | * @param callable $callable |
| 33 | */ |
| 34 | public function __construct(callable $callable) |
| 35 | { |
| 36 | $this->callable = $callable; |
| 37 | } |
| 38 | |
| 39 | /** |
| 40 | * {@inheritdoc} |
| 41 | */ |
| 42 | public function getHandlerForCommand($commandName) |
| 43 | { |
| 44 | $callable = $this->callable; |
| 45 | $handler = $callable($commandName); |
| 46 | |
| 47 | // Odds are the callable threw an exception but it always pays to check |
| 48 | if ($handler === null) { |
| 49 | throw MissingHandlerException::forCommand($commandName); |
| 50 | } |
| 51 | |
| 52 | return $handler; |
| 53 | } |
| 54 | } |
| 55 |