3 * Zend Framework (http://framework.zend.com/)
5 * @link http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license http://framework.zend.com/license/new-bsd New BSD License
10 namespace Zend\Console\Prompt
;
12 use Zend\Console\Exception
;
14 class Select
extends Char
19 protected $promptText = 'Please select an option';
24 protected $ignoreCase = true;
29 protected $options = array();
32 * Ask the user to select one of pre-defined options
34 * @param string $promptText The prompt text to display in console
35 * @param array $options Allowed options
36 * @param bool $allowEmpty Allow empty (no) selection?
37 * @param bool $echo True to display selected option?
38 * @throws Exception\BadMethodCallException if no options available
40 public function __construct(
41 $promptText = 'Please select one option',
46 if ($promptText !== null) {
47 $this->setPromptText($promptText);
50 if (!count($options)) {
51 throw new Exception\
BadMethodCallException(
52 'Cannot construct a "select" prompt without any options'
56 $this->setOptions($options);
58 if ($allowEmpty !== null) {
59 $this->setAllowEmpty($allowEmpty);
63 $this->setEcho($echo);
69 * Show a list of options and prompt the user to select one of them.
71 * @return string Selected option
73 public function show()
75 // Show prompt text and available options
76 $console = $this->getConsole();
77 $console->writeLine($this->promptText
);
78 foreach ($this->options
as $k => $v) {
79 $console->writeLine(' ' . $k . ') ' . $v);
83 $mask = implode("", array_keys($this->options
));
84 if ($this->allowEmpty
) {
88 // Prepare other params for parent class
89 $this->setAllowedChars($mask);
90 $oldPrompt = $this->promptText
;
91 $oldEcho = $this->echo;
93 $this->promptText
= null;
95 // Retrieve a single character
96 $response = parent
::show();
99 $this->promptText
= $oldPrompt;
100 $this->echo = $oldEcho;
102 // Display selected option if echo is enabled
104 if (isset($this->options
[$response])) {
105 $console->writeLine($this->options
[$response]);
107 $console->writeLine();
111 $this->lastResponse
= $response;
116 * Set allowed options
118 * @param array|\Traversable $options
119 * @throws Exception\BadMethodCallException
121 public function setOptions($options)
123 if (!is_array($options) && !$options instanceof \Traversable
) {
124 throw new Exception\
BadMethodCallException(
125 'Please specify an array or Traversable object as options'
129 if (!is_array($options)) {
130 $this->options
= array();
131 foreach ($options as $k => $v) {
132 $this->options
[$k] = $v;
135 $this->options
= $options;
142 public function getOptions()
144 return $this->options
;