function ChoiceQuestion::getDefaultValidator
3 calls to ChoiceQuestion::getDefaultValidator()
- ChoiceQuestion::setErrorMessage in vendor/
symfony/ console/ Question/ ChoiceQuestion.php - Sets the error message for invalid values.
- ChoiceQuestion::setMultiselect in vendor/
symfony/ console/ Question/ ChoiceQuestion.php - Sets multiselect option.
- ChoiceQuestion::__construct in vendor/
symfony/ console/ Question/ ChoiceQuestion.php
File
-
vendor/
symfony/ console/ Question/ ChoiceQuestion.php, line 113
Class
- ChoiceQuestion
- Represents a choice question.
Namespace
Symfony\Component\Console\QuestionCode
private function getDefaultValidator() : callable {
$choices = $this->choices;
$errorMessage = $this->errorMessage;
$multiselect = $this->multiselect;
$isAssoc = $this->isAssoc($choices);
return function ($selected) use ($choices, $errorMessage, $multiselect, $isAssoc) {
if ($multiselect) {
// Check for a separated comma values
if (!preg_match('/^[^,]+(?:,[^,]+)*$/', (string) $selected, $matches)) {
throw new InvalidArgumentException(\sprintf($errorMessage, $selected));
}
$selectedChoices = explode(',', (string) $selected);
}
else {
$selectedChoices = [
$selected,
];
}
if ($this->isTrimmable()) {
foreach ($selectedChoices as $k => $v) {
$selectedChoices[$k] = trim((string) $v);
}
}
$multiselectChoices = [];
foreach ($selectedChoices as $value) {
$results = [];
foreach ($choices as $key => $choice) {
if ($choice === $value) {
$results[] = $key;
}
}
if (\count($results) > 1) {
throw new InvalidArgumentException(\sprintf('The provided answer is ambiguous. Value should be one of "%s".', implode('" or "', $results)));
}
$result = array_search($value, $choices);
if (!$isAssoc) {
if (false !== $result) {
$result = $choices[$result];
}
elseif (isset($choices[$value])) {
$result = $choices[$value];
}
}
elseif (false === $result && isset($choices[$value])) {
$result = $value;
}
if (false === $result) {
throw new InvalidArgumentException(\sprintf($errorMessage, $value));
}
// For associative choices, consistently return the key as string:
$multiselectChoices[] = $isAssoc ? (string) $result : $result;
}
if ($multiselect) {
return $multiselectChoices;
}
return current($multiselectChoices);
};
}