SingleCommandApplication.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. /**
  23. * @return $this
  24. */
  25. public function setVersion(string $version): self
  26. {
  27. $this->version = $version;
  28. return $this;
  29. }
  30. /**
  31. * @final
  32. *
  33. * @return $this
  34. */
  35. public function setAutoExit(bool $autoExit): self
  36. {
  37. $this->autoExit = $autoExit;
  38. return $this;
  39. }
  40. public function run(InputInterface $input = null, OutputInterface $output = null): int
  41. {
  42. if ($this->running) {
  43. return parent::run($input, $output);
  44. }
  45. // We use the command name as the application name
  46. $application = new Application($this->getName() ?: 'UNKNOWN', $this->version);
  47. $application->setAutoExit($this->autoExit);
  48. // Fix the usage of the command displayed with "--help"
  49. $this->setName($_SERVER['argv'][0]);
  50. $application->add($this);
  51. $application->setDefaultCommand($this->getName(), true);
  52. $this->running = true;
  53. try {
  54. $ret = $application->run($input, $output);
  55. } finally {
  56. $this->running = false;
  57. }
  58. return $ret ?? 1;
  59. }
  60. }