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