Skip to content

ConfirmationQuestion normalizer may behave unexpectedly for Y/N question #29835

Closed
@mrthehud

Description

@mrthehud

Symfony version(s) affected: 4.2

Description
When using the ConfirmationQuestion class to ask a yes / no question, if the default is true, and the answer regex is '/^y/i', then any value not starting with [yY] is considered false - except "0"

How to reproduce
Create a console application, and in the execute method:

    $question = new ConfirmationQuestion("Yes or No?", true);
    $ans = $this->io->askQuestion($question); 
    echo $ans ? 'true' : 'false';

Then run it, and observe the output:
Input: "yes", "y", "YES", "Y", "" (empty string) etc
Output: "true"
Input "no", "No", "foo", "Bar", "1", "true" etc
Output: "false"
Input: "0"
Output: "true" <- I would expect false, as the string does not match the regex

Possible Solution
https://github.com/symfony/console/blob/4a5d48d2ca2422c5c02ed37e4146fb65591369d5/Question/ConfirmationQuestion.php

    private function getDefaultNormalizer()
    {
        $default = $this->getDefault();
        $regex = $this->trueAnswerRegex;
        return function ($answer) use ($default, $regex) {
            if (\is_bool($answer)) {
                return $answer;
            }
            $answerIsTrue = (bool) preg_match($regex, $answer);
            if (false === $default) {
                return $answer && $answerIsTrue;
            }
            return !$answer || $answerIsTrue;
        };
    }

Change line 56 (last return) to:

return strlen($answer) === 0 ? $default : $answerIsTrue;

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions