Skip to content

[Console] Fix Windows code page support #41113

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 7, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 36 additions & 7 deletions src/Symfony/Component/Console/Helper/QuestionHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -110,11 +110,6 @@ private function doAsk(OutputInterface $output, Question $question)
$inputStream = $this->inputStream ?: \STDIN;
$autocomplete = $question->getAutocompleterCallback();

if (\function_exists('sapi_windows_cp_set')) {
// Codepage used by cmd.exe on Windows to allow special characters (éàüñ).
@sapi_windows_cp_set(1252);
}

if (null === $autocomplete || !self::$stty || !Terminal::hasSttyAvailable()) {
$ret = false;
if ($question->isHidden()) {
Expand Down Expand Up @@ -514,7 +509,10 @@ private function isInteractiveInput($inputStream): bool
private function readInput($inputStream, Question $question)
{
if (!$question->isMultiline()) {
return fgets($inputStream, 4096);
$cp = $this->setIOCodepage();
$ret = fgets($inputStream, 4096);

return $this->resetIOCodepage($cp, $ret);
}

$multiLineStreamReader = $this->cloneInputStream($inputStream);
Expand All @@ -523,14 +521,45 @@ private function readInput($inputStream, Question $question)
}

$ret = '';
$cp = $this->setIOCodepage();
while (false !== ($char = fgetc($multiLineStreamReader))) {
if (\PHP_EOL === "{$ret}{$char}") {
break;
}
$ret .= $char;
}

return $ret;
return $this->resetIOCodepage($cp, $ret);
}

/**
* Set console I/O to the host code page.
*
* @return int Previous code page in IBM/EBCDIC format
*/
private function setIOCodepage(): int
{
if (\function_exists('sapi_windows_cp_set')) {
$cp = sapi_windows_cp_get();
sapi_windows_cp_set(sapi_windows_cp_get('oem'));

return $cp;
}

return 0;
}

/**
* Set console I/O to the specified code page and convert the user input.
*/
private function resetIOCodepage(int $cp, string $input): string
{
if (\function_exists('sapi_windows_cp_set') && 0 < $cp) {
sapi_windows_cp_set($cp);
$input = sapi_windows_cp_conv(sapi_windows_cp_get('oem'), $cp, $input);
}

return $input;
}

/**
Expand Down