You are here

public function DialogHelper::select in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 vendor/symfony/console/Helper/DialogHelper.php \Symfony\Component\Console\Helper\DialogHelper::select()

Asks the user to select a value.

Parameters

OutputInterface $output An Output instance:

string|array $question The question to ask:

array $choices List of choices to pick from:

bool|string $default The default answer if the user enters nothing:

bool|int $attempts Max number of times to ask before giving up (false by default, which means infinite):

string $errorMessage Message which will be shown if invalid value from choice list would be picked:

bool $multiselect Select more than one value separated by comma:

Return value

int|string|array The selected value or values (the key of the choices array)

Throws

\InvalidArgumentException

File

vendor/symfony/console/Helper/DialogHelper.php, line 53

Class

DialogHelper
The Dialog class provides helpers to interact with the user.

Namespace

Symfony\Component\Console\Helper

Code

public function select(OutputInterface $output, $question, $choices, $default = null, $attempts = false, $errorMessage = 'Value "%s" is invalid', $multiselect = false) {
  $width = max(array_map('strlen', array_keys($choices)));
  $messages = (array) $question;
  foreach ($choices as $key => $value) {
    $messages[] = sprintf("  [<info>%-{$width}s</info>] %s", $key, $value);
  }
  $output
    ->writeln($messages);
  $result = $this
    ->askAndValidate($output, '> ', function ($picked) use ($choices, $errorMessage, $multiselect) {

    // Collapse all spaces.
    $selectedChoices = str_replace(' ', '', $picked);
    if ($multiselect) {

      // Check for a separated comma values
      if (!preg_match('/^[a-zA-Z0-9_-]+(?:,[a-zA-Z0-9_-]+)*$/', $selectedChoices, $matches)) {
        throw new \InvalidArgumentException(sprintf($errorMessage, $picked));
      }
      $selectedChoices = explode(',', $selectedChoices);
    }
    else {
      $selectedChoices = array(
        $picked,
      );
    }
    $multiselectChoices = array();
    foreach ($selectedChoices as $value) {
      if (empty($choices[$value])) {
        throw new \InvalidArgumentException(sprintf($errorMessage, $value));
      }
      $multiselectChoices[] = $value;
    }
    if ($multiselect) {
      return $multiselectChoices;
    }
    return $picked;
  }, $attempts, $default);
  return $result;
}