ContainerCommandLoader.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace Symfony\Component\Console\CommandLoader;
  3. use Psr\Container\ContainerInterface;
  4. use Symfony\Component\Console\Exception\CommandNotFoundException;
  5. /**
  6. * Loads commands from a PSR-11 container.
  7. *
  8. * @author Robin Chalas <robin.chalas@gmail.com>
  9. */
  10. class ContainerCommandLoader implements CommandLoaderInterface
  11. {
  12. private $container;
  13. private $commandMap;
  14. /**
  15. * @param ContainerInterface $container A container from which to load command services
  16. * @param array $commandMap An array with command names as keys and service ids as values
  17. */
  18. public function __construct(ContainerInterface $container, array $commandMap)
  19. {
  20. $this->container = $container;
  21. $this->commandMap = $commandMap;
  22. }
  23. /**
  24. * {@inheritdoc}
  25. */
  26. public function get($name)
  27. {
  28. if (!$this->has($name)) {
  29. throw new CommandNotFoundException(sprintf('Command "%s" does not exist.', $name));
  30. }
  31. return $this->container->get($this->commandMap[$name]);
  32. }
  33. /**
  34. * {@inheritdoc}
  35. */
  36. public function has($name)
  37. {
  38. return isset($this->commandMap[$name]) && $this->container->has($this->commandMap[$name]);
  39. }
  40. /**
  41. * {@inheritdoc}
  42. */
  43. public function getNames()
  44. {
  45. return array_keys($this->commandMap);
  46. }
  47. }