-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprevent-quit.php
More file actions
60 lines (51 loc) · 1.63 KB
/
prevent-quit.php
File metadata and controls
60 lines (51 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php
declare(strict_types=1);
/**
* "Prevent quit" demo — eat Ctrl+C until the user confirms.
*
* php examples/prevent-quit.php
*
* Press Ctrl+C. The first press flips the model into 'really quit?'
* mode. Press 'y' to confirm or 'n' / Esc to cancel.
*/
require __DIR__ . '/../vendor/autoload.php';
use SugarCraft\Core\Cmd;
use SugarCraft\Core\KeyType;
use SugarCraft\Core\Model;
use SugarCraft\Core\Msg;
use SugarCraft\Core\Msg\KeyMsg;
use SugarCraft\Core\Program;
use SugarCraft\Core\ProgramOptions;
final class PreventQuit implements Model
{
public function __construct(public readonly bool $confirming = false) {}
public function init(): ?\Closure { return null; }
public function update(Msg $msg): array
{
if (!$msg instanceof KeyMsg) {
return [$this, null];
}
if ($this->confirming) {
return match (true) {
$msg->type === KeyType::Char && $msg->rune === 'y'
=> [$this, Cmd::quit()],
default
=> [new self(false), null],
};
}
if ($msg->ctrl && $msg->rune === 'c') {
return [new self(true), null];
}
return [$this, null];
}
public function view(): string
{
if ($this->confirming) {
return "Really quit? (y / n)\n";
}
return "Working hard. Press Ctrl+C to attempt quit.\n";
}
}
// Disable the runtime's built-in Ctrl-C handler so our update()
// gets the keystroke first. Quit happens explicitly via Cmd::quit().
(new Program(new PreventQuit(), new ProgramOptions(catchInterrupts: false)))->run();