ContainerCommandLoader.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. private ContainerInterface $container;
  22. private array $commandMap;
  23. /**
  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. public function get(string $name): Command
  32. {
  33. if (!$this->has($name)) {
  34. throw new CommandNotFoundException(sprintf('Command "%s" does not exist.', $name));
  35. }
  36. return $this->container->get($this->commandMap[$name]);
  37. }
  38. public function has(string $name): bool
  39. {
  40. return isset($this->commandMap[$name]) && $this->container->has($this->commandMap[$name]);
  41. }
  42. public function getNames(): array
  43. {
  44. return array_keys($this->commandMap);
  45. }
  46. }