Skip to content

Commit 3f588d0

Browse files
authored
Windows promptHidden (#49)
Windows promptHidden
2 parents 0db193b + 43fe762 commit 3f588d0

File tree

3 files changed

+35
-10
lines changed

3 files changed

+35
-10
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -330,7 +330,7 @@ $interactor->greenBold("The name is: $name", true);
330330

331331
#### Prompt hidden
332332

333-
> Currently not supported in windows platform, but maybe supported in future.
333+
> On windows platform, it may change the fontface which can be [fixed](https://superuser.com/a/757591).
334334
335335
```php
336336
$passValidator = function ($pass) {

src/IO/Interactor.php

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -313,15 +313,7 @@ public function prompt(string $text, $default = null, callable $fn = null, int $
313313
*/
314314
public function promptHidden(string $text, callable $fn = null, int $retry = 3)
315315
{
316-
$winOS = '\\' === \DIRECTORY_SEPARATOR;
317-
318-
// @codeCoverageIgnoreStart
319-
if ($winOS) {
320-
$this->writer->error('Hidden input not supported, Press Ctrl+C if you would like to abort', true);
321-
}
322-
// @codeCoverageIgnoreEnd
323-
324-
return $this->prompt($text, null, $fn, $retry, !$winOS);
316+
return $this->prompt($text, null, $fn, $retry, true);
325317
}
326318

327319
/**

src/Input/Reader.php

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,12 @@ public function read($default = null, callable $fn = null)
6262
*/
6363
public function readHidden($default = null, callable $fn = null)
6464
{
65+
// @codeCoverageIgnoreStart
66+
if ('\\' === \DIRECTORY_SEPARATOR) {
67+
return $this->readHiddenWinOS($default, $fn);
68+
}
69+
// @codeCoverageIgnoreEnd
70+
6571
\shell_exec('stty -echo');
6672
$in = $this->read($default, $fn);
6773
\shell_exec('stty echo');
@@ -70,4 +76,31 @@ public function readHidden($default = null, callable $fn = null)
7076

7177
return $in;
7278
}
79+
80+
/**
81+
* Read a line from configured stream (or terminal) but don't echo it back.
82+
*
83+
* @codeCoverageIgnore
84+
*
85+
* @param callable|null $fn The validator/sanitizer callback.
86+
*
87+
* @return mixed
88+
*/
89+
private function readHiddenWinOS($default = null, callable $fn = null)
90+
{
91+
$cmd = 'powershell -Command ' . \implode('; ', \array_filter([
92+
'$pword = Read-Host -AsSecureString',
93+
'$pword = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword)',
94+
'$pword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($pword)',
95+
'echo $pword',
96+
]));
97+
98+
$in = \rtrim(\shell_exec($cmd), "\r\n");
99+
100+
if ('' === $in && null !== $default) {
101+
return $default;
102+
}
103+
104+
return $fn ? $fn($in) : $in;
105+
}
73106
}

0 commit comments

Comments
 (0)