Completed
Pull Request — master (#9)
by ANTHONIUS
02:18
created

Shell::getOutput()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
c 0
b 0
f 0
rs 10
cc 1
eloc 1
nc 1
nop 0
1
<?php
2
3
/*
4
 * This file is part of the dotfiles project.
5
 *
6
 *     (c) Anthonius Munthi <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Dotfiles\Core\Console;
13
14
use Symfony\Component\Console\Exception\RuntimeException;
15
use Symfony\Component\Console\Input\StringInput;
16
use Symfony\Component\Console\Output\ConsoleOutput;
17
use Symfony\Component\Process\PhpExecutableFinder;
18
use Symfony\Component\Process\ProcessBuilder;
0 ignored issues
show
Bug introduced by
The type Symfony\Component\Process\ProcessBuilder was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
19
20
/**
21
 * A Shell wraps an Application to add shell capabilities to it.
22
 *
23
 * Support for history and completion only works with a PHP compiled
24
 * with readline support (either --with-readline or --with-libedit)
25
 *
26
 * This class copied directly from symfony console 2.8 component ;-)
27
 *
28
 * @author Fabien Potencier <[email protected]>
29
 * @author Martin Hasoň <[email protected]>
30
 * @author Anthonius Munthi <[email protected]>
31
 */
32
class Shell
33
{
34
    private $application;
35
    private $hasReadline;
36
    private $history;
37
    private $output;
38
    private $processIsolation = false;
39
40
    /**
41
     * If there is no readline support for the current PHP executable
42
     * a \RuntimeException exception is thrown.
43
     */
44
    public function __construct(Application $application)
45
    {
46
        $this->hasReadline = function_exists('readline');
47
        $this->application = $application;
48
        $this->history = getenv('HOME').'/.history_'.$application->getName();
49
        $this->output = new ConsoleOutput();
50
    }
51
52
    public function getProcessIsolation()
53
    {
54
        return $this->processIsolation;
55
    }
56
57
    /**
58
     * Runs the shell.
59
     */
60
    public function run()
61
    {
62
        $this->application->setAutoExit(false);
63
        $this->application->setCatchExceptions(true);
64
65
        if ($this->hasReadline) {
66
            readline_read_history($this->history);
67
            readline_completion_function(array($this, 'autocompleter'));
68
        }
69
70
        $this->output->writeln($this->getHeader());
71
        $php = null;
72
        if ($this->processIsolation) {
73
            $finder = new PhpExecutableFinder();
74
            $php = $finder->find();
75
            $this->output->writeln(
76
                <<<'EOF'
77
<info>Running with process isolation, you should consider this:</info>
78
  * each command is executed as separate process,
79
  * commands don't support interactivity, all params must be passed explicitly,
80
  * commands output is not colorized.
81
82
EOF
83
            );
84
        }
85
86
        while (true) {
87
            $command = $this->readline();
88
89
            if (false === $command) {
90
                $this->output->writeln("\n");
91
92
                break;
93
            }
94
95
            if ($this->hasReadline) {
96
                readline_add_history($command);
97
                readline_write_history($this->history);
98
            }
99
100
            if ($this->processIsolation) {
101
                $pb = new ProcessBuilder();
102
103
                $process = $pb
104
                    ->add($php)
105
                    ->add($_SERVER['argv'][0])
106
                    ->add($command)
107
                    ->inheritEnvironmentVariables(true)
108
                    ->getProcess()
109
                ;
110
111
                $output = $this->output;
112
                $process->run(function ($type, $data) use ($output) {
113
                    $output->writeln($data);
114
                });
115
116
                $ret = $process->getExitCode();
117
            } else {
118
                $ret = $this->application->run(new StringInput($command), $this->output);
119
            }
120
121
            if (0 !== $ret) {
122
                $this->output->writeln(sprintf('<error>The command terminated with an error status (%s)</error>', $ret));
123
            }
124
        }
125
    }
126
127
    public function setProcessIsolation($processIsolation)
128
    {
129
        $this->processIsolation = (bool) $processIsolation;
130
131
        if ($this->processIsolation && !class_exists('Symfony\\Component\\Process\\Process')) {
132
            throw new RuntimeException('Unable to isolate processes as the Symfony Process Component is not installed.');
133
        }
134
    }
135
136
    protected function getApplication()
137
    {
138
        return $this->application;
139
    }
140
141
    /**
142
     * Returns the shell header.
143
     *
144
     * @return string The header string
145
     */
146
    protected function getHeader()
147
    {
148
        return <<<EOF
149
150
Welcome to the <info>{$this->application->getName()}</info> shell (<comment>{$this->application->getVersion()}</comment>).
151
152
At the prompt, type <comment>help</comment> for some help,
153
or <comment>list</comment> to get a list of available commands.
154
155
To exit the shell, type <comment>^D</comment>.
156
157
EOF;
158
    }
159
160
    protected function getOutput()
161
    {
162
        return $this->output;
163
    }
164
165
    /**
166
     * Renders a prompt.
167
     *
168
     * @return string The prompt
169
     */
170
    protected function getPrompt()
171
    {
172
        // using the formatter here is required when using readline
173
        return $this->output->getFormatter()->format($this->application->getName().'>> ');
174
    }
175
176
    /**
177
     * Tries to return autocompletion for the current entered text.
178
     *
179
     * @param string $text The last segment of the entered text
180
     *
181
     * @return bool|array A list of guessed strings or true
182
     */
183
    private function autocompleter($text)
0 ignored issues
show
Unused Code introduced by
The parameter $text is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

183
    private function autocompleter(/** @scrutinizer ignore-unused */ $text)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
184
    {
185
        $info = readline_info();
186
        $text = substr($info['line_buffer'], 0, $info['end']);
187
188
        if ($info['point'] !== $info['end']) {
189
            return true;
190
        }
191
192
        // task name?
193
        if (false === strpos($text, ' ') || !$text) {
194
            return array_keys($this->application->all());
195
        }
196
197
        // options and arguments?
198
        try {
199
            $command = $this->application->find(substr($text, 0, strpos($text, ' ')));
200
        } catch (\Exception $e) {
201
            return true;
202
        }
203
204
        $list = array('--help');
205
        foreach ($command->getDefinition()->getOptions() as $option) {
206
            $list[] = '--'.$option->getName();
207
        }
208
209
        return $list;
210
    }
211
212
    /**
213
     * Reads a single line from standard input.
214
     *
215
     * @return string The single line from standard input
216
     */
217
    private function readline()
218
    {
219
        if ($this->hasReadline) {
220
            $line = readline($this->getPrompt());
221
        } else {
222
            $this->output->write($this->getPrompt());
223
            $line = fgets(STDIN, 1024);
224
            $line = (false === $line || '' === $line) ? false : rtrim($line);
225
        }
226
227
        return $line;
228
    }
229
}
230