-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathConsole.php
More file actions
88 lines (78 loc) · 2.33 KB
/
Copy pathConsole.php
File metadata and controls
88 lines (78 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
declare(strict_types=1);
namespace Scriptor\Boot\Cli;
/**
* Thin wrapper around stdin/stdout/stderr.
*
* Exists so InstallCommand and PasswordPrompt can be unit-tested with
* an in-memory replacement without `fopen('php://temp')` dancing in
* every test. Production code uses `new Console()`.
*/
class Console
{
/** @var resource */
protected $stdin;
/** @var resource */
protected $stdout;
/** @var resource */
protected $stderr;
public function __construct()
{
$this->stdin = \STDIN;
$this->stdout = \STDOUT;
$this->stderr = \STDERR;
}
public function writeln(string $line): void
{
\fwrite($this->stdout, $line . "\n");
}
public function errln(string $line): void
{
\fwrite($this->stderr, $line . "\n");
}
public function prompt(string $label): string
{
\fwrite($this->stdout, $label);
$line = \fgets($this->stdin);
return $line === false ? '' : \rtrim($line, "\r\n");
}
/**
* Read a line with echo suppressed via `stty -echo`. Falls back to
* normal echo if stty is unavailable (Windows, weird terminals).
* Returns the empty string when no TTY is attached.
*/
public function promptSecret(string $label): string
{
if (! $this->stdinIsTty()) {
return '';
}
\fwrite($this->stdout, $label);
$sttyOriginal = $this->trySttyToggle('-echo');
try {
$line = \fgets($this->stdin);
} finally {
if ($sttyOriginal !== null) {
\shell_exec('stty ' . \escapeshellarg($sttyOriginal));
}
\fwrite($this->stdout, "\n");
}
return $line === false ? '' : \rtrim($line, "\r\n");
}
public function stdinIsTty(): bool
{
return \stream_isatty($this->stdin);
}
/**
* Toggle a stty mode. Returns the previous settings string so the
* caller can restore it, or null when stty is unavailable.
*/
private function trySttyToggle(string $mode): ?string
{
$current = \shell_exec('stty -g 2>/dev/null');
if ($current === null || \trim((string) $current) === '') {
return null;
}
\shell_exec('stty ' . \escapeshellarg($mode) . ' 2>/dev/null');
return \trim((string) $current);
}
}