1<?php
2
3/*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Symfony\Component\Console;
13
14use Symfony\Component\Console\Command\Command;
15use Symfony\Component\Console\Input\InputInterface;
16use Symfony\Component\Console\Output\OutputInterface;
17
18/**
19 * @author Grégoire Pineau <lyrixx@lyrixx.info>
20 */
21class SingleCommandApplication extends Command
22{
23    private $version = 'UNKNOWN';
24    private $autoExit = true;
25    private $running = false;
26
27    public function setVersion(string $version): self
28    {
29        $this->version = $version;
30
31        return $this;
32    }
33
34    /**
35     * @final
36     */
37    public function setAutoExit(bool $autoExit): self
38    {
39        $this->autoExit = $autoExit;
40
41        return $this;
42    }
43
44    public function run(InputInterface $input = null, OutputInterface $output = null): int
45    {
46        if ($this->running) {
47            return parent::run($input, $output);
48        }
49
50        // We use the command name as the application name
51        $application = new Application($this->getName() ?: 'UNKNOWN', $this->version);
52        $application->setAutoExit($this->autoExit);
53        // Fix the usage of the command displayed with "--help"
54        $this->setName($_SERVER['argv'][0]);
55        $application->add($this);
56        $application->setDefaultCommand($this->getName(), true);
57
58        $this->running = true;
59        try {
60            $ret = $application->run($input, $output);
61        } finally {
62            $this->running = false;
63        }
64
65        return $ret ?? 1;
66    }
67}
68