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 class Char
extends AbstractPrompt
17 protected $promptText = 'Please select one option ';
22 protected $allowEmpty = false;
27 protected $allowedChars = 'yn';
32 protected $ignoreCase = true;
37 protected $echo = true;
40 * Ask the user for a single key stroke
42 * @param string $promptText The prompt text to display in console
43 * @param string $allowedChars A list of allowed chars (i.e. "abc12345")
44 * @param bool $ignoreCase If true, case will be ignored and prompt will always return lower-cased response
45 * @param bool $allowEmpty Is empty response allowed?
46 * @param bool $echo Display the selection after user presses key
48 public function __construct(
49 $promptText = 'Please hit a key',
50 $allowedChars = '0123456789abcdefghijklmnopqrstuvwxyz',
56 $this->setPromptText($promptText);
57 $this->setAllowEmpty($allowEmpty);
58 $this->setIgnoreCase($ignoreCase);
60 if (null != $allowedChars) {
61 if ($this->ignoreCase
) {
62 $this->setAllowedChars(strtolower($allowedChars));
64 $this->setAllowedChars($allowedChars);
68 $this->setEcho($echo);
72 * Show the prompt to user and return a single char.
76 public function show()
78 $this->getConsole()->write($this->promptText
);
79 $mask = $this->getAllowedChars();
82 * Normalize the mask if case is irrelevant
84 if ($this->ignoreCase
) {
85 $mask = strtolower($mask); // lowercase all
86 $mask .= strtoupper($mask); // uppercase and append
87 $mask = str_split($mask); // convert to array
88 $mask = array_unique($mask); // remove duplicates
89 $mask = implode("", $mask); // convert back to string
93 * Read char from console
95 $char = $this->getConsole()->readChar($mask);
98 echo trim($char)."\n";
100 if ($this->promptText
) {
101 echo "\n"; // skip to next line but only if we had any prompt text
105 return $this->lastResponse
= $char;
109 * @param bool $allowEmpty
111 public function setAllowEmpty($allowEmpty)
113 $this->allowEmpty
= (bool) $allowEmpty;
119 public function getAllowEmpty()
121 return $this->allowEmpty
;
125 * @param string $promptText
127 public function setPromptText($promptText)
129 $this->promptText
= $promptText;
135 public function getPromptText()
137 return $this->promptText
;
141 * @param string $allowedChars
143 public function setAllowedChars($allowedChars)
145 $this->allowedChars
= $allowedChars;
151 public function getAllowedChars()
153 return $this->allowedChars
;
157 * @param bool $ignoreCase
159 public function setIgnoreCase($ignoreCase)
161 $this->ignoreCase
= (bool) $ignoreCase;
167 public function getIgnoreCase()
169 return $this->ignoreCase
;
175 public function setEcho($echo)
177 $this->echo = (bool) $echo;
183 public function getEcho()