ConfirmationQuestion.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Console\Question;
  11. /**
  12. * Represents a yes/no question.
  13. *
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. */
  16. class ConfirmationQuestion extends Question
  17. {
  18. private $trueAnswerRegex;
  19. /**
  20. * @param string $question The question to ask to the user
  21. * @param bool $default The default answer to return, true or false
  22. * @param string $trueAnswerRegex A regex to match the "yes" answer
  23. */
  24. public function __construct(string $question, bool $default = true, string $trueAnswerRegex = '/^y/i')
  25. {
  26. parent::__construct($question, $default);
  27. $this->trueAnswerRegex = $trueAnswerRegex;
  28. $this->setNormalizer($this->getDefaultNormalizer());
  29. }
  30. /**
  31. * Returns the default answer normalizer.
  32. *
  33. * @return callable
  34. */
  35. private function getDefaultNormalizer()
  36. {
  37. $default = $this->getDefault();
  38. $regex = $this->trueAnswerRegex;
  39. return function ($answer) use ($default, $regex) {
  40. if (\is_bool($answer)) {
  41. return $answer;
  42. }
  43. $answerIsTrue = (bool) preg_match($regex, $answer);
  44. if (false === $default) {
  45. return $answer && $answerIsTrue;
  46. }
  47. return '' === $answer || $answerIsTrue;
  48. };
  49. }
  50. }