Skip to content

Commit

Permalink
[Feat] Exit prompt confirmation (#219)
Browse files Browse the repository at this point in the history
* feat: exit prompt confrimation

* use static function

* add pcntl_* support

* style: prompt start with new lines

* update using variable
  • Loading branch information
SonyPradana authored Oct 11, 2023
1 parent 19f24a2 commit 9209ef5
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions src/System/Console/helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, callable> $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);
}
}
}

0 comments on commit 9209ef5

Please sign in to comment.