Passed
Pull Request — master (#9)
by ANTHONIUS
02:11
created

Shell::setProcessIsolation()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
c 0
b 0
f 0
rs 9.4285
cc 3
eloc 3
nc 2
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 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
36
    private $hasReadline;
37
38
    private $history;
39
40
    private $output;
41
42
    private $processIsolation = false;
43
44
    /**
45
     * If there is no readline support for the current PHP executable
46
     * a \RuntimeException exception is thrown.
47
     */
48
    public function __construct(Application $application)
49
    {
50
        $this->hasReadline = function_exists('readline');
51
        $this->application = $application;
52
        $this->history = getenv('HOME').'/.history_'.$application->getName();
53
        $this->output = new ConsoleOutput();
54
    }
55
56
    public function getProcessIsolation()
57
    {
58
        return $this->processIsolation;
59
    }
60
61
    /**
62
     * Runs the shell.
63
     */
64
    public function run()
65
    {
66
        $this->application->setAutoExit(false);
67
        $this->application->setCatchExceptions(true);
68
69
        if ($this->hasReadline) {
70
            readline_read_history($this->history);
71
            readline_completion_function(array($this, 'autocompleter'));
72
        }
73
74
        $this->output->writeln($this->getHeader());
75
        $php = null;
76
        if ($this->processIsolation) {
77
            $finder = new PhpExecutableFinder();
78
            $php = $finder->find();
79
            $this->output->writeln(
80
                <<<'EOF'
81
<info>Running with process isolation, you should consider this:</info>
82
  * each command is executed as separate process,
83
  * commands don't support interactivity, all params must be passed explicitly,
84
  * commands output is not colorized.
85
86
EOF
87
            );
88
        }
89
90
        while (true) {
91
            $command = $this->readline();
92
93
            if (false === $command) {
94
                $this->output->writeln("\n");
95
96
                break;
97
            }
98
99
            if ($this->hasReadline) {
100
                readline_add_history($command);
101
                readline_write_history($this->history);
102
            }
103
104
            if ($this->processIsolation) {
105
                $pb = new ProcessBuilder();
106
107
                $process = $pb
108
                    ->add($php)
109
                    ->add($_SERVER['argv'][0])
110
                    ->add($command)
111
                    ->inheritEnvironmentVariables(true)
112
                    ->getProcess()
113
                ;
114
115
                $output = $this->output;
116
                $process->run(function ($type, $data) use ($output) {
117
                    $output->writeln($data);
118
                });
119
120
                $ret = $process->getExitCode();
121
            } else {
122
                $ret = $this->application->run(new StringInput($command), $this->output);
123
            }
124
125
            if (0 !== $ret) {
126
                $this->output->writeln(sprintf('<error>The command terminated with an error status (%s)</error>', $ret));
127
            }
128
        }
129
    }
130
131
    public function setProcessIsolation($processIsolation)
132
    {
133
        $this->processIsolation = (bool) $processIsolation;
134
135
        if ($this->processIsolation && !class_exists('Symfony\\Component\\Process\\Process')) {
136
            throw new RuntimeException('Unable to isolate processes as the Symfony Process Component is not installed.');
137
        }
138
    }
139
140
    protected function getApplication()
141
    {
142
        return $this->application;
143
    }
144
145
    /**
146
     * Returns the shell header.
147
     *
148
     * @return string The header string
149
     */
150
    protected function getHeader()
151
    {
152
        return <<<EOF
153
154
Welcome to the <info>{$this->application->getName()}</info> shell (<comment>{$this->application->getVersion()}</comment>).
155
156
At the prompt, type <comment>help</comment> for some help,
157
or <comment>list</comment> to get a list of available commands.
158
159
To exit the shell, type <comment>^D</comment>.
160
161
EOF;
162
    }
163
164
    protected function getOutput()
165
    {
166
        return $this->output;
167
    }
168
169
    /**
170
     * Renders a prompt.
171
     *
172
     * @return string The prompt
173
     */
174
    protected function getPrompt()
175
    {
176
        // using the formatter here is required when using readline
177
        return $this->output->getFormatter()->format($this->application->getName().'>> ');
178
    }
179
180
    /**
181
     * Tries to return autocompletion for the current entered text.
182
     *
183
     * @param string $text The last segment of the entered text
184
     *
185
     * @return bool|array A list of guessed strings or true
186
     */
187
    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

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