FactoryCommandLoader.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. /**
  29. * {@inheritdoc}
  30. */
  31. public function has(string $name): bool
  32. {
  33. return isset($this->factories[$name]);
  34. }
  35. /**
  36. * {@inheritdoc}
  37. */
  38. public function get(string $name): Command
  39. {
  40. if (!isset($this->factories[$name])) {
  41. throw new CommandNotFoundException(sprintf('Command "%s" does not exist.', $name));
  42. }
  43. $factory = $this->factories[$name];
  44. return $factory();
  45. }
  46. /**
  47. * {@inheritdoc}
  48. */
  49. public function getNames(): array
  50. {
  51. return array_keys($this->factories);
  52. }
  53. }