Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit7be7fcb

Browse files
committed
[Console] Support a set of control keys and key combinations in QuestionHelper
1 parent9f77ba3 commit7be7fcb

File tree

4 files changed

+267
-4
lines changed

4 files changed

+267
-4
lines changed

‎src/Symfony/Component/Console/Helper/QuestionHelper.php

Lines changed: 183 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,14 @@
1818
useSymfony\Component\Console\Formatter\OutputFormatterStyle;
1919
useSymfony\Component\Console\Input\InputInterface;
2020
useSymfony\Component\Console\Input\StreamableInputInterface;
21+
useSymfony\Component\Console\Output\ConsoleOutput;
2122
useSymfony\Component\Console\Output\ConsoleOutputInterface;
2223
useSymfony\Component\Console\Output\ConsoleSectionOutput;
2324
useSymfony\Component\Console\Output\OutputInterface;
25+
useSymfony\Component\Console\Output\StreamOutput;
2426
useSymfony\Component\Console\Question\ChoiceQuestion;
2527
useSymfony\Component\Console\Question\Question;
28+
useSymfony\Component\Console\Style\SymfonyStyle;
2629
useSymfony\Component\Console\Terminal;
2730

2831
usefunctionSymfony\Component\String\s;
@@ -34,6 +37,25 @@
3437
*/
3538
class QuestionHelperextends Helper
3639
{
40+
privateconstKEY_ALT_B ="\033b";
41+
privateconstKEY_ALT_F ="\033f";
42+
privateconstKEY_ARROW_LEFT ="\033[D";
43+
privateconstKEY_ARROW_RIGHT ="\033[C";
44+
privateconstKEY_BACKSPACE ="\177";
45+
privateconstKEY_CTRL_A ="\001";
46+
privateconstKEY_CTRL_B ="\002";
47+
privateconstKEY_CTRL_E ="\005";
48+
privateconstKEY_CTRL_F ="\006";
49+
privateconstKEY_CTRL_H ="\010";
50+
privateconstKEY_CTRL_ARROW_LEFT ="\033[1;5D";
51+
privateconstKEY_CTRL_ARROW_RIGHT ="\033[1;5C";
52+
privateconstKEY_CTRL_SHIFT_ARROW_LEFT ="\033[1;6D";
53+
privateconstKEY_CTRL_SHIFT_ARROW_RIGHT ="\033[1;6C";
54+
privateconstKEY_DELETE ="\033[3~";
55+
privateconstKEY_END ="\033[F";
56+
privateconstKEY_ENTER ="\n";
57+
privateconstKEY_HOME ="\033[H";
58+
3759
privatestaticbool$stty =true;
3860
privatestaticbool$stdinIsInteractive;
3961

@@ -122,7 +144,7 @@ private function doAsk($inputStream, OutputInterface $output, Question $question
122144
stream_set_blocking($inputStream,true);
123145
}
124146

125-
$ret =$this->readInput($inputStream,$question);
147+
$ret =$this->readInput($inputStream,$question,$output);
126148

127149
if (!$isBlocked) {
128150
stream_set_blocking($inputStream,false);
@@ -499,13 +521,12 @@ private function isInteractiveInput($inputStream): bool
499521
* @param resource $inputStream The handler resource
500522
* @param Question $question The question being asked
501523
*/
502-
privatefunctionreadInput($inputStream,Question$question):string|false
524+
privatefunctionreadInput($inputStream,Question$question,OutputInterface$output):string|false
503525
{
504526
if (!$question->isMultiline()) {
505527
$cp =$this->setIOCodepage();
506-
$ret =fgets($inputStream,4096);
507528

508-
return$this->resetIOCodepage($cp,$ret);
529+
return$this->resetIOCodepage($cp,$this->handleCliInput($inputStream,$output));
509530
}
510531

511532
$multiLineStreamReader =$this->cloneInputStream($inputStream);
@@ -586,4 +607,162 @@ private function cloneInputStream($inputStream)
586607

587608
return$cloneStream;
588609
}
610+
611+
/**
612+
* @param resource $inputStream The handler resource
613+
*/
614+
privatefunctionhandleCliInput($inputStream,OutputInterface$output):string|false
615+
{
616+
if (!Terminal::hasSttyAvailable() ||'/' !== \DIRECTORY_SEPARATOR) {
617+
returnfgets($inputStream,4096);
618+
}
619+
620+
// Memory not supported for stream_select
621+
$isStdin ='php://stdin' === (stream_get_meta_data($inputStream)['uri'] ??null);
622+
// Check for stdout and stderr because helpers are using stderr by default
623+
$isOutputSupported =$outputinstanceof StreamOutput ?\in_array(stream_get_meta_data($output->getStream())['uri'] ??null, ['php://stdout','php://stderr','php://output']) :
624+
($outputinstanceof SymfonyStyle &&$output->getOutput()instanceof StreamOutput &&\in_array(stream_get_meta_data($output->getOutput()->getStream())['uri'] ??null, ['php://stdout','php://stderr','php://output']));
625+
$sttyMode =shell_exec('stty -g');
626+
// Disable icanon (so we can fread each keypress)
627+
shell_exec('stty -icanon -echo');
628+
629+
if ($isOutputSupported) {
630+
$originalOutput =$output;
631+
// This is needed for the input handling, when a question is in a section because then the inout is handled after the section
632+
// Verbosity level is set to normal to see the input because using quiet would not show in input
633+
$output =newConsoleOutput();
634+
}
635+
636+
$cursor =newCursor($output);
637+
$startXPos =$cursor->getCurrentPosition()[0];
638+
$pressedKey =false;
639+
$ret = [];
640+
$currentInputXPos =0;
641+
642+
while (!feof($inputStream) &&self::KEY_ENTER !==$pressedKey) {
643+
$read = [$inputStream];
644+
$write =$except =null;
645+
while ($isStdin &&0 === @stream_select($read,$write,$except,0,100)) {
646+
// Give signal handlers a chance to run
647+
$read = [$inputStream];
648+
}
649+
$pressedKey =fread($inputStream,1);
650+
651+
if ((false ===$pressedKey ||0 ===\ord($pressedKey)) &&empty($ret)) {
652+
// Reset stty so it behaves normally again
653+
shell_exec('stty'.$sttyMode);
654+
655+
returnfalse;
656+
}
657+
658+
$unreadBytes =stream_get_meta_data($inputStream)['unread_bytes'];
659+
if ("\033" ===$pressedKey &&0 <$unreadBytes) {
660+
$pressedKey .=fread($inputStream,1);
661+
if (91 ===\ord($pressedKey[1]) &&1 <$unreadBytes) {
662+
// Ctrl keys / key combinations need at least 3 chars
663+
$pressedKey .=fread($inputStream,1);
664+
if (isset($pressedKey[2]) &&51 ===\ord($pressedKey[2]) &&2 <$unreadBytes) {
665+
// Del needs 4 chars
666+
$pressedKey .=fread($inputStream,1);
667+
}
668+
if (isset($pressedKey[2]) &&49 ===\ord($pressedKey[2]) &&2 <$unreadBytes) {
669+
// Ctrl + arrow left/right needs 6 chars
670+
$pressedKey .=fread($inputStream,3);
671+
}
672+
}
673+
}elseif ("\303" ===$pressedKey &&0 <$unreadBytes) {
674+
// Special chars need 2 chars
675+
$pressedKey .=fread($inputStream,1);
676+
}
677+
678+
switch (true) {
679+
caseself::KEY_ARROW_LEFT ===$pressedKey &&$currentInputXPos >0:
680+
caseself::KEY_CTRL_B ===$pressedKey &&$currentInputXPos >0:
681+
$cursor->moveLeft();
682+
--$currentInputXPos;
683+
break;
684+
caseself::KEY_ARROW_RIGHT ===$pressedKey &&$currentInputXPos <\count($ret):
685+
caseself::KEY_CTRL_F ===$pressedKey &&$currentInputXPos <\count($ret):
686+
$cursor->moveRight();
687+
++$currentInputXPos;
688+
break;
689+
caseself::KEY_CTRL_ARROW_LEFT ===$pressedKey &&$currentInputXPos >0:
690+
caseself::KEY_ALT_B ===$pressedKey &&$currentInputXPos >0:
691+
caseself::KEY_CTRL_SHIFT_ARROW_LEFT ===$pressedKey &&$currentInputXPos >0:
692+
do {
693+
$cursor->moveLeft();
694+
--$currentInputXPos;
695+
}while ($currentInputXPos >0 && (1 <\strlen($ret[$currentInputXPos -1]) ||preg_match('/\w/',$ret[$currentInputXPos -1])));
696+
break;
697+
caseself::KEY_CTRL_ARROW_RIGHT ===$pressedKey &&$currentInputXPos <\count($ret):
698+
caseself::KEY_ALT_F ===$pressedKey &&$currentInputXPos <\count($ret):
699+
caseself::KEY_CTRL_SHIFT_ARROW_RIGHT ===$pressedKey &&$currentInputXPos <\count($ret):
700+
do {
701+
$cursor->moveRight();
702+
++$currentInputXPos;
703+
}while ($currentInputXPos <\count($ret) && (1 <\strlen($ret[$currentInputXPos]) ||preg_match('/\w/',$ret[$currentInputXPos])));
704+
break;
705+
caseself::KEY_CTRL_H ===$pressedKey &&$currentInputXPos >0:
706+
caseself::KEY_BACKSPACE ===$pressedKey &&$currentInputXPos >0:
707+
array_splice($ret,$currentInputXPos -1,1);
708+
$cursor->moveToColumn($startXPos);
709+
if ($isOutputSupported) {
710+
$output->write(implode('',$ret));
711+
}
712+
$cursor->clearLineAfter()
713+
->moveToColumn(($currentInputXPos +$startXPos) -1);
714+
--$currentInputXPos;
715+
break;
716+
caseself::KEY_DELETE ===$pressedKey &&$currentInputXPos <\count($ret):
717+
array_splice($ret,$currentInputXPos,1);
718+
$cursor->moveToColumn($startXPos);
719+
if ($isOutputSupported) {
720+
$output->write(implode('',$ret));
721+
}
722+
$cursor->clearLineAfter()
723+
->moveToColumn($currentInputXPos +$startXPos);
724+
break;
725+
caseself::KEY_HOME ===$pressedKey:
726+
caseself::KEY_CTRL_A ===$pressedKey:
727+
$cursor->moveToColumn($startXPos);
728+
$currentInputXPos =0;
729+
break;
730+
caseself::KEY_END ===$pressedKey:
731+
caseself::KEY_CTRL_E ===$pressedKey:
732+
$cursor->moveToColumn($startXPos +\count($ret));
733+
$currentInputXPos =\count($ret);
734+
break;
735+
case !preg_match('@[[:cntrl:]]@',$pressedKey):
736+
if ($currentInputXPos >=0 &&$currentInputXPos <\count($ret)) {
737+
array_splice($ret,$currentInputXPos,0,$pressedKey);
738+
$cursor->moveToColumn($startXPos);
739+
if ($isOutputSupported) {
740+
$output->write(implode('',$ret));
741+
}
742+
$cursor->clearLineAfter()
743+
->moveToColumn($currentInputXPos +$startXPos +1);
744+
}else {
745+
$ret[] =$pressedKey;
746+
if ($isOutputSupported) {
747+
$output->write($pressedKey);
748+
}
749+
}
750+
++$currentInputXPos;
751+
break;
752+
default:
753+
break;
754+
}
755+
}
756+
757+
if ($isOutputSupported) {
758+
// Clear the output to write it to the original output
759+
$cursor->moveToColumn($startXPos)->clearLineAfter();
760+
$originalOutput->writeln(implode('',$ret));
761+
}
762+
763+
// Reset stty so it behaves normally again
764+
shell_exec('stty'.$sttyMode);
765+
766+
returnimplode('',$ret);
767+
}
589768
}

‎src/Symfony/Component/Console/Style/SymfonyStyle.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,11 @@ public function __construct(
5757
parent::__construct($output);
5858
}
5959

60+
publicfunctiongetOutput():OutputInterface
61+
{
62+
return$this->output;
63+
}
64+
6065
/**
6166
* Formats a message as a block of text.
6267
*/

‎src/Symfony/Component/Console/Tests/Helper/QuestionHelperTest.php

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,13 @@
1919
useSymfony\Component\Console\Helper\HelperSet;
2020
useSymfony\Component\Console\Helper\QuestionHelper;
2121
useSymfony\Component\Console\Input\InputInterface;
22+
useSymfony\Component\Console\Output\ConsoleSectionOutput;
2223
useSymfony\Component\Console\Output\OutputInterface;
2324
useSymfony\Component\Console\Output\StreamOutput;
2425
useSymfony\Component\Console\Question\ChoiceQuestion;
2526
useSymfony\Component\Console\Question\ConfirmationQuestion;
2627
useSymfony\Component\Console\Question\Question;
28+
useSymfony\Component\Console\Style\SymfonyStyle;
2729
useSymfony\Component\Console\Terminal;
2830
useSymfony\Component\Console\Tester\ApplicationTester;
2931

@@ -32,6 +34,25 @@
3234
*/
3335
class QuestionHelperTestextends AbstractQuestionHelperTestCase
3436
{
37+
privateconstKEY_ALT_B ="\033b";
38+
privateconstKEY_ALT_F ="\033f";
39+
privateconstKEY_ARROW_LEFT ="\033[D";
40+
privateconstKEY_ARROW_RIGHT ="\033[C";
41+
privateconstKEY_BACKSPACE ="\177";
42+
privateconstKEY_CTRL_A ="\001";
43+
privateconstKEY_CTRL_B ="\002";
44+
privateconstKEY_CTRL_E ="\005";
45+
privateconstKEY_CTRL_F ="\006";
46+
privateconstKEY_CTRL_H ="\010";
47+
privateconstKEY_CTRL_ARROW_LEFT ="\033[1;5D";
48+
privateconstKEY_CTRL_ARROW_RIGHT ="\033[1;5C";
49+
privateconstKEY_CTRL_SHIFT_ARROW_LEFT ="\033[1;6D";
50+
privateconstKEY_CTRL_SHIFT_ARROW_RIGHT ="\033[1;6C";
51+
privateconstKEY_DELETE ="\033[3~";
52+
privateconstKEY_END ="\033[F";
53+
privateconstKEY_ENTER ="\n";
54+
privateconstKEY_HOME ="\033[H";
55+
3556
publicfunctiontestAskChoice()
3657
{
3758
$questionHelper =newQuestionHelper();
@@ -172,6 +193,56 @@ public function testAsk()
172193
$this->assertEquals('What time is it?',stream_get_contents($output->getStream()));
173194
}
174195

196+
/**
197+
* @dataProvider getAskInputWithControlsData
198+
*/
199+
publicfunctiontestAskInputWithControls(string$input,string$expected)
200+
{
201+
if (!Terminal::hasSttyAvailable()) {
202+
$this->markTestSkipped('`stty` is required to test autocomplete functionality');
203+
}
204+
$dialog =newQuestionHelper();
205+
206+
$inputStream =$this->getInputStream($input.self::KEY_ENTER);
207+
208+
$question =newQuestion('Question?');
209+
$this->assertEquals($expected,$dialog->ask($this->createStreamableInputInterfaceMock($inputStream),$this->createOutputInterface(),$question));
210+
}
211+
212+
publicfunctiongetAskInputWithControlsData()
213+
{
214+
return [
215+
['test1234,;.:_-+*\'#\\()/@!äßñ','test1234,;.:_-+*\'#\\()/@!äßñ'],
216+
['tet'.self::KEY_ARROW_LEFT.'s','test'],
217+
['tesñt'.self::KEY_ARROW_LEFT.self::KEY_BACKSPACE,'test'],
218+
['tesst'.self::KEY_CTRL_B.self::KEY_CTRL_H,'test'],
219+
['tes@t'.self::KEY_ARROW_LEFT.self::KEY_ARROW_LEFT.self::KEY_DELETE,'test'],
220+
['test'.self::KEY_ARROW_LEFT.self::KEY_ARROW_LEFT.'1'.self::KEY_ARROW_RIGHT.'2','te1s2t'],
221+
['test'.self::KEY_ARROW_LEFT.self::KEY_ARROW_LEFT.'1'.self::KEY_CTRL_F.'2','te1s2t'],
222+
['es'.self::KEY_HOME.'t'.self::KEY_END.'t','test'],
223+
['es'.self::KEY_CTRL_A.'t'.self::KEY_CTRL_E.'t','test'],
224+
['t e@sñt'.self::KEY_CTRL_ARROW_LEFT.self::KEY_BACKSPACE.self::KEY_CTRL_ARROW_LEFT.self::KEY_BACKSPACE,'tesñt'],
225+
['t e.sät'.self::KEY_CTRL_ARROW_LEFT.self::KEY_CTRL_ARROW_LEFT.self::KEY_BACKSPACE.self::KEY_CTRL_ARROW_RIGHT.self::KEY_DELETE,'tesät'],
226+
['t e-sñt'.self::KEY_CTRL_SHIFT_ARROW_LEFT.self::KEY_BACKSPACE.self::KEY_ALT_B.self::KEY_BACKSPACE,'tesñt'],
227+
['t e?sät'.self::KEY_CTRL_ARROW_LEFT.self::KEY_CTRL_ARROW_LEFT.self::KEY_CTRL_ARROW_LEFT.self::KEY_CTRL_SHIFT_ARROW_RIGHT.self::KEY_DELETE.self::KEY_ALT_F.self::KEY_DELETE,'tesät'],
228+
];
229+
}
230+
231+
publicfunctiontestAskInputWithControlsInSection()
232+
{
233+
if (!Terminal::hasSttyAvailable()) {
234+
$this->markTestSkipped('`stty` is required to test autocomplete functionality');
235+
}
236+
237+
$output =$this->createOutputInterface();
238+
$sections = [];
239+
$section =newConsoleSectionOutput($output->getStream(),$sections,$output->getVerbosity(),false,newOutputFormatter());
240+
$inputStream =$this->getInputStream('es'.self::KEY_HOME.'t'.self::KEY_END.'t'.self::KEY_ENTER);
241+
$io =newSymfonyStyle($this->createStreamableInputInterfaceMock($inputStream),$section);
242+
243+
$this->assertEquals('test',$io->ask('Test the input behavior'));
244+
}
245+
175246
publicfunctiontestAskNonTrimmed()
176247
{
177248
$dialog =newQuestionHelper();

‎src/Symfony/Component/Console/Tests/Style/SymfonyStyleTest.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,14 @@ public function testOutputProgressIterate()
9696
$this->assertStringEqualsFile($outputFilepath,$this->tester->getDisplay(true));
9797
}
9898

99+
publicfunctiontestGetOutput()
100+
{
101+
$output =$this->createMock(OutputInterface::class);
102+
$io =newSymfonyStyle($this->createMock(InputInterface::class),$output);
103+
104+
$this->assertSame($output,$io->getOutput());
105+
}
106+
99107
publicfunctiontestGetErrorStyle()
100108
{
101109
$input =$this->createMock(InputInterface::class);

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp