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

Commitb2e525c

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

File tree

4 files changed

+269
-4
lines changed

4 files changed

+269
-4
lines changed

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

Lines changed: 185 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
/**
3860
* @var resource|null
3961
*/
@@ -129,7 +151,7 @@ private function doAsk(OutputInterface $output, Question $question): mixed
129151
stream_set_blocking($inputStream,true);
130152
}
131153

132-
$ret =$this->readInput($inputStream,$question);
154+
$ret =$this->readInput($inputStream,$question,$output);
133155

134156
if (!$isBlocked) {
135157
stream_set_blocking($inputStream,false);
@@ -522,13 +544,12 @@ private function isInteractiveInput($inputStream): bool
522544
* @param resource $inputStream The handler resource
523545
* @param Question $question The question being asked
524546
*/
525-
privatefunctionreadInput($inputStream,Question$question):string|false
547+
privatefunctionreadInput($inputStream,Question$question,OutputInterface$output):string|false
526548
{
527549
if (!$question->isMultiline()) {
528550
$cp =$this->setIOCodepage();
529-
$ret =fgets($inputStream,4096);
530551

531-
return$this->resetIOCodepage($cp,$ret);
552+
return$this->resetIOCodepage($cp,$this->handleCliInput($inputStream,$output));
532553
}
533554

534555
$multiLineStreamReader =$this->cloneInputStream($inputStream);
@@ -609,4 +630,164 @@ private function cloneInputStream($inputStream)
609630

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

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,11 @@ public function __construct(InputInterface $input, OutputInterface $output)
5858
parent::__construct($this->output =$output);
5959
}
6060

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

‎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
@@ -100,6 +100,14 @@ public function testOutputProgressIterate()
100100
$this->assertStringEqualsFile($outputFilepath,$this->tester->getDisplay(true));
101101
}
102102

103+
publicfunctiontestGetOutput()
104+
{
105+
$output =$this->createMock(OutputInterface::class);
106+
$io =newSymfonyStyle($this->createMock(InputInterface::class),$output);
107+
108+
$this->assertSame($output,$io->getOutput());
109+
}
110+
103111
publicfunctiontestGetErrorStyle()
104112
{
105113
$input =$this->createMock(InputInterface::class);

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp