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

Shell::autocompleter()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 27
c 0
b 0
f 0
rs 8.439
cc 6
eloc 14
nc 5
nop 1
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 Dotfiles\Core\DI\Parameters;
15
use Symfony\Component\Console\Exception\RuntimeException;
16
use Symfony\Component\Console\Input\StringInput;
17
use Symfony\Component\Console\Output\ConsoleOutput;
18
use Symfony\Component\Process\PhpExecutableFinder;
19
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...
20
21
/**
22
 * A Shell wraps an Application to add shell capabilities to it.
23
 *
24
 * Support for history and completion only works with a PHP compiled
25
 * with readline support (either --with-readline or --with-libedit)
26
 *
27
 * This class copied directly from symfony console 2.8 component ;-)
28
 *
29
 * @author Fabien Potencier <[email protected]>
30
 * @author Martin Hasoň <[email protected]>
31
 * @author Anthonius Munthi <[email protected]>
32
 */
33
class Shell
34
{
35
    private $application;
36
37
    private $hasReadline;
38
39
    private $history;
40
41
    private $isRunning = false;
42
43
    private $output;
44
45
    /**
46
     * @var Parameters
47
     */
48
    private $parameters;
49
50
    private $processIsolation = false;
51
52
    /**
53
     * If there is no readline support for the current PHP executable
54
     * a \RuntimeException exception is thrown.
55
     */
56
    public function __construct(Application $application, Parameters $parameters)
57
    {
58
        $this->hasReadline = function_exists('readline');
59
        $this->application = $application;
60
        $this->history = getenv('HOME').'/.history_'.$application->getName();
61
        $this->output = new ConsoleOutput();
62
        $this->parameters = $parameters;
63
    }
64
65
    public function getProcessIsolation()
66
    {
67
        return $this->processIsolation;
68
    }
69
70
    public function run()
71
    {
72
        if (!$this->isRunning) {
73
            $this->isRunning = true;
74
            $this->doRun();
75
        } else {
76
            $input = new StringInput('list');
77
            $this->getApplication()->run($input);
78
        }
79
    }
80
81
    public function setProcessIsolation($processIsolation)
82
    {
83
        $this->processIsolation = (bool) $processIsolation;
84
85
        if ($this->processIsolation && !class_exists('Symfony\\Component\\Process\\Process')) {
86
            throw new RuntimeException('Unable to isolate processes as the Symfony Process Component is not installed.');
87
        }
88
    }
89
90
    protected function getApplication()
91
    {
92
        return $this->application;
93
    }
94
95
    /**
96
     * Returns the shell header.
97
     *
98
     * @return string The header string
99
     */
100
    protected function getHeader()
101
    {
102
        return <<<EOF
103
104
Welcome to the <info>{$this->application->getName()}</info> (<comment>{$this->application->getVersion()}</comment>).
105
106
At the prompt, type <comment>help</comment> for some help,
107
or <comment>list</comment> to get a list of available commands.
108
109
To exit the shell, type <comment>^D</comment>.
110
111
EOF;
112
    }
113
114
    protected function getOutput()
115
    {
116
        return $this->output;
117
    }
118
119
    /**
120
     * Renders a prompt.
121
     *
122
     * @return string The prompt
123
     */
124
    protected function getPrompt()
125
    {
126
        $prompt = $this->application->getName().'>> ';
127
128
        return $this->output->getFormatter()->format($prompt);
129
    }
130
131
    /**
132
     * Tries to return autocompletion for the current entered text.
133
     *
134
     * @param string $text The last segment of the entered text
135
     *
136
     * @return bool|array A list of guessed strings or true
137
     */
138
    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

138
    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...
139
    {
140
        $info = readline_info();
141
        $text = substr($info['line_buffer'], 0, $info['end']);
142
143
        if ($info['point'] !== $info['end']) {
144
            return true;
145
        }
146
147
        // task name?
148
        if (false === strpos($text, ' ') || !$text) {
149
            return array_keys($this->application->all());
150
        }
151
152
        // options and arguments?
153
        try {
154
            $command = $this->application->find(substr($text, 0, strpos($text, ' ')));
155
        } catch (\Exception $e) {
156
            return true;
157
        }
158
159
        $list = array('--help');
160
        foreach ($command->getDefinition()->getOptions() as $option) {
161
            $list[] = '--'.$option->getName();
162
        }
163
164
        return $list;
165
    }
166
167
    /**
168
     * Runs the shell.
169
     */
170
    private function doRun()
171
    {
172
        $this->application->setAutoExit(false);
173
        $this->application->setCatchExceptions(true);
174
175
        if ($this->hasReadline) {
176
            readline_read_history($this->history);
177
            readline_completion_function(array($this, 'autocompleter'));
178
        }
179
180
        $this->output->writeln($this->getHeader());
181
        $php = null;
182
        if ($this->processIsolation) {
183
            $finder = new PhpExecutableFinder();
184
            $php = $finder->find();
185
            $this->output->writeln(
186
                <<<'EOF'
187
<info>Running with process isolation, you should consider this:</info>
188
  * each command is executed as separate process,
189
  * commands don't support interactivity, all params must be passed explicitly,
190
  * commands output is not colorized.
191
192
EOF
193
            );
194
        }
195
196
        while (true) {
197
            $command = $this->readline();
198
199
            if (false === $command) {
200
                $this->output->writeln("\n");
201
202
                break;
203
            }
204
205
            if ($this->hasReadline) {
206
                readline_add_history($command);
207
                readline_write_history($this->history);
208
            }
209
210
            if ($this->processIsolation) {
211
                $pb = new ProcessBuilder();
212
213
                $process = $pb
214
                    ->add($php)
215
                    ->add($_SERVER['argv'][0])
216
                    ->add($command)
217
                    ->inheritEnvironmentVariables(true)
218
                    ->getProcess()
219
                ;
220
221
                $output = $this->output;
222
                $process->run(function ($type, $data) use ($output) {
223
                    $output->writeln($data);
224
                });
225
226
                $ret = $process->getExitCode();
227
            } else {
228
                $ret = $this->application->run(new StringInput($command), $this->output);
229
            }
230
231
            if (0 !== $ret) {
232
                $this->output->writeln(sprintf('<error>The command terminated with an error status (%s)</error>', $ret));
233
            }
234
        }
235
    }
236
237
    /**
238
     * Reads a single line from standard input.
239
     *
240
     * @return string The single line from standard input
241
     */
242
    private function readline()
243
    {
244
        if ($this->hasReadline) {
245
            $line = readline($this->getPrompt());
246
        } else {
247
            $this->output->write($this->getPrompt());
248
            $line = fgets(STDIN, 1024);
249
            $line = (false === $line || '' === $line) ? false : rtrim($line);
250
        }
251
252
        return $line;
253
    }
254
}
255