Total Complexity | 115 |
Total Lines | 570 |
Duplicated Lines | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
Complex classes like QuestionHelper often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use QuestionHelper, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
34 | class QuestionHelper extends Helper |
||
35 | { |
||
36 | private $inputStream; |
||
37 | private static $shell; |
||
|
|||
38 | private static $stty = true; |
||
39 | private static $stdinIsInteractive; |
||
40 | |||
41 | /** |
||
42 | * Asks a question to the user. |
||
43 | * |
||
44 | * @return mixed The user answer |
||
45 | * |
||
46 | * @throws RuntimeException If there is no data to read in the input stream |
||
47 | */ |
||
48 | public function ask(InputInterface $input, OutputInterface $output, Question $question) |
||
49 | { |
||
50 | if ($output instanceof ConsoleOutputInterface) { |
||
51 | $output = $output->getErrorOutput(); |
||
52 | } |
||
53 | |||
54 | if (!$input->isInteractive()) { |
||
55 | return $this->getDefaultAnswer($question); |
||
56 | } |
||
57 | |||
58 | if ($input instanceof StreamableInputInterface && $stream = $input->getStream()) { |
||
59 | $this->inputStream = $stream; |
||
60 | } |
||
61 | |||
62 | try { |
||
63 | if (!$question->getValidator()) { |
||
64 | return $this->doAsk($output, $question); |
||
65 | } |
||
66 | |||
67 | $interviewer = function () use ($output, $question) { |
||
68 | return $this->doAsk($output, $question); |
||
69 | }; |
||
70 | |||
71 | return $this->validateAttempts($interviewer, $output, $question); |
||
72 | } catch (MissingInputException $exception) { |
||
73 | $input->setInteractive(false); |
||
74 | |||
75 | if (null === $fallbackOutput = $this->getDefaultAnswer($question)) { |
||
76 | throw $exception; |
||
77 | } |
||
78 | |||
79 | return $fallbackOutput; |
||
80 | } |
||
81 | } |
||
82 | |||
83 | /** |
||
84 | * {@inheritdoc} |
||
85 | */ |
||
86 | public function getName() |
||
87 | { |
||
88 | return 'question'; |
||
89 | } |
||
90 | |||
91 | /** |
||
92 | * Prevents usage of stty. |
||
93 | */ |
||
94 | public static function disableStty() |
||
95 | { |
||
96 | self::$stty = false; |
||
97 | } |
||
98 | |||
99 | /** |
||
100 | * Asks the question to the user. |
||
101 | * |
||
102 | * @return mixed |
||
103 | * |
||
104 | * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden |
||
105 | */ |
||
106 | private function doAsk(OutputInterface $output, Question $question) |
||
107 | { |
||
108 | $this->writePrompt($output, $question); |
||
109 | |||
110 | $inputStream = $this->inputStream ?: \STDIN; |
||
111 | $autocomplete = $question->getAutocompleterCallback(); |
||
112 | |||
113 | if (null === $autocomplete || !self::$stty || !Terminal::hasSttyAvailable()) { |
||
114 | $ret = false; |
||
115 | if ($question->isHidden()) { |
||
116 | try { |
||
117 | $hiddenResponse = $this->getHiddenResponse($output, $inputStream, $question->isTrimmable()); |
||
118 | $ret = $question->isTrimmable() ? trim($hiddenResponse) : $hiddenResponse; |
||
119 | } catch (RuntimeException $e) { |
||
120 | if (!$question->isHiddenFallback()) { |
||
121 | throw $e; |
||
122 | } |
||
123 | } |
||
124 | } |
||
125 | |||
126 | if (false === $ret) { |
||
127 | $ret = $this->readInput($inputStream, $question); |
||
128 | if (false === $ret) { |
||
129 | throw new MissingInputException('Aborted.'); |
||
130 | } |
||
131 | if ($question->isTrimmable()) { |
||
132 | $ret = trim($ret); |
||
133 | } |
||
134 | } |
||
135 | } else { |
||
136 | $autocomplete = $this->autocomplete($output, $question, $inputStream, $autocomplete); |
||
137 | $ret = $question->isTrimmable() ? trim($autocomplete) : $autocomplete; |
||
138 | } |
||
139 | |||
140 | if ($output instanceof ConsoleSectionOutput) { |
||
141 | $output->addContent($ret); |
||
142 | } |
||
143 | |||
144 | $ret = \strlen($ret) > 0 ? $ret : $question->getDefault(); |
||
145 | |||
146 | if ($normalizer = $question->getNormalizer()) { |
||
147 | return $normalizer($ret); |
||
148 | } |
||
149 | |||
150 | return $ret; |
||
151 | } |
||
152 | |||
153 | /** |
||
154 | * @return mixed |
||
155 | */ |
||
156 | private function getDefaultAnswer(Question $question) |
||
157 | { |
||
158 | $default = $question->getDefault(); |
||
159 | |||
160 | if (null === $default) { |
||
161 | return $default; |
||
162 | } |
||
163 | |||
164 | if ($validator = $question->getValidator()) { |
||
165 | return \call_user_func($question->getValidator(), $default); |
||
166 | } elseif ($question instanceof ChoiceQuestion) { |
||
167 | $choices = $question->getChoices(); |
||
168 | |||
169 | if (!$question->isMultiselect()) { |
||
170 | return $choices[$default] ?? $default; |
||
171 | } |
||
172 | |||
173 | $default = explode(',', $default); |
||
174 | foreach ($default as $k => $v) { |
||
175 | $v = $question->isTrimmable() ? trim($v) : $v; |
||
176 | $default[$k] = $choices[$v] ?? $v; |
||
177 | } |
||
178 | } |
||
179 | |||
180 | return $default; |
||
181 | } |
||
182 | |||
183 | /** |
||
184 | * Outputs the question prompt. |
||
185 | */ |
||
186 | protected function writePrompt(OutputInterface $output, Question $question) |
||
187 | { |
||
188 | $message = $question->getQuestion(); |
||
189 | |||
190 | if ($question instanceof ChoiceQuestion) { |
||
191 | $output->writeln(array_merge([ |
||
192 | $question->getQuestion(), |
||
193 | ], $this->formatChoiceQuestionChoices($question, 'info'))); |
||
194 | |||
195 | $message = $question->getPrompt(); |
||
196 | } |
||
197 | |||
198 | $output->write($message); |
||
199 | } |
||
200 | |||
201 | /** |
||
202 | * @return string[] |
||
203 | */ |
||
204 | protected function formatChoiceQuestionChoices(ChoiceQuestion $question, string $tag) |
||
205 | { |
||
206 | $messages = []; |
||
207 | |||
208 | $maxWidth = max(array_map('self::width', array_keys($choices = $question->getChoices()))); |
||
209 | |||
210 | foreach ($choices as $key => $value) { |
||
211 | $padding = str_repeat(' ', $maxWidth - self::width($key)); |
||
212 | |||
213 | $messages[] = sprintf(" [<$tag>%s$padding</$tag>] %s", $key, $value); |
||
214 | } |
||
215 | |||
216 | return $messages; |
||
217 | } |
||
218 | |||
219 | /** |
||
220 | * Outputs an error message. |
||
221 | */ |
||
222 | protected function writeError(OutputInterface $output, \Exception $error) |
||
223 | { |
||
224 | if (null !== $this->getHelperSet() && $this->getHelperSet()->has('formatter')) { |
||
225 | $message = $this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error'); |
||
226 | } else { |
||
227 | $message = '<error>'.$error->getMessage().'</error>'; |
||
228 | } |
||
229 | |||
230 | $output->writeln($message); |
||
231 | } |
||
232 | |||
233 | /** |
||
234 | * Autocompletes a question. |
||
235 | * |
||
236 | * @param resource $inputStream |
||
237 | */ |
||
238 | private function autocomplete(OutputInterface $output, Question $question, $inputStream, callable $autocomplete): string |
||
239 | { |
||
240 | $cursor = new Cursor($output, $inputStream); |
||
241 | |||
242 | $fullChoice = ''; |
||
243 | $ret = ''; |
||
244 | |||
245 | $i = 0; |
||
246 | $ofs = -1; |
||
247 | $matches = $autocomplete($ret); |
||
248 | $numMatches = \count($matches); |
||
249 | |||
250 | $sttyMode = shell_exec('stty -g'); |
||
251 | |||
252 | // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead) |
||
253 | shell_exec('stty -icanon -echo'); |
||
254 | |||
255 | // Add highlighted text style |
||
256 | $output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white')); |
||
257 | |||
258 | // Read a keypress |
||
259 | while (!feof($inputStream)) { |
||
260 | $c = fread($inputStream, 1); |
||
261 | |||
262 | // as opposed to fgets(), fread() returns an empty string when the stream content is empty, not false. |
||
263 | if (false === $c || ('' === $ret && '' === $c && null === $question->getDefault())) { |
||
264 | shell_exec(sprintf('stty %s', $sttyMode)); |
||
265 | throw new MissingInputException('Aborted.'); |
||
266 | } elseif ("\177" === $c) { // Backspace Character |
||
267 | if (0 === $numMatches && 0 !== $i) { |
||
268 | --$i; |
||
269 | $cursor->moveLeft(s($fullChoice)->slice(-1)->width(false)); |
||
270 | |||
271 | $fullChoice = self::substr($fullChoice, 0, $i); |
||
272 | } |
||
273 | |||
274 | if (0 === $i) { |
||
275 | $ofs = -1; |
||
276 | $matches = $autocomplete($ret); |
||
277 | $numMatches = \count($matches); |
||
278 | } else { |
||
279 | $numMatches = 0; |
||
280 | } |
||
281 | |||
282 | // Pop the last character off the end of our string |
||
283 | $ret = self::substr($ret, 0, $i); |
||
284 | } elseif ("\033" === $c) { |
||
285 | // Did we read an escape sequence? |
||
286 | $c .= fread($inputStream, 2); |
||
287 | |||
288 | // A = Up Arrow. B = Down Arrow |
||
289 | if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) { |
||
290 | if ('A' === $c[2] && -1 === $ofs) { |
||
291 | $ofs = 0; |
||
292 | } |
||
293 | |||
294 | if (0 === $numMatches) { |
||
295 | continue; |
||
296 | } |
||
297 | |||
298 | $ofs += ('A' === $c[2]) ? -1 : 1; |
||
299 | $ofs = ($numMatches + $ofs) % $numMatches; |
||
300 | } |
||
301 | } elseif (\ord($c) < 32) { |
||
302 | if ("\t" === $c || "\n" === $c) { |
||
303 | if ($numMatches > 0 && -1 !== $ofs) { |
||
304 | $ret = (string) $matches[$ofs]; |
||
305 | // Echo out remaining chars for current match |
||
306 | $remainingCharacters = substr($ret, \strlen(trim($this->mostRecentlyEnteredValue($fullChoice)))); |
||
307 | $output->write($remainingCharacters); |
||
308 | $fullChoice .= $remainingCharacters; |
||
309 | $i = (false === $encoding = mb_detect_encoding($fullChoice, null, true)) ? \strlen($fullChoice) : mb_strlen($fullChoice, $encoding); |
||
310 | |||
311 | $matches = array_filter( |
||
312 | $autocomplete($ret), |
||
313 | function ($match) use ($ret) { |
||
314 | return '' === $ret || 0 === strpos($match, $ret); |
||
315 | } |
||
316 | ); |
||
317 | $numMatches = \count($matches); |
||
318 | $ofs = -1; |
||
319 | } |
||
320 | |||
321 | if ("\n" === $c) { |
||
322 | $output->write($c); |
||
323 | break; |
||
324 | } |
||
325 | |||
326 | $numMatches = 0; |
||
327 | } |
||
328 | |||
329 | continue; |
||
330 | } else { |
||
331 | if ("\x80" <= $c) { |
||
332 | $c .= fread($inputStream, ["\xC0" => 1, "\xD0" => 1, "\xE0" => 2, "\xF0" => 3][$c & "\xF0"]); |
||
333 | } |
||
334 | |||
335 | $output->write($c); |
||
336 | $ret .= $c; |
||
337 | $fullChoice .= $c; |
||
338 | ++$i; |
||
339 | |||
340 | $tempRet = $ret; |
||
341 | |||
342 | if ($question instanceof ChoiceQuestion && $question->isMultiselect()) { |
||
343 | $tempRet = $this->mostRecentlyEnteredValue($fullChoice); |
||
344 | } |
||
345 | |||
346 | $numMatches = 0; |
||
347 | $ofs = 0; |
||
348 | |||
349 | foreach ($autocomplete($ret) as $value) { |
||
350 | // If typed characters match the beginning chunk of value (e.g. [AcmeDe]moBundle) |
||
351 | if (0 === strpos($value, $tempRet)) { |
||
352 | $matches[$numMatches++] = $value; |
||
353 | } |
||
354 | } |
||
355 | } |
||
356 | |||
357 | $cursor->clearLineAfter(); |
||
358 | |||
359 | if ($numMatches > 0 && -1 !== $ofs) { |
||
360 | $cursor->savePosition(); |
||
361 | // Write highlighted text, complete the partially entered response |
||
362 | $charactersEntered = \strlen(trim($this->mostRecentlyEnteredValue($fullChoice))); |
||
363 | $output->write('<hl>'.OutputFormatter::escapeTrailingBackslash(substr($matches[$ofs], $charactersEntered)).'</hl>'); |
||
364 | $cursor->restorePosition(); |
||
365 | } |
||
366 | } |
||
367 | |||
368 | // Reset stty so it behaves normally again |
||
369 | shell_exec(sprintf('stty %s', $sttyMode)); |
||
370 | |||
371 | return $fullChoice; |
||
372 | } |
||
373 | |||
374 | private function mostRecentlyEnteredValue(string $entered): string |
||
375 | { |
||
376 | // Determine the most recent value that the user entered |
||
377 | if (false === strpos($entered, ',')) { |
||
378 | return $entered; |
||
379 | } |
||
380 | |||
381 | $choices = explode(',', $entered); |
||
382 | if (\strlen($lastChoice = trim($choices[\count($choices) - 1])) > 0) { |
||
383 | return $lastChoice; |
||
384 | } |
||
385 | |||
386 | return $entered; |
||
387 | } |
||
388 | |||
389 | /** |
||
390 | * Gets a hidden response from user. |
||
391 | * |
||
392 | * @param resource $inputStream The handler resource |
||
393 | * @param bool $trimmable Is the answer trimmable |
||
394 | * |
||
395 | * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden |
||
396 | */ |
||
397 | private function getHiddenResponse(OutputInterface $output, $inputStream, bool $trimmable = true): string |
||
398 | { |
||
399 | if ('\\' === \DIRECTORY_SEPARATOR) { |
||
400 | $exe = __DIR__.'/../Resources/bin/hiddeninput.exe'; |
||
401 | |||
402 | // handle code running from a phar |
||
403 | if ('phar:' === substr(__FILE__, 0, 5)) { |
||
404 | $tmpExe = sys_get_temp_dir().'/hiddeninput.exe'; |
||
405 | copy($exe, $tmpExe); |
||
406 | $exe = $tmpExe; |
||
407 | } |
||
408 | |||
409 | $sExec = shell_exec('"'.$exe.'"'); |
||
410 | $value = $trimmable ? rtrim($sExec) : $sExec; |
||
411 | $output->writeln(''); |
||
412 | |||
413 | if (isset($tmpExe)) { |
||
414 | unlink($tmpExe); |
||
415 | } |
||
416 | |||
417 | return $value; |
||
418 | } |
||
419 | |||
420 | if (self::$stty && Terminal::hasSttyAvailable()) { |
||
421 | $sttyMode = shell_exec('stty -g'); |
||
422 | shell_exec('stty -echo'); |
||
423 | } elseif ($this->isInteractiveInput($inputStream)) { |
||
424 | throw new RuntimeException('Unable to hide the response.'); |
||
425 | } |
||
426 | |||
427 | $value = fgets($inputStream, 4096); |
||
428 | |||
429 | if (self::$stty && Terminal::hasSttyAvailable()) { |
||
430 | shell_exec(sprintf('stty %s', $sttyMode)); |
||
431 | } |
||
432 | |||
433 | if (false === $value) { |
||
434 | throw new MissingInputException('Aborted.'); |
||
435 | } |
||
436 | if ($trimmable) { |
||
437 | $value = trim($value); |
||
438 | } |
||
439 | $output->writeln(''); |
||
440 | |||
441 | return $value; |
||
442 | } |
||
443 | |||
444 | /** |
||
445 | * Validates an attempt. |
||
446 | * |
||
447 | * @param callable $interviewer A callable that will ask for a question and return the result |
||
448 | * |
||
449 | * @return mixed The validated response |
||
450 | * |
||
451 | * @throws \Exception In case the max number of attempts has been reached and no valid response has been given |
||
452 | */ |
||
453 | private function validateAttempts(callable $interviewer, OutputInterface $output, Question $question) |
||
454 | { |
||
455 | $error = null; |
||
456 | $attempts = $question->getMaxAttempts(); |
||
457 | |||
458 | while (null === $attempts || $attempts--) { |
||
459 | if (null !== $error) { |
||
460 | $this->writeError($output, $error); |
||
461 | } |
||
462 | |||
463 | try { |
||
464 | return $question->getValidator()($interviewer()); |
||
465 | } catch (RuntimeException $e) { |
||
466 | throw $e; |
||
467 | } catch (\Exception $error) { |
||
468 | } |
||
469 | } |
||
470 | |||
471 | throw $error; |
||
472 | } |
||
473 | |||
474 | private function isInteractiveInput($inputStream): bool |
||
475 | { |
||
476 | if ('php://stdin' !== (stream_get_meta_data($inputStream)['uri'] ?? null)) { |
||
477 | return false; |
||
478 | } |
||
479 | |||
480 | if (null !== self::$stdinIsInteractive) { |
||
481 | return self::$stdinIsInteractive; |
||
482 | } |
||
483 | |||
484 | if (\function_exists('stream_isatty')) { |
||
485 | return self::$stdinIsInteractive = stream_isatty(fopen('php://stdin', 'r')); |
||
486 | } |
||
487 | |||
488 | if (\function_exists('posix_isatty')) { |
||
489 | return self::$stdinIsInteractive = posix_isatty(fopen('php://stdin', 'r')); |
||
490 | } |
||
491 | |||
492 | if (!\function_exists('exec')) { |
||
493 | return self::$stdinIsInteractive = true; |
||
494 | } |
||
495 | |||
496 | exec('stty 2> /dev/null', $output, $status); |
||
497 | |||
498 | return self::$stdinIsInteractive = 1 !== $status; |
||
499 | } |
||
500 | |||
501 | /** |
||
502 | * Reads one or more lines of input and returns what is read. |
||
503 | * |
||
504 | * @param resource $inputStream The handler resource |
||
505 | * @param Question $question The question being asked |
||
506 | * |
||
507 | * @return string|bool The input received, false in case input could not be read |
||
508 | */ |
||
509 | private function readInput($inputStream, Question $question) |
||
510 | { |
||
511 | if (!$question->isMultiline()) { |
||
512 | $cp = $this->setIOCodepage(); |
||
513 | $ret = fgets($inputStream, 4096); |
||
514 | |||
515 | return $this->resetIOCodepage($cp, $ret); |
||
516 | } |
||
517 | |||
518 | $multiLineStreamReader = $this->cloneInputStream($inputStream); |
||
519 | if (null === $multiLineStreamReader) { |
||
520 | return false; |
||
521 | } |
||
522 | |||
523 | $ret = ''; |
||
524 | $cp = $this->setIOCodepage(); |
||
525 | while (false !== ($char = fgetc($multiLineStreamReader))) { |
||
526 | if (\PHP_EOL === "{$ret}{$char}") { |
||
527 | break; |
||
528 | } |
||
529 | $ret .= $char; |
||
530 | } |
||
531 | |||
532 | return $this->resetIOCodepage($cp, $ret); |
||
533 | } |
||
534 | |||
535 | /** |
||
536 | * Sets console I/O to the host code page. |
||
537 | * |
||
538 | * @return int Previous code page in IBM/EBCDIC format |
||
539 | */ |
||
540 | private function setIOCodepage(): int |
||
541 | { |
||
542 | if (\function_exists('sapi_windows_cp_set')) { |
||
543 | $cp = sapi_windows_cp_get(); |
||
544 | sapi_windows_cp_set(sapi_windows_cp_get('oem')); |
||
545 | |||
546 | return $cp; |
||
547 | } |
||
548 | |||
549 | return 0; |
||
550 | } |
||
551 | |||
552 | /** |
||
553 | * Sets console I/O to the specified code page and converts the user input. |
||
554 | * |
||
555 | * @param string|false $input |
||
556 | * |
||
557 | * @return string|false |
||
558 | */ |
||
559 | private function resetIOCodepage(int $cp, $input) |
||
570 | } |
||
571 | |||
572 | /** |
||
573 | * Clones an input stream in order to act on one instance of the same |
||
574 | * stream without affecting the other instance. |
||
575 | * |
||
576 | * @param resource $inputStream The handler resource |
||
577 | * |
||
578 | * @return resource|null The cloned resource, null in case it could not be cloned |
||
579 | */ |
||
580 | private function cloneInputStream($inputStream) |
||
604 | } |
||
605 | } |
||
606 |