Skip to content

Commit 9f2edd6

Browse files
committed
check for conversion possibility, don't rely on exception catching
1 parent a9605da commit 9f2edd6

File tree

1 file changed

+17
-10
lines changed

1 file changed

+17
-10
lines changed

src/Console/Helper/Question/AlwaysReturnKeyOfChoiceQuestion.php

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -117,12 +117,9 @@ private function prepareChoices()
117117
$choices = [];
118118
foreach ($this->choiceViews as $choiceView) {
119119
$label = $choiceView->label;
120-
if ($choiceView->data != $choiceView->value) {
121-
try {
122-
$label .= ' (<comment>' . $choiceView->data . '</comment>)';
123-
} catch (\ErrorException $exception) {
124-
// data cannot be converted to string - do nothing
125-
}
120+
$data = $choiceView->data;
121+
if ($data != $choiceView->value && $this->canBeConvertedToString($data)) {
122+
$label .= ' (<comment>' . $data . '</comment>)';
126123
}
127124

128125
$choices[$choiceView->value] = $label;
@@ -140,11 +137,12 @@ private function prepareAutocompleteValues()
140137

141138
foreach ($this->choiceViews as $choiceView) {
142139
$autocompleteValues[] = $choiceView->value;
143-
try {
144-
$autocompleteValues[] = (string)$choiceView->data;
145-
} catch (\ErrorException $exception) {
146-
// data cannot be converted to string - do nothing
140+
141+
$data = $choiceView->data;
142+
if ($this->canBeConvertedToString($data)) {
143+
$autocompleteValues[] = (string)$data;
147144
}
145+
148146
$autocompleteValues[] = $choiceView->label;
149147
}
150148

@@ -164,4 +162,13 @@ private function assertFlatChoiceViewsArray(array $choiceViews)
164162
}
165163
}
166164
}
165+
166+
/**
167+
* @param mixed $value
168+
* @return bool
169+
*/
170+
private function canBeConvertedToString($value)
171+
{
172+
return null === $value || is_scalar($value) || (\is_object($value) && method_exists($value, '__toString'));
173+
}
167174
}

0 commit comments

Comments
 (0)