diff --git a/src/Console/Getch.php b/src/Console/Getch.php index a4b3b19..89ac3fa 100644 --- a/src/Console/Getch.php +++ b/src/Console/Getch.php @@ -31,13 +31,13 @@ final class Getch if (self::$ffi === null) { $osFamily = PHP_OS_FAMILY; if ($osFamily === 'Windows') { - self::$ffi = FFI::cdef('char _getch();', self::WINDOWS_LIBRARY); + self::$ffi = FFI::cdef('char _getch(); int _ungetch(char c);', self::WINDOWS_LIBRARY); } elseif ($osFamily === 'Linux') { if (!file_exists($linuxLibrary)) { throw new RuntimeException(sprintf('Could not find library file %s.', $linuxLibrary)); } - self::$ffi = FFI::cdef('char _getch(); int _ungetch(int ch);', $linuxLibrary); + self::$ffi = FFI::cdef('char _getch(); int _ungetch(char ch);', $linuxLibrary); } else { throw new RuntimeException(sprintf('Sorry, %s is not supported yet.', $osFamily)); } @@ -51,6 +51,21 @@ final class Getch public function ungetch(string $char) { - return self::$ffi->_ungetch($char); + return self::$ffi->_ungetch($char[0]); + } + + public function ungetchString(string $string): bool + { + $stringReverse = \strrev($string); + $result = false; + + foreach(\str_split($stringReverse) as $char) { + $result = self::$ffi->_ungetch($char) > 0; + if(!$result) { + return false; + } + } + + return $result; } } diff --git a/src/Console/Resources/getch.c b/src/Console/Resources/getch.c index 5f2e769..5fc5211 100644 --- a/src/Console/Resources/getch.c +++ b/src/Console/Resources/getch.c @@ -16,7 +16,7 @@ int _getch(void) return ch; } -int _ungetch(int ch) +int _ungetch(char ch) { return ungetc(ch, stdin); } \ No newline at end of file diff --git a/src/Console/function.php b/src/Console/function.php index 35f68b4..076c1ab 100644 --- a/src/Console/function.php +++ b/src/Console/function.php @@ -28,3 +28,12 @@ if(!function_exists('ungetch')) { return $g->ungetch($char); } } + +if(!function_exists('ungetchString')) { + function ungetchString(string $string, string $linuxLibrary = null): bool + { + $g = new Getch($linuxLibrary); + + return $g->ungetchString($string); + } +}