Ask::autocomplete()   D
last analyzed

Complexity

Conditions 25
Paths 18

Size

Total Lines 91
Code Lines 57

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 650

Importance

Changes 0
Metric Value
cc 25
eloc 57
nc 18
nop 1
dl 0
loc 91
ccs 0
cts 56
cp 0
crap 650
rs 4.1666
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
// +----------------------------------------------------------------------
3
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
6
// +----------------------------------------------------------------------
7
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
8
// +----------------------------------------------------------------------
9
// | Author: yunwuxin <[email protected]>
10
// +----------------------------------------------------------------------
11
12
namespace think\console\output;
13
14
use think\console\Input;
15
use think\console\Output;
16
use think\console\output\question\Choice;
17
use think\console\output\question\Confirmation;
18
19
class Ask
20
{
21
    private static $stty;
22
23
    private static $shell;
24
25
    /** @var  Input */
26
    protected $input;
27
28
    /** @var  Output */
29
    protected $output;
30
31
    /** @var  Question */
32
    protected $question;
33
34
    public function __construct(Input $input, Output $output, Question $question)
35
    {
36
        $this->input    = $input;
37
        $this->output   = $output;
38
        $this->question = $question;
39
    }
40
41
    public function run()
42
    {
43
        if (!$this->input->isInteractive()) {
44
            return $this->question->getDefault();
45
        }
46
47
        if (!$this->question->getValidator()) {
48
            return $this->doAsk();
49
        }
50
51
        $that = $this;
52
53
        $interviewer = function () use ($that) {
54
            return $that->doAsk();
55
        };
56
57
        return $this->validateAttempts($interviewer);
58
    }
59
60
    protected function doAsk()
61
    {
62
        $this->writePrompt();
63
64
        $inputStream  = STDIN;
65
        $autocomplete = $this->question->getAutocompleterValues();
66
67
        if (null === $autocomplete || !$this->hasSttyAvailable()) {
68
            $ret = false;
69
            if ($this->question->isHidden()) {
70
                try {
71
                    $ret = trim($this->getHiddenResponse($inputStream));
72
                } catch (\RuntimeException $e) {
73
                    if (!$this->question->isHiddenFallback()) {
74
                        throw $e;
75
                    }
76
                }
77
            }
78
79
            if (false === $ret) {
80
                $ret = fgets($inputStream, 4096);
81
                if (false === $ret) {
82
                    throw new \RuntimeException('Aborted');
83
                }
84
                $ret = trim($ret);
85
            }
86
        } else {
87
            $ret = trim($this->autocomplete($inputStream));
88
        }
89
90
        $ret = strlen($ret) > 0 ? $ret : $this->question->getDefault();
91
92
        if ($normalizer = $this->question->getNormalizer()) {
93
            return $normalizer($ret);
94
        }
95
96
        return $ret;
97
    }
98
99
    private function autocomplete($inputStream)
100
    {
101
        $autocomplete = $this->question->getAutocompleterValues();
102
        $ret          = '';
103
104
        $i          = 0;
105
        $ofs        = -1;
106
        $matches    = $autocomplete;
107
        $numMatches = count($matches);
0 ignored issues
show
Bug introduced by
It seems like $matches can also be of type Traversable and null; however, parameter $value of count() does only seem to accept Countable|array, maybe add an additional type check? ( Ignorable by Annotation )

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

107
        $numMatches = count(/** @scrutinizer ignore-type */ $matches);
Loading history...
108
109
        $sttyMode = shell_exec('stty -g');
110
111
        shell_exec('stty -icanon -echo');
112
113
        while (!feof($inputStream)) {
114
            $c = fread($inputStream, 1);
115
116
            if ("\177" === $c) {
117
                if (0 === $numMatches && 0 !== $i) {
118
                    --$i;
119
                    $this->output->write("\033[1D");
120
                }
121
122
                if ($i === 0) {
123
                    $ofs        = -1;
124
                    $matches    = $autocomplete;
125
                    $numMatches = count($matches);
126
                } else {
127
                    $numMatches = 0;
128
                }
129
130
                $ret = substr($ret, 0, $i);
131
            } elseif ("\033" === $c) {
132
                $c .= fread($inputStream, 2);
133
134
                if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
135
                    if ('A' === $c[2] && -1 === $ofs) {
136
                        $ofs = 0;
137
                    }
138
139
                    if (0 === $numMatches) {
140
                        continue;
141
                    }
142
143
                    $ofs += ('A' === $c[2]) ? -1 : 1;
144
                    $ofs = ($numMatches + $ofs) % $numMatches;
145
                }
146
            } elseif (ord($c) < 32) {
147
                if ("\t" === $c || "\n" === $c) {
148
                    if ($numMatches > 0 && -1 !== $ofs) {
149
                        $ret = $matches[$ofs];
150
                        $this->output->write(substr($ret, $i));
151
                        $i = strlen($ret);
152
                    }
153
154
                    if ("\n" === $c) {
155
                        $this->output->write($c);
156
                        break;
157
                    }
158
159
                    $numMatches = 0;
160
                }
161
162
                continue;
163
            } else {
164
                $this->output->write($c);
165
                $ret .= $c;
166
                ++$i;
167
168
                $numMatches = 0;
169
                $ofs        = 0;
170
171
                foreach ($autocomplete as $value) {
172
                    if (0 === strpos($value, $ret) && $i !== strlen($value)) {
173
                        $matches[$numMatches++] = $value;
174
                    }
175
                }
176
            }
177
178
            $this->output->write("\033[K");
179
180
            if ($numMatches > 0 && -1 !== $ofs) {
181
                $this->output->write("\0337");
182
                $this->output->highlight(substr($matches[$ofs], $i));
183
                $this->output->write("\0338");
184
            }
185
        }
186
187
        shell_exec(sprintf('stty %s', $sttyMode));
188
189
        return $ret;
190
    }
