ContainerCommandLoader.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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\Exception\CommandNotFoundException;
  13. /**
  14. * Loads commands from a PSR-11 container.
  15. *
  16. * @author Robin Chalas <robin.chalas@gmail.com>
  17. */
  18. class ContainerCommandLoader implements CommandLoaderInterface
  19. {
  20. private $container;
  21. private $commandMap;
  22. /**
  23. * @param ContainerInterface $container A container from which to load command services
  24. * @param array $commandMap An array with command names as keys and service ids as values
  25. */
  26. public function __construct(ContainerInterface $container, array $commandMap)
  27. {
  28. $this->container = $container;
  29. $this->commandMap = $commandMap;
  30. }
  31. /**
  32. * {@inheritdoc}
  33. */
  34. public function get($name)
  35. {
  36. if (!$this->has($name)) {
  37. throw new CommandNotFoundException(sprintf('Command "%s" does not exist.', $name));
  38. }
  39. return $this->container->get($this->commandMap[$name]);
  40. }
  41. /**
  42. * {@inheritdoc}
  43. */
  44. public function has($name)
  45. {
  46. return isset($this->commandMap[$name]) && $this->container->has($this->commandMap[$name]);
  47. }
  48. /**
  49. * {@inheritdoc}
  50. */
  51. public function getNames()
  52. {
  53. return array_keys($this->commandMap);
  54. }
  55. }