1<?php 2 3namespace League\Tactician\Handler\Locator; 4 5use League\Tactician\Exception\MissingHandlerException; 6 7/** 8 * Fetch handler instances from an in-memory collection. 9 * 10 * This locator allows you to bind a handler object to receive commands of a 11 * certain class name. For example: 12 * 13 * // Wire everything together 14 * $myHandler = new TaskAddedHandler($dependency1, $dependency2); 15 * $inMemoryLocator->addHandler($myHandler, 'My\TaskAddedCommand'); 16 * 17 * // Returns $myHandler 18 * $inMemoryLocator->getHandlerForCommand('My\TaskAddedCommand'); 19 */ 20class InMemoryLocator implements HandlerLocator 21{ 22 /** 23 * @var object[] 24 */ 25 protected $handlers = []; 26 27 /** 28 * @param array $commandClassToHandlerMap 29 */ 30 public function __construct(array $commandClassToHandlerMap = []) 31 { 32 $this->addHandlers($commandClassToHandlerMap); 33 } 34 35 /** 36 * Bind a handler instance to receive all commands with a certain class 37 * 38 * @param object $handler Handler to receive class 39 * @param string $commandClassName Command class e.g. "My\TaskAddedCommand" 40 */ 41 public function addHandler($handler, $commandClassName) 42 { 43 $this->handlers[$commandClassName] = $handler; 44 } 45 46 /** 47 * Allows you to add multiple handlers at once. 48 * 49 * The map should be an array in the format of: 50 * [ 51 * AddTaskCommand::class => $someHandlerInstance, 52 * CompleteTaskCommand::class => $someHandlerInstance, 53 * ] 54 * 55 * @param array $commandClassToHandlerMap 56 */ 57 protected function addHandlers(array $commandClassToHandlerMap) 58 { 59 foreach ($commandClassToHandlerMap as $commandClass => $handler) { 60 $this->addHandler($handler, $commandClass); 61 } 62 } 63 64 /** 65 * Returns the handler bound to the command's class name. 66 * 67 * @param string $commandName 68 * 69 * @return object 70 */ 71 public function getHandlerForCommand($commandName) 72 { 73 if (!isset($this->handlers[$commandName])) { 74 throw MissingHandlerException::forCommand($commandName); 75 } 76 77 return $this->handlers[$commandName]; 78 } 79} 80