99
1010namespace Toolkit \Cli \Traits ;
1111
12+ use Toolkit \Cli \Cli ;
13+ use Toolkit \Cli \Util \Readline ;
14+ use function fopen ;
15+ use function strip_tags ;
1216use const STDIN ;
1317
1418/**
@@ -35,7 +39,7 @@ trait ReadMessageTrait
3539 public static function read ($ message = null , bool $ nl = false , array $ opts = []): string
3640 {
3741 if ($ message ) {
38- self ::write ($ message , $ nl );
42+ Cli ::write ($ message , $ nl );
3943 }
4044
4145 $ opts = array_merge ([
@@ -61,9 +65,15 @@ public static function read($message = null, bool $nl = false, array $opts = [])
6165 public static function readln ($ message = null , bool $ nl = false , array $ opts = []): string
6266 {
6367 if ($ message ) {
64- self ::write ($ message , $ nl );
68+ Cli ::write ($ message , $ nl );
6569 }
6670
71+ // TIP: use readline method, support left and right press.
72+ if (Readline::isSupported ()) {
73+ return Readline::readline ();
74+ }
75+
76+ // read from input stream
6777 $ opts = array_merge ([
6878 'length ' => 1024 ,
6979 'stream ' => self ::$ inputStream ,
@@ -97,7 +107,7 @@ public static function readRow($message = null, bool $nl = false): string
97107 public static function readSafe ($ message = null , bool $ nl = false , array $ opts = []): string
98108 {
99109 if ($ message ) {
100- self ::write ($ message , $ nl );
110+ Cli ::write ($ message , $ nl );
101111 }
102112
103113 $ opts = array_merge ([
@@ -106,7 +116,9 @@ public static function readSafe($message = null, bool $nl = false, array $opts =
106116 'allowTags ' => null ,
107117 ], $ opts );
108118
109- return trim (fgetss ($ opts ['stream ' ], $ opts ['length ' ], $ opts ['allowTags ' ]));
119+ // up: fgetss has been DEPRECATED as of PHP 7.3.0
120+ // return trim(fgetss($opts['stream'], $opts['length'], $opts['allowTags']));
121+ return trim (strip_tags (fgets ($ opts ['stream ' ], $ opts ['length ' ]), $ opts ['allowTags ' ]));
110122 }
111123
112124 /**
@@ -137,6 +149,33 @@ public static function readFirst(string $message = '', bool $nl = false): string
137149 return self ::readChar ($ message , $ nl );
138150 }
139151
152+ /**
153+ * Read password text.
154+ * NOTICE: only support linux
155+ *
156+ * @param string $prompt
157+ *
158+ * @return string
159+ * @link https://www.php.net/manual/zh/function.readline.php#120729
160+ */
161+ public static function readPassword (string $ prompt = '' ): string
162+ {
163+ $ termDevice = '/dev/tty ' ;
164+ if ($ prompt ) {
165+ Cli::write ($ prompt );
166+ }
167+
168+ $ h = fopen ($ termDevice , 'rb ' );
169+ if ($ h === false ) {
170+ // throw new RuntimeException("Failed to open terminal device");
171+ return '' ; // probably not running in a terminal.
172+ }
173+
174+ $ line = trim ((string )fgets ($ h ));
175+ fclose ($ h );
176+ return $ line ;
177+ }
178+
140179 /**
141180 * @return false|resource
142181 */
0 commit comments