You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.3 KiB

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