FactoryCommandLoader.php 1.2 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 Symfony\Component\Console\Command\Command;
  12. use Symfony\Component\Console\Exception\CommandNotFoundException;
  13. /**
  14. * A simple command loader using factories to instantiate commands lazily.
  15. *
  16. * @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
  17. */
  18. class FactoryCommandLoader implements CommandLoaderInterface
  19. {
  20. /**
  21. * @param callable[] $factories Indexed by command names
  22. */
  23. public function __construct(
  24. private array $factories,
  25. ) {
  26. }
  27. public function has(string $name): bool
  28. {
  29. return isset($this->factories[$name]);
  30. }
  31. public function get(string $name): Command
  32. {
  33. if (!isset($this->factories[$name])) {
  34. throw new CommandNotFoundException(\sprintf('Command "%s" does not exist.', $name));
  35. }
  36. $factory = $this->factories[$name];
  37. return $factory();
  38. }
  39. public function getNames(): array
  40. {
  41. return array_keys($this->factories);
  42. }
  43. }