Browse files

Use readline in console when supported

$this->stdin->read(); will use readline if the system is detected to
support it.  In linux, you will be able to use the left and right arrow
keys to edit the current line, use the up and down keys to navigate
history, press ^U to delete the entire line, etc.

Before this, using arrow keys in linux will just spam characters like
^[[C^[[A^[[D^[[C^[[A^.  Useful for "Console/cake console"
  • Loading branch information...
1 parent 64cf405 commit 916d9921621fb7b278b28a7f2e35d9dc0b412dfe Matt Reishus committed Sep 1, 2013
Showing with 18 additions and 0 deletions.
  1. +18 −0 lib/Cake/Console/ConsoleInput.php
View
18 lib/Cake/Console/ConsoleInput.php
@@ -31,13 +31,24 @@ class ConsoleInput {
* @var resource
*/
protected $_input;
+/**
+ * Can this instance use readline?
+ * Two conditions must be met:
+ * 1. Readline support must be enabled.
+ * 2. Handle we are attached to must be stdin.
+ * Allows rich editing with arrow keys and history when inputting a string.
+ *
+ * @var bool
+ */
+ private $_can_readline;
/**
* Constructor
*
* @param string $handle The location of the stream to use as input.
*/
public function __construct($handle = 'php://stdin') {
+ $this->_can_readline = extension_loaded('readline') && $handle == 'php://stdin' ? true : false;
$this->_input = fopen($handle, 'r');
}
@@ -47,6 +58,13 @@ public function __construct($handle = 'php://stdin') {
* @return mixed The value of the stream
*/
public function read() {
+ if ($this->_can_readline) {
+ $line = readline('');
+ if (!empty($line)) {
+ readline_add_history($line);
+ }
+ return $line;
+ }
return fgets($this->_input);
}

0 comments on commit 916d992

Please sign in to comment.