FactoryCommandLoader.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. private array $factories;
  21. /**
  22. * @param callable[] $factories Indexed by command names
  23. */
  24. public function __construct(array $factories)
  25. {
  26. $this->factories = $factories;
  27. }
  28. public function has(string $name): bool
  29. {
  30. return isset($this->factories[$name]);
  31. }
  32. public function get(string $name): Command
  33. {
  34. if (!isset($this->factories[$name])) {
  35. throw new CommandNotFoundException(sprintf('Command "%s" does not exist.', $name));
  36. }
  37. $factory = $this->factories[$name];
  38. return $factory();
  39. }
  40. public function getNames(): array
  41. {
  42. return array_keys($this->factories);
  43. }
  44. }