SingleCommandApplication.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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;
  11. use Symfony\Component\Console\Command\Command;
  12. use Symfony\Component\Console\Input\InputInterface;
  13. use Symfony\Component\Console\Output\OutputInterface;
  14. /**
  15. * @author Grégoire Pineau <lyrixx@lyrixx.info>
  16. */
  17. class SingleCommandApplication extends Command
  18. {
  19. private $version = 'UNKNOWN';
  20. private $autoExit = true;
  21. private $running = false;
  22. public function setVersion(string $version): self
  23. {
  24. $this->version = $version;
  25. return $this;
  26. }
  27. /**
  28. * @final
  29. */
  30. public function setAutoExit(bool $autoExit): self
  31. {
  32. $this->autoExit = $autoExit;
  33. return $this;
  34. }
  35. public function run(InputInterface $input = null, OutputInterface $output = null): int
  36. {
  37. if ($this->running) {
  38. return parent::run($input, $output);
  39. }
  40. // We use the command name as the application name
  41. $application = new Application($this->getName() ?: 'UNKNOWN', $this->version);
  42. $application->setAutoExit($this->autoExit);
  43. // Fix the usage of the command displayed with "--help"
  44. $this->setName($_SERVER['argv'][0]);
  45. $application->add($this);
  46. $application->setDefaultCommand($this->getName(), true);
  47. $this->running = true;
  48. try {
  49. $ret = $application->run($input, $output);
  50. } finally {
  51. $this->running = false;
  52. }
  53. return $ret ?? 1;
  54. }
  55. }