FactoryCommandLoader.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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($name)
  31. {
  32. return isset($this->factories[$name]);
  33. }
  34. /**
  35. * {@inheritdoc}
  36. */
  37. public function get($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. }