ContainerCommandLoader.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. * @param array $commandMap An array with command names as keys and service ids as values
  23. */
  24. public function __construct(
  25. private ContainerInterface $container,
  26. private array $commandMap,
  27. ) {
  28. }
  29. public function get(string $name): Command
  30. {
  31. if (!$this->has($name)) {
  32. throw new CommandNotFoundException(\sprintf('Command "%s" does not exist.', $name));
  33. }
  34. return $this->container->get($this->commandMap[$name]);
  35. }
  36. public function has(string $name): bool
  37. {
  38. return isset($this->commandMap[$name]) && $this->container->has($this->commandMap[$name]);
  39. }
  40. public function getNames(): array
  41. {
  42. return array_keys($this->commandMap);
  43. }
  44. }