From 9209ef5b2820e945ad5182aac24bfc7e6a219454 Mon Sep 17 00:00:00 2001 From: Angger Pradana Date: Thu, 12 Oct 2023 00:19:12 +0700 Subject: [PATCH] [Feat] Exit prompt confirmation (#219) * feat: exit prompt confrimation * use static function * add pcntl_* support * style: prompt start with new lines * update using variable --- src/System/Console/helper.php | 54 +++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/src/System/Console/helper.php b/src/System/Console/helper.php index ba02c188..e8753e59 100644 --- a/src/System/Console/helper.php +++ b/src/System/Console/helper.php @@ -167,3 +167,57 @@ public function width(int $min, int $max): int return $terminal->width($min, $max); } } + +if (!function_exists('exit_prompt')) { + /** + * Register ctrl+c event. + * + * @param string|Style $title + * @param array $options + */ + function exit_prompt($title, array $options = null): void + { + $signal = defined('SIGINT') ? constant('SIGINT') : 2; + $options ??= [ + 'yes' => static function () use ($signal) { + if (function_exists('posix_kill') && function_exists('posix_getpid')) { + posix_kill(posix_getgid(), $signal); + } + + exit(128 + $signal); + }, + 'no' => fn () => null, + ]; + + if (function_exists('sapi_windows_set_ctrl_handler') && 'cli' === PHP_SAPI) { + sapi_windows_set_ctrl_handler(static function (int $event) use ($title, $options) { + if (PHP_WINDOWS_EVENT_CTRL_C === $event) { + (new Style())->out(); + (new Prompt($title, $options, 'no'))->option(); + } + }); + } + + if (function_exists('pcntl_signal')) { + pcntl_signal($signal, $options['yes']); + } + } +} + +if (!function_exists('remove_exit_prompt')) { + /** + * Remove ctrl-c handle. + */ + function remove_exit_prompt(): void + { + if (function_exists('sapi_windows_set_ctrl_handler') && 'cli' === PHP_SAPI) { + sapi_windows_set_ctrl_handler(function (int $handler): void {}, false); + } + + $signal = defined('SIGINT') ? constant('SIGINT') : 2; + $default = defined('SIG_DFL') ? constant('SIG_DFL') : 0; + if (function_exists('pcntl_signal')) { + pcntl_signal($signal, $default); + } + } +}