191
192
    protected function getHiddenResponse($inputStream)
193
    {
194
        if ('\\' === DIRECTORY_SEPARATOR) {
195
            $exe = __DIR__ . '/../bin/hiddeninput.exe';
196
197
            $value = rtrim(shell_exec($exe));
198
            $this->output->writeln('');
199
200
            return $value;
201
        }
202
203
        if ($this->hasSttyAvailable()) {
204
            $sttyMode = shell_exec('stty -g');
205
206
            shell_exec('stty -echo');
207
            $value = fgets($inputStream, 4096);
208
            shell_exec(sprintf('stty %s', $sttyMode));
209
210
            if (false === $value) {
211
                throw new \RuntimeException('Aborted');
212
            }
213
214
            $value = trim($value);
215
            $this->output->writeln('');
216
217
            return $value;
218
        }
219
220
        if (false !== $shell = $this->getShell()) {
221
            $readCmd = $shell === 'csh' ? 'set mypassword = $<' : 'read -r mypassword';
222
            $command = sprintf("/usr/bin/env %s -c 'stty -echo; %s; stty echo; echo \$mypassword'", $shell, $readCmd);
223
            $value   = rtrim(shell_exec($command));
224
            $this->output->writeln('');
225
226
            return $value;
227
        }
228
229
        throw new \RuntimeException('Unable to hide the response.');
230
    }
231
232
    protected function validateAttempts($interviewer)
233
    {
234
        /** @var \Exception $error */
235
        $error    = null;
236
        $attempts = $this->question->getMaxAttempts();
237
        while (null === $attempts || $attempts--) {
238
            if (null !== $error) {
239
                $this->output->error($error->getMessage());
240
            }
241
242
            try {
243
                return call_user_func($this->question->getValidator(), $interviewer());
0 ignored issues
show
Bug introduced by
It seems like $this->question->getValidator() can also be of type null; however, parameter $callback of call_user_func() does only seem to accept callable, maybe add an additional type check? ( Ignorable by Annotation )

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

243
                return call_user_func(/** @scrutinizer ignore-type */ $this->question->getValidator(), $interviewer());
Loading history...
244
            } catch (\Exception $error) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
245
            }
246
        }
247
248
        throw $error;
249
    }
250
251
    /**
252
     * 显示问题的提示信息
253
     */
254
    protected function writePrompt()
255
    {
256
        $text    = $this->question->getQuestion();
257
        $default = $this->question->getDefault();
258
259
        switch (true) {
260
            case null === $default:
261
                $text = sprintf(' <info>%s</info>:', $text);
262
263
                break;
264
265
            case $this->question instanceof Confirmation:
266
                $text = sprintf(' <info>%s (yes/no)</info> [<comment>%s</comment>]:', $text, $default ? 'yes' : 'no');
267
268
                break;
269
270
            case $this->question instanceof Choice && $this->question->isMultiselect():
271
                $choices = $this->question->getChoices();
0 ignored issues
show
Bug introduced by
The method getChoices() does not exist on think\console\output\Question. It seems like you code against a sub-type of think\console\output\Question such as think\console\output\question\Choice. ( Ignorable by Annotation )

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

271
                /** @scrutinizer ignore-call */ 
272
                $choices = $this->question->getChoices();
Loading history...
272
                $default = explode(',', $default);
273
274
                foreach ($default as $key => $value) {
275
                    $default[$key] = $choices[trim($value)];
276
                }
277
278
                $text = sprintf(' <info>%s</info> [<comment>%s</comment>]:', $text, implode(', ', $default));
279
280
                break;
281
282
            case $this->question instanceof Choice:
283
                $choices = $this->question->getChoices();
284
                $text    = sprintf(' <info>%s</info> [<comment>%s</comment>]:', $text, $choices[$default]);
285
286
                break;
287
288
            default:
289
                $text = sprintf(' <info>%s</info> [<comment>%s</comment>]:', $text, $default);
290
        }
291
292
        $this->output->writeln($text);
293
294
        if ($this->question instanceof Choice) {
295
            $width = max(array_map('strlen', array_keys($this->question->getChoices())));
296
297
            foreach ($this->question->getChoices() as $key => $value) {
298
                $this->output->writeln(sprintf("  [<comment>%-{$width}s</comment>] %s", $key, $value));
299
            }
300
        }
301
302
        $this->output->write(' > ');
303
    }
304
305
    private function getShell()
306
    {
307
        if (null !== self::$shell) {
308
            return self::$shell;
309
        }
310
311
        self::$shell = false;
312
313
        if (file_exists('/usr/bin/env')) {
314
            $test = "/usr/bin/env %s -c 'echo OK' 2> /dev/null";
315
            foreach (['bash', 'zsh', 'ksh', 'csh'] as $sh) {
316
                if ('OK' === rtrim(shell_exec(sprintf($test, $sh)))) {
317
                    self::$shell = $sh;
318
                    break;
319
                }
320
            }
321
        }
322
323
        return self::$shell;
324
    }
325
326
    private function hasSttyAvailable()
327
    {
328
        if (null !== self::$stty) {
329
            return self::$stty;
330
        }
331
332
        exec('stty 2>&1', $output, $exitcode);
333
334
        return self::$stty = $exitcode === 0;
335
    }
336
}
337