Fix max width for multibyte keys in choice question

This commit is contained in:
Marek Pietrzak 2016-01-08 16:25:18 +00:00 committed by Fabien Potencier
parent 3c6d1a93dd
commit 5d2463b925
2 changed files with 32 additions and 2 deletions

View File

@ -162,11 +162,12 @@ class QuestionHelper extends Helper
$message = $question->getQuestion();
if ($question instanceof ChoiceQuestion) {
$width = max(array_map('strlen', array_keys($question->getChoices())));
$maxWidth = max(array_map(array($this, 'strlen'), array_keys($question->getChoices())));
$messages = (array) $question->getQuestion();
foreach ($question->getChoices() as $key => $value) {
$messages[] = sprintf(" [<info>%-${width}s</info>] %s", $key, $value);
$width = $maxWidth - $this->strlen($key);
$messages[] = ' [<info>'.$key.str_repeat(' ', $width).'</info>] '.$value;
}
$output->writeln($messages);

View File

@ -11,6 +11,7 @@
namespace Symfony\Component\Console\Tests\Helper;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Helper\HelperSet;
use Symfony\Component\Console\Helper\FormatterHelper;
@ -350,6 +351,34 @@ class QuestionHelperTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('not yet', $dialog->ask($this->createInputInterfaceMock(false), $this->createOutputInterface(), $question));
}
public function testChoiceOutputFormattingQuestionForUtf8Keys()
{
$question = 'Lorem ipsum?';
$possibleChoices = array(
'foo' => 'foo',
'żółw' => 'bar',
'łabądź' => 'baz',
);
$outputShown = array(
$question,
' [<info>foo </info>] foo',
' [<info>żółw </info>] bar',
' [<info>łabądź</info>] baz',
);
$output = $this->getMock('\Symfony\Component\Console\Output\OutputInterface');
$output->method('getFormatter')->willReturn(new OutputFormatter());
$dialog = new QuestionHelper();
$dialog->setInputStream($this->getInputStream("\n"));
$helperSet = new HelperSet(array(new FormatterHelper()));
$dialog->setHelperSet($helperSet);
$output->expects($this->once())->method('writeln')->with($this->equalTo($outputShown));
$question = new ChoiceQuestion($question, $possibleChoices, 'foo');
$dialog->ask($this->createInputInterfaceMock(), $output, $question);
}
protected function getInputStream($input)
{
$stream = fopen('php://memory', 'r+', false);