ContainerCommandLoader.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Console\CommandLoader;
  11. use Psr\Container\ContainerInterface;
  12. use Symfony\Component\Console\Command\Command;
  13. use Symfony\Component\Console\Exception\CommandNotFoundException;
  14. /**
  15. * Loads commands from a PSR-11 container.
  16. *
  17. * @author Robin Chalas <robin.chalas@gmail.com>
  18. */
  19. class ContainerCommandLoader implements CommandLoaderInterface
  20. {
  21. /**
  22. * @var \Psr\Container\ContainerInterface
  23. */
  24. private $container;
  25. /**
  26. * @var mixed[]
  27. */
  28. private $commandMap;
  29. /**
  30. * @param array $commandMap An array with command names as keys and service ids as values
  31. * @param \Psr\Container\ContainerInterface $container
  32. */
  33. public function __construct($container, $commandMap)
  34. {
  35. $this->container = $container;
  36. $this->commandMap = $commandMap;
  37. }
  38. /**
  39. * @param string $name
  40. */
  41. public function get($name)
  42. {
  43. if (!$this->has($name)) {
  44. throw new CommandNotFoundException(sprintf('Command "%s" does not exist.', $name));
  45. }
  46. return $this->container->get($this->commandMap[$name]);
  47. }
  48. /**
  49. * @param string $name
  50. */
  51. public function has($name)
  52. {
  53. return isset($this->commandMap[$name]) && $this->container->has($this->commandMap[$name]);
  54. }
  55. public function getNames()
  56. {
  57. return array_keys($this->commandMap);
  58. }
  59. }