Skip to content

Commit e061b63

Browse files
authored
Merge pull request #63 from clue-labs/readline
Optionally use `ext-readline` to enable raw input mode if available
2 parents 1cf2db1 + e3ec4c0 commit e061b63

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

README.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -583,6 +583,13 @@ If this extension is missing, then this library will use a slighty slower Regex
583583
work-around that should otherwise work equally well.
584584
Installing `ext-mbstring` is highly recommended.
585585

586+
Internally, it will use the `ext-readline` to enable raw terminal input mode.
587+
If this extension is missing, then this library will manually set the required
588+
TTY settings on start and will try to restore previous settings on exit.
589+
Input line editing is handled entirely within this library and does not rely on
590+
`ext-readline`.
591+
Installing `ext-readline` is entirely optional.
592+
586593
Note that *Microsoft Windows is not supported*.
587594
Due to platform inconsistencies, PHP does not provide support for reading from
588595
standard console input without blocking.

src/Stdin.php

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@ class Stdin extends Stream
1212
{
1313
private $oldMode = null;
1414

15+
/**
16+
* @param LoopInterface $loop
17+
* @codeCoverageIgnore this is covered by functional tests with/without ext-readline
18+
*/
1519
public function __construct(LoopInterface $loop)
1620
{
1721
// STDIN not defined ("php -a") or already closed (`fclose(STDIN)`)
@@ -28,6 +32,14 @@ public function __construct(LoopInterface $loop)
2832
return $this->close();
2933
}
3034

35+
if (function_exists('readline_callback_handler_install')) {
36+
// Prefer `ext-readline` to install dummy handler to turn on raw input mode.
37+
// We will nevery actually feed the readline handler and instead
38+
// handle all input in our `Readline` implementation.
39+
readline_callback_handler_install('', function () { });
40+
return;
41+
}
42+
3143
if ($this->isTty()) {
3244
$this->oldMode = shell_exec('stty -g');
3345

@@ -51,9 +63,15 @@ public function __destruct()
5163
$this->restore();
5264
}
5365

66+
/**
67+
* @codeCoverageIgnore this is covered by functional tests with/without ext-readline
68+
*/
5469
private function restore()
5570
{
56-
if ($this->oldMode !== null && $this->isTty()) {
71+
if (function_exists('readline_callback_handler_remove')) {
72+
// remove dummy readline handler to turn to default input mode
73+
readline_callback_handler_remove();
74+
} elseif ($this->oldMode !== null && $this->isTty()) {
5775
// Reset stty so it behaves normally again
5876
shell_exec(sprintf('stty %s', $this->oldMode));
5977
$this->oldMode = null;

0 commit comments

Comments
 (0)