From 30d5bee61fa3f6c81d5990dd9c16b06987c04d00 Mon Sep 17 00:00:00 2001 From: Daniel Ronkainen Date: Mon, 30 Nov 2026 17:31:18 +0100 Subject: [PATCH 01/15] test: establish Prompts compatibility baseline --- composer.json | 15 ++- tests/unitary-compatibility.php | 209 ++++++++++++++++++++++++++++++++ 2 files changed, 223 insertions(+), 1 deletion(-) create mode 100644 tests/unitary-compatibility.php diff --git a/composer.json b/composer.json index aebdb0e..3d1edb9 100644 --- a/composer.json +++ b/composer.json @@ -27,16 +27,29 @@ "homepage": "https://wazabii.se" } ], + "scripts": { + "test": "php vendor/bin/unitary" + }, "require": { "php": ">=8.2", "maplephp/dto": "^3.1", "maplephp/http": "^2.0", "maplephp/validate": "^2.0" }, + "require-dev": { + "maplephp/unitary": "^3.0" + }, "autoload": { "psr-4": { "MaplePHP\\Prompts\\": "src" } }, - "minimum-stability": "dev" + "extra": { + "branch-alias": { + "dev-main": "1.2.x-dev", + "dev-develop": "1.2.x-dev" + } + }, + "minimum-stability": "dev", + "prefer-stable": true } diff --git a/tests/unitary-compatibility.php b/tests/unitary-compatibility.php new file mode 100644 index 0000000..db39f95 --- /dev/null +++ b/tests/unitary-compatibility.php @@ -0,0 +1,209 @@ +getAnsi()->disableAnsi(disableAnsi: true); + $this->answers = $answers; + } + + public function readline(string $message): string + { + $this->getStream()->write("$message: "); + return array_shift($this->answers) ?? throw new LogicException('The scripted input is exhausted'); + } +} + +function promptsCompatibilityPrompt(PromptsCompatibilityCommand $command): Prompt +{ + $prompt = new Prompt(); + // Supply finite input through the command used by the legacy constructor. + (new ReflectionProperty(Prompt::class, 'command'))->setValue($prompt, $command); + return $prompt; +} + +group('Composer loads Prompts from the checkout under test', static function (TestCase $case) { + $root = dirname(__DIR__); + $case->expect(realpath(InstalledVersions::getInstallPath('maplephp/prompts')) === $root) + ->isTrue()->validate(); + + foreach ([Command::class, Prompt::class, SttyWrapper::class, Ansi::class, Blocks::class] as $class) { + $relativeName = substr($class, strlen('MaplePHP\\Prompts\\')); + $expectedPath = "$root/src/" . str_replace('\\', '/', $relativeName) . '.php'; + $case->expect((new ReflectionClass($class))->getFileName() === realpath($expectedPath)) + ->isTrue()->validate($class); + } +}); + +group('Command preserves named stream and output parameters', static function (TestCase $case) { + $original = new Stream('php://memory'); + $output = new Stream('php://memory'); + $command = new Command(stream: new Response($original)); + $copy = $command->withStream(stream: $output); + $copy->getAnsi()->disableAnsi(disableAnsi: true); + + $case->expect($copy !== $command && $command->getStream() === $original && $copy->getStream() === $output) + ->isTrue()->validate(); + $case->expect($copy->getStty() instanceof SttyWrapper)->isTrue()->validate(); + $case->expect($command->message(message: 'original', getLine: false))->isFalse()->validate(); + $case->expect($copy->message(message: 'message'))->isFalse()->validate(); + $copy->title(message: 'title', break: false); + $case->expect($copy->approve(message: ' approved'))->isFalse()->validate(); + $case->expect($copy->statusMsg(message: 'status', break: false))->isFalse()->validate(); + $case->expect($copy->error(message: ' error'))->isFalse()->validate(); + $copy->progress(expectedRows: 5, maxLength: 5, sleep: 0); + + $case->expect((string) $original)->isEqualTo("original\n")->validate(); + $case->expect((string) $output)->isEqualTo("message\ntitle approved\nstatus error\n-----\n")->validate(); +}); + +group('Command keeps fallback prompts and returns the original option key', static function (TestCase $case) { + $output = new Stream('php://memory'); + $command = new PromptsCompatibilityCommand($output, '0', '2', 'no', ' YES ', ' one, two '); + + $case->expect($command->inputSelect(message: 'Choose', choices: [4 => 'First', 'second' => 'Second'])) + ->isEqualTo('second')->validate(); + $case->expect($command->inputToggle(message: 'Toggle') === 0)->isTrue()->validate(); + $case->expect($command->confirm(message: 'Confirm'))->isTrue()->validate(); + $case->expect($command->list(message: 'List'))->isEqualTo(['one', 'two'])->validate(); + $case->expect(fn () => $command->inputSelect(message: 'Choose', choices: [])) + ->isThrowable(InvalidArgumentException::class)->validate(); + + $menu = "Choose (1-2)\n1: First\n2: Second\nInput your answer: "; + $case->expect((string) $output)->isEqualTo( + $menu . $menu . "Toggle\nType 'yes' or 'no': Confirm\n" . + "Type 'yes' to continue and 'no' to abort': List (comma separate): " + )->validate(); +}); + +group('Ansi preserves plain and terminal output for legacy styles', static function (TestCase $case) { + $ansi = new Ansi(); + $dashed = $ansi->supportsUnicode() ? "─\u{200A}─\u{200A}" : '──'; + $styles = $ansi->isSupported() ? "\033[34m\033[1mTitle\033[0m\033[0m" : 'Title'; + $line = $ansi->isSupported() ? "\033[1;34m───\033[0m" : '───'; + + $case->expect($ansi->style(styles: ['bold', 'blue'], message: 'Title'))->isEqualTo($styles)->validate(); + $case->expect($ansi->line(lineLength: 3, color: 34))->isEqualTo($line)->validate(); + $case->expect($ansi->middot())->isEqualTo($ansi->isSupported() ? '•' : '.')->validate(); + $case->expect(fn () => $ansi->style(styles: 'absent', message: 'Title')) + ->isThrowable(InvalidArgumentException::class)->validate(); + $ansi->disableAnsi(disableAnsi: true); + $case->expect($ansi->style(styles: 'bold', message: 'Title'))->isEqualTo('Title')->validate(); + $case->expect($ansi->dashedLine(lineLength: 4, color: 34))->isEqualTo($dashed)->validate(); + $case->expect($ansi->middot())->isEqualTo('.')->validate(); +}); + +group('Blocks preserves the legacy section, row and example layout', static function (TestCase $case) { + $output = new Stream('php://memory'); + $command = new Command(stream: $output); + $command->getAnsi()->disableAnsi(disableAnsi: true); + $blocks = new Blocks(command: $command); + + $blocks->addHeadline(title: 'Help', addStyle: 'blue'); + $blocks->addSection(title: 'Summary', description: 'Run a command.'); + $blocks->addSection(title: 'Usage', description: static function (Blocks $section) use ($case): Blocks { + $copy = $section->addOption(option: '-h', description: 'Short help') + ->addOption(option: '--help', description: 'Show help') + ->addList(option: 'run', description: 'Run tests') + ->addList(option: 'test', description: 'Test locally') + ->addExamples(example: 'app run', description: 'Run all tests'); + $case->expect($copy !== $section)->isTrue()->validate(); + return $copy; + }); + $blocks->addRow(description: static function (Blocks $row) use ($case): Blocks { + $cell = $row->addCell(option: 'A', description: 'First'); + $case->expect($cell === $row)->isTrue()->validate(); + return $row->addCell(option: 'BB', description: 'Second'); + }); + $blocks->addPadding(content: static function (Blocks $content): void { + $content->addText(title: 'End', addStyle: 'grey'); + }); + $blocks->addCode(code: 'new Command();'); + + $case->expect($blocks->severityLevel(severity: 'LOW', title: 'Low risk'))->isEqualTo('Low risk')->validate(); + $case->expect($blocks->severityLevel(severity: 'medium'))->isEqualTo('Medium')->validate(); + $case->expect((string) $output)->isEqualTo( + "Help\n\nSummary:\n Run a command.\n\nUsage:\n" . + " -h Short help\n --help Show help\nrun Run tests\ntest Test locally\n" . + " app run\n Run all tests\n[A ] First\n[BB ] Second\n \n\nEnd\n\n\nnew Command();\n\n" + )->validate(); +}); + +group('Prompt renders its legacy header before processing rows', static function (TestCase $case) { + $output = new Stream('php://memory'); + $prompt = promptsCompatibilityPrompt(new PromptsCompatibilityCommand($output)); + $case->expect($prompt->setTitle(title: 'Title')->setDescription(description: 'Details') === $prompt) + ->isTrue()->validate(); + $case->expect($prompt->prompt())->isEqualTo([])->validate(); + $case->expect((string) $output)->isEqualTo("\nExit the prompt with [CTRL + C]\n\nTitle\nDetails\n\n") + ->validate(); +}); + +group('Prompt consumes completed rows and retains an aborted row for the next run', static function (TestCase $case) { + $output = new Stream('php://memory'); + $command = new PromptsCompatibilityCommand($output, '0', 'no', 'yes', ''); + $prompt = promptsCompatibilityPrompt($command); + $previous = []; + $case->expect($prompt->disableHeaderInfo(disable: true)->set(data: [ + 'notice' => ['type' => 'message', 'message' => 'Notice'], + 'first' => ['message' => 'First', 'default' => 'unused'], + 'skip' => [ + 'type' => 'continue', + 'items' => static function (mixed $value, int $index) use (&$previous): bool { + $previous = [$value, $index]; + return false; + }, + ], + 'confirm' => ['type' => 'confirm', 'message' => 'Continue?'], + ])->add(name: 'last', data: ['message' => 'Last', 'default' => 'default']) === $prompt) + ->isTrue()->validate(); + + $case->expect($prompt->getCommand() === $command)->isTrue()->validate(); + $case->expect($prompt->prompt())->isFalse()->validate(); + $case->expect($previous)->isEqualTo(['0', 2])->validate(); + $case->expect($prompt->prompt() === ['confirm' => 1, 'last' => 'default'])->isTrue()->validate(); + $case->expect($prompt->prompt())->isEqualTo([])->validate(); + $case->expect((string) $output)->isEqualTo( + "Notice\nFirst (unused): Continue?\nType 'yes' to continue and 'no' to abort': Aborted...\n" . + "Continue?\nType 'yes' to continue and 'no' to abort': Last (default): " + )->validate(); +}); + +group('Prompt keeps callable validation polarity and built-in rule names', static function (TestCase $case) { + $output = new Stream('php://memory'); + $prompt = promptsCompatibilityPrompt(new PromptsCompatibilityCommand($output, 'rejected', 'accepted', 'x', 'long')); + $errors = []; + $report = static function (?string $reason, mixed $value, array $row) use (&$errors): string { + $errors[] = [$reason, $value, $row['message']]; + return 'Try again'; + }; + + $case->expect($prompt->promptLine(row: [ + 'message' => 'Callable', + 'validate' => static fn (string $value): bool => $value === 'rejected', + 'error' => $report, + ]))->isEqualTo('accepted')->validate(); + $case->expect($prompt->promptLine(row: [ + 'message' => 'Rule', + 'validate' => ['length' => [2, 10]], + 'error' => $report, + ]))->isEqualTo('long')->validate(); + $case->expect($errors === [[null, 'rejected', 'Callable'], ['length', 'x', 'Rule']])->isTrue()->validate(); + $case->expect((string) $output)->isEqualTo("Callable: Try again\nCallable: Rule: Try again\nRule: ")->validate(); +}); From 42f8a81e2ff30f445ba8978048c3106471553aba Mon Sep 17 00:00:00 2001 From: Daniel Ronkainen Date: Mon, 30 Nov 2026 17:41:07 +0100 Subject: [PATCH 02/15] fix: separate prompt input from output --- src/Command.php | 281 +++++++++++++++---- src/Exceptions/InputExhaustedException.php | 11 + src/Exceptions/InputInterruptedException.php | 11 + src/Prompt.php | 26 +- src/SttyWrapper.php | 31 ++ src/WindowsPasswordReader.php | 80 ++++++ tests/unitary-compatibility.php | 14 +- tests/unitary-input.php | 226 +++++++++++++++ 8 files changed, 610 insertions(+), 70 deletions(-) create mode 100644 src/Exceptions/InputExhaustedException.php create mode 100644 src/Exceptions/InputInterruptedException.php create mode 100644 src/WindowsPasswordReader.php create mode 100644 tests/unitary-input.php diff --git a/src/Command.php b/src/Command.php index 65d7969..95c3582 100755 --- a/src/Command.php +++ b/src/Command.php @@ -5,6 +5,9 @@ use Exception; use InvalidArgumentException; use MaplePHP\Http\Stream; +use MaplePHP\Prompts\Exceptions\InputExhaustedException; +use MaplePHP\Prompts\Exceptions\InputInterruptedException; +use MaplePHP\Prompts\Exceptions\PromptException; use MaplePHP\Prompts\Themes\Ansi; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\StreamInterface; @@ -16,15 +19,17 @@ class Command { private StreamInterface $stream; + private ?StreamInterface $input; private SttyWrapper $stty; private Ansi $ansi; - public function __construct(StreamInterface|ResponseInterface|null $stream = null) - { - // This is the stream we want to use, 9/10 times - + public function __construct( + StreamInterface|ResponseInterface|null $stream = null, + ?StreamInterface $input = null + ) { $stream = ($stream instanceof ResponseInterface) ? $stream->getBody() : $stream; - $this->stream = $stream === null ? new Stream(Stream::STDOUT) : $stream; + $this->stream = $stream ?? new Stream(Stream::STDOUT); + $this->input = $input; $this->stty = new SttyWrapper(); $this->ansi = new Ansi(); @@ -53,6 +58,25 @@ public function getStream(): StreamInterface return $this->stream; } + /** + * Get the input stream independently of the output stream. + */ + public function getInput(): StreamInterface + { + return $this->input ??= (defined('STDIN') ? new Stream(STDIN) : new Stream(Stream::STDIN, 'rb')); + } + + /** + * Whether the input uses the process's terminal on standard input. + */ + public function hasTerminalInput(): bool + { + return defined('STDIN') && + ($this->input === null || ($this->input instanceof Stream && + ($this->input->getResource() === STDIN || $this->input->getStream() === Stream::STDIN))) && + $this->standardInputIsTerminal(); + } + /** * Get SttyWrapper * @@ -78,15 +102,41 @@ public function getAnsi(): Ansi * * @param string $message * @return string + * @throws InputExhaustedException */ public function readline(string $message): string { - if (function_exists("readline")) { - return readline("$message: "); + if (function_exists('readline') && defined('STDIN') && is_resource(STDIN) && + !stream_get_meta_data(STDIN)['unread_bytes'] && $this->hasTerminalInput() && + defined('STDOUT') && stream_isatty(STDOUT) && + $this->stream instanceof Stream && + ($this->stream->getResource() === STDOUT || $this->stream->getStream() === Stream::STDOUT) && + ($this->input === null || !$this->input->getMetadata('unread_bytes'))) { + $line = readline("$message: "); + if ($line === false) { + throw new InputExhaustedException(); + } + return $line; } - $this->stream->write("$message: "); - return (string)$this->stream->getLine(); + $this->write("$message: ", false); + return $this->readInputLine(); + } + + /** + * Ask for a line of input. + */ + public function ask(string $message): string + { + return $this->readline($message); + } + + /** + * Write a line of output. + */ + public function line(string $message = '', bool $break = true): void + { + $this->write($message, $break); } /** @@ -99,9 +149,9 @@ public function readline(string $message): string public function message(string $message, bool $getLine = false): string|false { if ($getLine) { - return $this->readline($message); + return $this->ask($message); } - $this->write($message); + $this->line($message); return false; } @@ -123,6 +173,7 @@ public function title(string $message, bool $break = true): void * @param string $message * @param bool $break Add new line * @return string|false + * @deprecated Use success() to display a success message. */ public function approve(string $message, bool $break = true): string|false { @@ -130,12 +181,21 @@ public function approve(string $message, bool $break = true): string|false return false; } + /** + * Display a success message. + */ + public function success(string $message, bool $break = true): void + { + $this->approve($message, $break); + } + /** * Display a status message * * @param string $message * @param bool $break Add new line * @return string|false + * @deprecated Use status() to display a status message. */ public function statusMsg(string $message, bool $break = true): string|false { @@ -143,6 +203,22 @@ public function statusMsg(string $message, bool $break = true): string|false return false; } + /** + * Display a status message. + */ + public function status(string $message, bool $break = true): void + { + $this->statusMsg($message, $break); + } + + /** + * Display a warning message. + */ + public function warning(string $message, bool $break = true): void + { + $this->write($this->getAnsi()->yellow($message), $break); + } + /** * Display a error message * @@ -203,20 +279,20 @@ public function inputSelect(string $message, array $choices): int|string throw new InvalidArgumentException("You cannot input an empty array!", 1); } - $int = 1; + $keys = array_keys($choices); $length = count($choices); - $this->message(sprintf($this->getAnsi()->bold($message . " (%d-%d)"), $int, $length)); - foreach ($choices as $value) { - $this->message($this->getAnsi()->style(["blue", "bold"], "$int:") . " $value"); - $int++; - } - $line = (int)$this->message("Input your answer", true); - if ($line > 0 && $line <= $length) { - $index = $line - 1; - $values = array_keys($choices); - return $values[$index] ?? $index; + while (true) { + $int = 1; + $this->message($this->getAnsi()->bold($message . " (1-$length)")); + foreach ($choices as $value) { + $this->message($this->getAnsi()->style(["blue", "bold"], "$int:") . " $value"); + $int++; + } + $line = (int)$this->message("Input your answer", true); + if ($line > 0 && $line <= $length) { + return $keys[$line - 1]; + } } - return $this->inputSelect($message, $choices); } /** @@ -249,38 +325,40 @@ public function toggle(string $message): int|string */ public function inputToggle(string $message): int|string { - $this->message($this->getAnsi()->bold($message)); - $line = strtolower((string)$this->message("Type 'yes' or 'no'", true)); - - if ($line === "yes" || $line === "no") { - return (int)($line === "yes"); - } - return $this->toggle($message); + do { + $this->message($this->getAnsi()->bold($message)); + $line = strtolower((string)$this->message("Type 'yes' or 'no'", true)); + } while ($line !== "yes" && $line !== "no"); + return (int)($line === "yes"); } /** - * Get a masked input if supported, otherwise get unmasked input + * Read a line without echoing terminal input. * * @param string $message * @return string */ public function mask(string $message): string { - if (function_exists("system")) { - //ob_start(); - $this->stream->write("$message (masked input): "); - if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { - // Not yet tested. But should work if my research is right - $input = rtrim((string)exec("powershell -Command \$input = Read-Host -AsSecureString; [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR(\$input))")); - } else { - $input = rtrim((string)exec((string)$this->stty->maskInput())); + if (!$this->hasTerminalInput()) { + if ($this->isUnverifiedTerminalInput()) { + throw new PromptException('Masked input requires the terminal on standard input.'); } - $this->stream->write("\n"); - //ob_get_clean(); - return $input; + return $this->readMaskedLine($message); } - $this->message("Warning: The input will not be masked. The PHP function \"system\" is disabled."); - return (string)$this->message($message, true); + if (PHP_OS_FAMILY === 'Windows') { + return (new WindowsPasswordReader())->read( + fn () => $this->write("$message (masked input): ", false), + fn () => $this->write('') + ); + } + + // Read Ctrl+C as a byte so that PHP builds without pcntl restore the terminal. + return $this->getStty()->withTerminalMode( + fn (): string => $this->readMaskedLine($message, terminal: true), + '-echo', '-echonl', '-icanon', '-isig', '-iexten', '-ixon', + '-igncr', '-inlcr', 'icrnl', 'min', '1', 'time', '0' + ); } /** @@ -291,15 +369,11 @@ public function mask(string $message): string */ public function confirm(string $message): bool { - $this->message($this->getAnsi()->style(["yellow", "bold"], $message)); - $line = trim(strtolower((string)$this->message("Type 'yes' to continue and 'no' to abort'", true))); - - if ($line === "yes") { - return true; - } elseif ($line === "no") { - return false; - } - return $this->confirm($message); + do { + $this->message($this->getAnsi()->style(["yellow", "bold"], $message)); + $line = trim(strtolower((string)$this->message("Type 'yes' to continue and 'no' to abort'", true))); + } while ($line !== "yes" && $line !== "no"); + return $line === "yes"; } /** @@ -330,6 +404,107 @@ public function progress(int $expectedRows, int $maxLength = 100, null|int|calla $this->stream->write("\n"); } + private function standardInputIsTerminal(): bool + { + if (!defined('STDIN') || !is_resource(STDIN)) { + return false; + } + if (!stream_get_meta_data(STDIN)['unread_bytes']) { + return stream_isatty(STDIN); + } + + // Older PHP versions can disturb buffered input when casting a stream for stream_isatty(). + $probe = new Stream(Stream::STDIN, 'rb'); + try { + return stream_isatty($probe->getResource()); + } finally { + $probe->close(); + } + } + + private function isUnverifiedTerminalInput(): bool + { + if ($this->input === null) { + return false; + } + $uri = $this->input->getMetadata('uri'); + if ($uri === Stream::STDIN || $uri === 'php://fd/0') { + return $this->standardInputIsTerminal(); + } + if ($this->input instanceof Stream) { + $resource = $this->input->getResource(); + if (!is_resource($resource)) { + return false; + } + if ($this->input->getMetadata('unread_bytes')) { + // Avoid casting an input with pending bytes. TTYs are character devices. + $stat = fstat($resource); + return $stat === false || ($stat['mode'] & 0170000) === 0020000; + } + return stream_isatty($resource); + } + return is_string($uri) && preg_match('~^(?:/dev/(?:tty[^/]*|pts/[0-9]+)|CONIN\$)$~iD', $uri) === 1; + } + + private function readInputLine(bool $maskedTerminal = false): string + { + $input = $this->getInput(); + $line = ''; + while (true) { + // A PSR stream can be non-seekable. Stop at the line break without consuming the next answer. + $byte = $input->read(1); + if ($byte === '') { + if (!$input->eof()) { + throw new PromptException('The input stream did not return any data.'); + } + break; + } + if ($byte === "\n") { + return str_ends_with($line, "\r") ? substr($line, 0, -1) : $line; + } + if ($maskedTerminal) { + switch ($byte) { + case "\x03": + throw new InputInterruptedException(); + case "\x04": + break 2; + case "\x08": + case "\x7f": + $line = $this->eraseLastCharacter($line); + continue 2; + case "\x15": + $line = ''; + continue 2; + } + } + $line .= $byte; + } + if ($line === '') { + throw new InputExhaustedException(); + } + return $line; + } + + private function eraseLastCharacter(string $line): string + { + $index = strlen($line) - 1; + // Include the leading byte when erasing a UTF-8 character. + while ($index > 0 && (ord($line[$index]) & 0xc0) === 0x80) { + $index--; + } + return substr($line, 0, max(0, $index)); + } + + private function readMaskedLine(string $message, bool $terminal = false): string + { + $this->write("$message (masked input): ", false); + try { + return $this->readInputLine($terminal); + } finally { + $this->write(''); + } + } + /** * Progress appearance * diff --git a/src/Exceptions/InputExhaustedException.php b/src/Exceptions/InputExhaustedException.php new file mode 100644 index 0000000..7ee41c6 --- /dev/null +++ b/src/Exceptions/InputExhaustedException.php @@ -0,0 +1,11 @@ +command = new Command(); + $this->command = $command ?? new Command(); } /** @@ -115,7 +117,7 @@ public function promptLine(array $row): mixed $rowType = $row['type'] ?? "text"; $confirm = $row['confirm'] ?? false; - if (isset($default) && is_string($default) && strlen($default)) { + if (is_string($default) && $default !== "" && !in_array($rowType, ["invisible", "mask", "password"], true)) { $message .= " ($default)"; } @@ -164,10 +166,13 @@ public function promptLine(array $row): mixed if (!is_array($items)) { throw new InvalidArgumentException("The items must return a a valid array"); } - $inst = new self(); + $inst = new self($this->command); $inst->disableHeaderInfo(true); $inst->data = $items; - $input = $inst->prompt(); + $input = $inst->run(); + if ($input === false) { + return false; + } break; } @@ -205,9 +210,18 @@ public function promptLine(array $row): mixed * * @return array|false * @throws ErrorException - * @throws PromptException|\MaplePHP\Prompts\PromptException + * @throws PromptException */ public function prompt(): array|false + { + try { + return $this->run(); + } catch (InputExhaustedException | InputInterruptedException) { + return false; + } + } + + private function run(): array|false { $result = []; $this->index = 0; diff --git a/src/SttyWrapper.php b/src/SttyWrapper.php index 9481175..13592c4 100755 --- a/src/SttyWrapper.php +++ b/src/SttyWrapper.php @@ -2,6 +2,8 @@ namespace MaplePHP\Prompts; +use MaplePHP\Prompts\Exceptions\PromptException; + /** * Class SttyWrapper * @package MaplePHP\Prompts @@ -133,4 +135,33 @@ public function hasSttySupport(): bool } return false; } + + /** + * Apply settings to standard input for the duration of a terminal operation. + * + * @throws PromptException + */ + public function withTerminalMode(callable $callback, string ...$settings): mixed + { + $previous = $this->runStty('-g'); + try { + $this->runStty(...$settings); + return $callback(); + } finally { + $this->runStty($previous); + } + } + + private function runStty(string ...$settings): string + { + if (!function_exists('exec') || !$this->isUnix()) { + throw new PromptException('Could not configure the terminal with stty.'); + } + $arguments = implode(' ', array_map('escapeshellarg', $settings)); + $state = exec("stty $arguments 2>/dev/null", $output, $status); + if ($status !== 0 || $state === false) { + throw new PromptException('Could not configure the terminal with stty.'); + } + return $state; + } } diff --git a/src/WindowsPasswordReader.php b/src/WindowsPasswordReader.php new file mode 100644 index 0000000..7ae193b --- /dev/null +++ b/src/WindowsPasswordReader.php @@ -0,0 +1,80 @@ + STDIN, 1 => ['pipe', 'w'], 2 => ['file', 'NUL', 'w']], + $pipes, + options: ['bypass_shell' => true] + ); + if (!is_resource($process)) { + throw new PromptException('Could not disable terminal echo for masked input.'); + } + try { + if (fread($pipes[1], 1) !== "\n") { + throw new PromptException('Could not disable terminal echo for masked input.'); + } + $start(); + try { + $line = stream_get_contents($pipes[1]); + } finally { + $finish(); + } + } finally { + // An output stream failure can leave the child waiting for a key. + if (!isset($line)) { + proc_terminate($process); + } + fclose($pipes[1]); + $status = proc_close($process); + } + if ($status === 2) { + throw new InputInterruptedException(); + } + if ($status === 3) { + throw new InputExhaustedException(); + } + if ($status !== 0 || $line === false) { + throw new PromptException('Could not read masked input.'); + } + return $line; + } +} diff --git a/tests/unitary-compatibility.php b/tests/unitary-compatibility.php index db39f95..c96d7c7 100644 --- a/tests/unitary-compatibility.php +++ b/tests/unitary-compatibility.php @@ -30,14 +30,6 @@ public function readline(string $message): string } } -function promptsCompatibilityPrompt(PromptsCompatibilityCommand $command): Prompt -{ - $prompt = new Prompt(); - // Supply finite input through the command used by the legacy constructor. - (new ReflectionProperty(Prompt::class, 'command'))->setValue($prompt, $command); - return $prompt; -} - group('Composer loads Prompts from the checkout under test', static function (TestCase $case) { $root = dirname(__DIR__); $case->expect(realpath(InstalledVersions::getInstallPath('maplephp/prompts')) === $root) @@ -147,7 +139,7 @@ function promptsCompatibilityPrompt(PromptsCompatibilityCommand $command): Promp group('Prompt renders its legacy header before processing rows', static function (TestCase $case) { $output = new Stream('php://memory'); - $prompt = promptsCompatibilityPrompt(new PromptsCompatibilityCommand($output)); + $prompt = new Prompt(new PromptsCompatibilityCommand($output)); $case->expect($prompt->setTitle(title: 'Title')->setDescription(description: 'Details') === $prompt) ->isTrue()->validate(); $case->expect($prompt->prompt())->isEqualTo([])->validate(); @@ -158,7 +150,7 @@ function promptsCompatibilityPrompt(PromptsCompatibilityCommand $command): Promp group('Prompt consumes completed rows and retains an aborted row for the next run', static function (TestCase $case) { $output = new Stream('php://memory'); $command = new PromptsCompatibilityCommand($output, '0', 'no', 'yes', ''); - $prompt = promptsCompatibilityPrompt($command); + $prompt = new Prompt($command); $previous = []; $case->expect($prompt->disableHeaderInfo(disable: true)->set(data: [ 'notice' => ['type' => 'message', 'message' => 'Notice'], @@ -187,7 +179,7 @@ function promptsCompatibilityPrompt(PromptsCompatibilityCommand $command): Promp group('Prompt keeps callable validation polarity and built-in rule names', static function (TestCase $case) { $output = new Stream('php://memory'); - $prompt = promptsCompatibilityPrompt(new PromptsCompatibilityCommand($output, 'rejected', 'accepted', 'x', 'long')); + $prompt = new Prompt(new PromptsCompatibilityCommand($output, 'rejected', 'accepted', 'x', 'long')); $errors = []; $report = static function (?string $reason, mixed $value, array $row) use (&$errors): string { $errors[] = [$reason, $value, $row['message']]; diff --git a/tests/unitary-input.php b/tests/unitary-input.php new file mode 100644 index 0000000..0d840c1 --- /dev/null +++ b/tests/unitary-input.php @@ -0,0 +1,226 @@ +offset; + } + + public function eof(): bool + { + return !$this->blocked && $this->offset === strlen($this->data); + } + + public function isSeekable(): bool + { + return false; + } + + public function seek(int $offset, int $whence = SEEK_SET): void + { + throw new RuntimeException('The input stream is not seekable'); + } + + public function rewind(): void + { + throw new RuntimeException('The input stream is not seekable'); + } + + public function isWritable(): bool + { + return false; + } + + public function write(string $string): int + { + throw new RuntimeException('The input stream is not writable'); + } + + public function isReadable(): bool + { + return true; + } + + public function read(int $length): string + { + if ($this->blocked) { + return ''; + } + $chunk = substr($this->data, $this->offset, $length); + $this->offset += strlen($chunk); + return $chunk; + } + + public function getContents(): string + { + throw new RuntimeException('The test requires incremental reads'); + } + + public function getMetadata(?string $key = null): mixed + { + return $key === null ? [] : null; + } +} + +group('Command reads a generic PSR input separately from write-only output', static function (TestCase $case) { + $path = tempnam(sys_get_temp_dir(), 'prompts-output-'); + $output = new Stream($path, 'wb'); + try { + $input = new PromptsPsrInput("\r\n0\n two spaces \t\r\nfinal\r"); + $command = new Command(stream: $output, input: $input); + $command->getAnsi()->disableAnsi(true); + $case->expect($command->getInput() === $input && !$output->isReadable())->isTrue()->validate(); + $case->expect($command->ask(message: 'Blank') === '')->isTrue()->validate(); + $case->expect($command->message(message: 'Zero', getLine: true) === '0')->isTrue()->validate(); + $case->expect($command->readline(message: 'Whitespace') === " two spaces \t")->isTrue()->validate(); + $copy = $command->withStream(new Stream('php://memory')); + $case->expect($copy->getInput() === $input && $copy->ask('Final') === "final\r")->isTrue()->validate(); + $case->expect(fn () => $command->ask('Exhausted'))->isThrowable(InputExhaustedException::class)->validate(); + $command->line('!'); + $command->line(); + $command->success(message: 'Success', break: false); + $command->status(message: ' Status'); + $command->warning(message: 'Warning'); + } finally { + $output->close(); + $written = file_get_contents($path); + unlink($path); + } + $case->expect($written)->isEqualTo("Blank: Zero: Whitespace: Exhausted: !\n\nSuccess Status\nWarning\n")->validate(); +}); + +group('Command line fallbacks retry and stop when input is exhausted', static function (TestCase $case) { + $output = new Stream('php://memory'); + $command = new Command(stream: $output, input: new PromptsPsrInput(str_repeat("invalid\n", 10000) . "no\n")); + $command->getAnsi()->disableAnsi(true); + $case->expect($command->inputToggle('Toggle') === 0)->isTrue()->validate(); + + foreach ([ + static fn (Command $command) => $command->confirm('Confirm'), + static fn (Command $command) => $command->inputSelect('Choose', ['key' => 'Option']), + static fn (Command $command) => $command->list('List'), + ] as $read) { + $empty = new Command(stream: $output, input: new PromptsPsrInput('')); + $case->expect(fn () => $read($empty))->isThrowable(InputExhaustedException::class)->validate(); + } + $blocked = new Command(stream: $output, input: new PromptsPsrInput('', blocked: true)); + $case->expect(fn () => $blocked->ask('Blocked'))->isThrowable(PromptException::class)->validate(); +}); + +group('Masked input preserves whitespace and keeps passwords out of output', static function (TestCase $case) { + $output = new Stream('php://memory'); + $command = new Command(stream: $output, input: new PromptsPsrInput(" secret \\ \t\r\n\n")); + $prompt = new Prompt(command: $command); + $case->expect($command->mask('Password') === " secret \\ \t")->isTrue()->validate(); + $case->expect($prompt->promptLine([ + 'type' => 'password', + 'message' => 'Use default', + 'default' => 'default secret', + ]) === 'default secret')->isTrue()->validate(); + $case->expect(fn () => $command->mask('Exhausted'))->isThrowable(InputExhaustedException::class)->validate(); + $case->expect((string)$output) + ->isEqualTo("Password (masked input): \nUse default (masked input): \nExhausted (masked input): \n")->validate(); +}); + +group('Nested prompts consume the same input and propagate aborts', static function (TestCase $case) { + $row = ['type' => 'continue', 'items' => [ + 'first' => ['message' => 'First'], + 'confirm' => ['type' => 'confirm', 'message' => 'Confirm'], + ]]; + $data = ['nested' => $row, 'last' => ['message' => 'Last']]; + + $output = new Stream('php://memory'); + $command = new Command(stream: $output, input: new PromptsPsrInput("inside\nyes\n0")); + $command->getAnsi()->disableAnsi(true); + $prompt = (new Prompt($command))->disableHeaderInfo(true); + $case->expect($prompt->set($data)->prompt() === [ + 'nested' => ['first' => 'inside', 'confirm' => 1], + 'last' => '0', + ])->isTrue()->validate(); + $case->expect((string)$output) + ->isEqualTo("First: Confirm\nType 'yes' to continue and 'no' to abort': Last: ")->validate(); + + foreach (["inside\nno\n", "inside\n"] as $answers) { + $output = new Stream('php://memory'); + $prompt = (new Prompt(new Command(stream: $output, input: new PromptsPsrInput($answers)))) + ->disableHeaderInfo(true); + $case->expect($prompt->set($data)->prompt())->isFalse()->validate(); + $case->expect(str_contains((string)$output, 'Last: '))->isFalse()->validate(); + } + + $prompt = new Prompt(new Command(stream: new Stream('php://memory'), input: new PromptsPsrInput(''))); + $case->expect(fn () => $prompt->promptLine($row))->isThrowable(InputExhaustedException::class)->validate(); + $case->expect(fn () => $prompt->promptLine(['message' => 'Default', 'default' => 'unused'])) + ->isThrowable(InputExhaustedException::class)->validate(); +}); + +group('Commands share real stdin when switching output streams', static function (TestCase $case) { + $code = <<<'PHP' + require 'vendor/autoload.php'; + + $command = new \MaplePHP\Prompts\Command(); + $output = new \MaplePHP\Http\Stream('php://memory'); + $copy = $command->withStream($output); + if ($command->ask('First') !== '0' || + $copy->ask('Second') !== 'second' || + $command->mask('Masked') !== " private\t" || + (string)$output !== 'Second: ') { + exit(1); + } + try { + $copy->ask('Exhausted'); + } catch (\MaplePHP\Prompts\Exceptions\InputExhaustedException) { + exit(0); + } + exit(1); + PHP; + $process = proc_open([PHP_BINARY, '-r', $code], [['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']], $pipes, dirname(__DIR__)); + if (!is_resource($process)) { + throw new RuntimeException('Could not run the stdin fixture'); + } + fwrite($pipes[0], "0\r\nsecond\n private\t"); + fclose($pipes[0]); + $stdout = stream_get_contents($pipes[1]); + $stderr = stream_get_contents($pipes[2]); + fclose($pipes[1]); + fclose($pipes[2]); + $case->expect(proc_close($process) === 0)->isTrue()->validate($stderr); + $case->expect($stdout)->isEqualTo("First: Masked (masked input): \n")->validate(); + $case->expect($stderr === '')->isTrue()->validate(); +}); From 5f7086b0d7f3f7f5f78a67cddbd73d208d6fdb54 Mon Sep 17 00:00:00 2001 From: Daniel Ronkainen Date: Mon, 30 Nov 2026 17:52:52 +0100 Subject: [PATCH 03/15] fix: restore terminal state in selection prompts --- src/Command.php | 154 +++++++++++++++----- src/Navigation.php | 256 +++++++++++++++++++++++++++++---- tests/unitary-navigation.php | 270 +++++++++++++++++++++++++++++++++++ 3 files changed, 618 insertions(+), 62 deletions(-) create mode 100644 tests/unitary-navigation.php diff --git a/src/Command.php b/src/Command.php index 95c3582..4d05817 100755 --- a/src/Command.php +++ b/src/Command.php @@ -20,6 +20,8 @@ class Command { private StreamInterface $stream; private ?StreamInterface $input; + /** @var object{byte: string} Shared by copies that use the same input. */ + private object $inputLookahead; private SttyWrapper $stty; private Ansi $ansi; @@ -30,6 +32,7 @@ public function __construct( $stream = ($stream instanceof ResponseInterface) ? $stream->getBody() : $stream; $this->stream = $stream ?? new Stream(Stream::STDOUT); $this->input = $input; + $this->inputLookahead = (object)['byte' => '']; $this->stty = new SttyWrapper(); $this->ansi = new Ansi(); @@ -66,6 +69,44 @@ public function getInput(): StreamInterface return $this->input ??= (defined('STDIN') ? new Stream(STDIN) : new Stream(Stream::STDIN, 'rb')); } + /** @internal Read one byte from the input shared by line and key readers. */ + public function readInputByte(): string + { + $byte = $this->inputLookahead->byte; + if ($byte !== '') { + $this->inputLookahead->byte = ''; + return $byte; + } + return $this->getInput()->read(1); + } + + /** @internal Whether native input has a byte ready within the given microseconds. */ + public function inputIsReady(int $microseconds): bool + { + $input = $this->getInput(); + $unread = $input->getMetadata('unread_bytes'); + if ($this->inputLookahead->byte !== '' || (is_int($unread) && $unread > 0)) { + return true; + } + if (!function_exists('stream_select') || !$input instanceof Stream || !is_resource($resource = $input->getResource())) { + return false; + } + $read = [$resource]; + $write = $except = null; + return stream_select($read, $write, $except, 0, $microseconds) === 1; + } + + /** @internal Consume the LF in a terminal CRLF while retaining unrelated input. */ + public function finishInputEnter(): void + { + if ($this->inputIsReady(0)) { + $byte = $this->readInputByte(); + if ($byte !== "\n") { + $this->inputLookahead->byte = $byte; + } + } + } + /** * Whether the input uses the process's terminal on standard input. */ @@ -77,6 +118,27 @@ public function hasTerminalInput(): bool $this->standardInputIsTerminal(); } + /** + * Whether this command can write cursor controls to its output terminal. + */ + public function hasCursorOutput(): bool + { + $output = $this->getStream(); + if (!$this->getAnsi()->isSupported() || !$output instanceof Stream) { + return false; + } + $resource = $output->getResource(); + return is_resource($resource) && stream_isatty($resource); + } + + /** + * Whether cursor-based navigation can use this command's input and output. + */ + public function supportsNavigation(): bool + { + return $this->hasCursorOutput() && $this->hasTerminalInput() && $this->getStty()->hasSttySupport(); + } + /** * Get SttyWrapper * @@ -106,8 +168,8 @@ public function getAnsi(): Ansi */ public function readline(string $message): string { - if (function_exists('readline') && defined('STDIN') && is_resource(STDIN) && - !stream_get_meta_data(STDIN)['unread_bytes'] && $this->hasTerminalInput() && + if (function_exists('readline') && $this->hasCursorOutput() && defined('STDIN') && is_resource(STDIN) && + $this->inputLookahead->byte === '' && !stream_get_meta_data(STDIN)['unread_bytes'] && $this->hasTerminalInput() && defined('STDOUT') && stream_isatty(STDOUT) && $this->stream instanceof Stream && ($this->stream->getResource() === STDOUT || $this->stream->getStream() === Stream::STDOUT) && @@ -255,17 +317,28 @@ public function list(string $message): array */ public function select(string $message, array $items): int|string { - if ($this->stty->hasSttySupport()) { - $command = new Navigation($this); - $command->setHelperText($command::HELPER_TEXT); - $command->navigation($message, $items, function (int $index, array $items) { - $this->showMenu($index, $items); - }); - return $command->getValue(); + if ($this->supportsNavigation()) { + return $this->selectMenu($message, $items); } return $this->inputSelect($message, $items); } + /** + * Select zero or more items. The original keys are returned in declaration order. + * + * On a terminal, use Up/Down to move, Space to toggle and Enter to accept. + * Other streams accept comma-separated positions starting at 1. An empty + * line keeps the defaults and `none` clears them. + * + * @param array $items + * @param array $defaults Original keys selected initially. + * @return list + */ + public function multiSelect(string $message, array $items, array $defaults = []): array + { + return (new Navigation($this))->navigateMultiple($message, $items, $defaults); + } + /** * Display a non-interactive prompt with multiple options * @@ -288,9 +361,10 @@ public function inputSelect(string $message, array $choices): int|string $this->message($this->getAnsi()->style(["blue", "bold"], "$int:") . " $value"); $int++; } - $line = (int)$this->message("Input your answer", true); - if ($line > 0 && $line <= $length) { - return $keys[$line - 1]; + $line = trim((string)$this->message("Input your answer", true)); + $position = (int)$line; + if (preg_match('/\A[0-9]+\z/', $line) && $position > 0 && $position <= $length) { + return $keys[$position - 1]; } } } @@ -304,14 +378,8 @@ public function inputSelect(string $message, array $choices): int|string */ public function toggle(string $message): int|string { - if ($this->stty->hasSttySupport()) { - $items = [1 => "Yes", 0 => "No"]; - $command = new Navigation($this); - $command->setHelperText(Navigation::HELPER_TEXT); - $command->navigation($message, $items, function (int $index, array $items) { - $this->showMenu($index, $items); - }); - return $command->getValue(); + if ($this->supportsNavigation()) { + return $this->selectMenu($message, [1 => "Yes", 0 => "No"]); } return $this->inputToggle($message); } @@ -379,31 +447,47 @@ public function confirm(string $message): bool /** * Create a progress bar * + * With positive dimensions, each frame renders one cell up to $maxLength. + * The callback receives the zero-based frame scaled by the ratio of the + * smaller dimension to the larger, and ($maxLength - 0.5) at the same scale. + * A zero dimension produces an empty line. + * * @param int $expectedRows The maximum expected rows * @param int $maxLength The maximum bar length - * @param int|callable|null $sleep int for sleep in milliseconds (3000 ms = 1 second) or callback with returned int for sleep in milliseconds + * @param int|callable|null $sleep Sleep in milliseconds, or a per-cell callback returning the delay. * @return void */ public function progress(int $expectedRows, int $maxLength = 100, null|int|callable $sleep = null): void { - $i = 0; - $char = "-"; - $ratio = ($maxLength > $expectedRows) ? $expectedRows / $maxLength : $maxLength / $expectedRows; - $length = ($maxLength - 0.5) * $ratio; - $inc = round($ratio, 4); - while ($i < $length) { - if (is_callable($sleep)) { - $sleep = $sleep($i, $length); - } - if (is_int($sleep) && $sleep >= 0) { - usleep($sleep * 1000); + if ($expectedRows < 0 || $maxLength < 0) { + throw new InvalidArgumentException('Progress dimensions cannot be negative.'); + } + if ($expectedRows > 0 && $maxLength > 0) { + // The animation uses the full bar width. Keep the callback's original scale. + $ratio = (float)(min($expectedRows, $maxLength) / max($expectedRows, $maxLength)); + $length = ((float)$maxLength - 0.5) * $ratio; + for ($frame = 0; $frame < $maxLength; $frame++) { + $i = $frame === 0 ? 0 : (float)$frame * $ratio; + $delay = is_callable($sleep) ? $sleep($i, $length) : $sleep; + if (is_int($delay) && $delay > 0) { + usleep($delay * 1000); + } + $this->stream->write($this->progAppear('-', $i, $length)); } - $this->stream->write($this->progAppear($char, $i, $length)); - $i += $inc; } $this->stream->write("\n"); } + private function selectMenu(string $message, array $items): int|string + { + $navigation = new Navigation($this); + $navigation->setHelperText(Navigation::HELPER_TEXT); + $navigation->navigate($message, $items, function (int $index, array $items): void { + $this->showMenu($index, $items); + }); + return $navigation->getValue(); + } + private function standardInputIsTerminal(): bool { if (!defined('STDIN') || !is_resource(STDIN)) { @@ -452,7 +536,7 @@ private function readInputLine(bool $maskedTerminal = false): string $line = ''; while (true) { // A PSR stream can be non-seekable. Stop at the line break without consuming the next answer. - $byte = $input->read(1); + $byte = $this->readInputByte(); if ($byte === '') { if (!$input->eof()) { throw new PromptException('The input stream did not return any data.'); diff --git a/src/Navigation.php b/src/Navigation.php index 5467029..63dfcdd 100755 --- a/src/Navigation.php +++ b/src/Navigation.php @@ -3,6 +3,10 @@ namespace MaplePHP\Prompts; use Exception; +use InvalidArgumentException; +use MaplePHP\Prompts\Exceptions\InputExhaustedException; +use MaplePHP\Prompts\Exceptions\InputInterruptedException; +use MaplePHP\Prompts\Exceptions\PromptException; /** * Class Navigation @@ -12,9 +16,14 @@ class Navigation { public const HELPER_TEXT = "Use arrow keys to navigate and press (%s) to select item."; + private const ARROW_UP = ["\033[A", "\033OA"]; + private const ARROW_DOWN = ["\033[B", "\033OB"]; + private Command $command; private int $index = 0; + /** @var list */ private array $items = []; + /** @var list */ private array $values = []; private string $acceptKey = ""; private ?string $helperText = null; @@ -55,31 +64,88 @@ public function setHelperText(string $text): void } /** - * Navigate questions + * Select an item with a caller-provided renderer. + * + * The renderer receives the zero-based index and a list of labels on the + * initial render and whenever the selection moves. Render one row per + * label so the cursor can return to the start of the menu. With numbered + * input, the renderer runs before the menu and again if the choice changes. + * + * @psalm-suppress DeprecatedMethod Existing navigation() overrides handle this call. + */ + public function navigate(string $message, array $items, callable $call): void + { + // Keep dispatching to existing subclasses that override navigation(). + $this->navigation($message, $items, $call); + } + + /** + * Navigate questions. * * @param string $message * @param array $items * @param callable $call * @return void * @throws Exception + * @deprecated Use navigate() to select an item. */ public function navigation(string $message, array $items, callable $call): void { - $this->values = array_keys($items); - $this->items = array_values($items); - $start = $this->command->getStty()->toggleEnable(false, "echo")->toggleEnable(true, "cbreak"); - system((string)$start); - - $this->command->getStream()->write($this->command->getAnsi()->bold($message) . "\n"); - $call($this->index, $this->items); - $this->streamHelperText(); - $this->input(function () use ($call) { + $this->setItems($items); + if (!$this->command->supportsNavigation()) { $call($this->index, $this->items); - $this->streamHelperText(); + $key = $this->command->inputSelect($message, $items); + $index = array_search($key, $this->values, true); + if ($index === false) { + throw new PromptException('The input selection did not return an available choice.'); + } + if ($index !== $this->index) { + $this->index = $index; + $call($this->index, $this->items); + } + return; + } + + $this->withNavigationMode(function () use ($message, $call): void { + $render = function () use ($call): void { + $call($this->index, $this->items); + $this->streamHelperText(); + }; + $this->command->title($message); + $render(); + $this->input($render); }); + } - $end = $this->command->getStty()->toggleEnable(true, "echo")->toggleEnable(false, "cbreak"); - system((string)$end); + /** + * @internal Use Command::multiSelect() to select several items. + * @param array $defaults + * @return list + */ + public function navigateMultiple(string $message, array $items, array $defaults): array + { + $this->setItems($items); + $positions = array_flip($this->values); + $selected = []; + foreach ($defaults as $default) { + if ((!is_int($default) && !is_string($default)) || !isset($positions[$default]) || + $this->values[$positions[$default]] !== $default) { + throw new InvalidArgumentException('Each default must be an available choice key.'); + } + $selected[$positions[$default]] = true; + } + + if ($this->command->supportsNavigation()) { + $selected = $this->selectMultipleInTerminal($message, $selected); + } else { + $selected = $this->selectMultipleByNumber($message, $selected); + } + + return array_values(array_filter( + $this->values, + static fn (int $index): bool => isset($selected[$index]), + ARRAY_FILTER_USE_KEY + )); } /** @@ -89,10 +155,7 @@ public function navigation(string $message, array $items, callable $call): void */ public function getValue(): int|string { - if (isset($this->values[$this->index]) && (is_string($this->values[$this->index]) || is_int($this->values[$this->index]))) { - return $this->values[$this->index]; - } - return 0; + return $this->values[$this->index] ?? 0; } /** @@ -114,24 +177,154 @@ public function getItem(): string */ public function input(callable $call): void { + $this->readKeys($call); + } + + private function setItems(array $items): void + { + if ($items === []) { + throw new InvalidArgumentException('You cannot input an empty array!', 1); + } + $this->index = 0; + $this->items = array_values($items); + $this->values = array_keys($items); + } + + private function withNavigationMode(callable $call): void + { + // Read Ctrl+C as a byte so an interrupt follows the same restoration path as EOF. + $this->command->getStty()->withTerminalMode( + $call, '-echo', '-echonl', '-icanon', '-isig', '-iexten', '-ixon', + '-igncr', '-inlcr', '-icrnl', 'min', '1', 'time', '0' + ); + } + + /** + * @param array $selected + * @return array + */ + private function selectMultipleInTerminal(string $message, array $selected): array + { + $this->withNavigationMode(function () use ($message, &$selected): void { + $this->command->title($message); + $this->setHelperText('Use arrow keys to navigate, Space to toggle and (%s) to accept.'); + $render = function (int $index) use (&$selected): void { + foreach ($this->items as $position => $item) { + $marker = isset($selected[$position]) ? 'x' : ' '; + $label = "[$marker] $item"; + $this->command->line($position === $index ? $this->command->getAnsi()->selectedItem($label) : $label); + } + $this->streamHelperText(); + }; + $toggle = static function (int $index) use (&$selected): void { + if (isset($selected[$index])) { + unset($selected[$index]); + } else { + $selected[$index] = true; + } + }; + $render($this->index); + $this->readKeys($render, $toggle); + }); + return $selected; + } + + /** + * @param array $defaults + * @return array + */ + private function selectMultipleByNumber(string $message, array $defaults): array + { + $this->command->line($message); + foreach ($this->items as $index => $item) { + $number = $index + 1; + $marker = isset($defaults[$index]) ? 'x' : ' '; + $this->command->line("$number: [$marker] $item"); + } while (true) { - $input = $this->command->getStream()->read(3); - //$key = $this->getKeyName($input); + $line = trim($this->command->ask("Enter comma-separated numbers, leave blank for defaults, or type 'none'")); + if ($line === '') { + return $defaults; + } + if (strtolower($line) === 'none') { + return []; + } + $selected = []; + foreach (explode(',', $line) as $choice) { + $choice = trim($choice); + $number = (int)$choice; + if (!preg_match('/\A[0-9]+\z/', $choice) || $number < 1 || $number > count($this->items)) { + continue 2; + } + $selected[$number - 1] = true; + } + return $selected; + } + } - if ($input === $this->command->getAnsi()->keyUp()) { + private function readKeys(callable $render, ?callable $toggle = null): void + { + $enterKeys = in_array($this->acceptKey, ["\r", "\n", "\r\n"], true) ? ["\r", "\n"] : [$this->acceptKey]; + $knownKeys = array_merge(self::ARROW_UP, self::ARROW_DOWN, $enterKeys); + while (true) { + $key = $this->readKey($knownKeys); + $previous = $this->index; + if (in_array($key, self::ARROW_UP, true)) { $this->index = max(0, $this->index - 1); - } elseif ($input === $this->command->getAnsi()->keyDown()) { - $this->index = min(count($this->items) - 1, $this->index + 1); - } elseif ($input === $this->acceptKey) { - break; + } elseif (in_array($key, self::ARROW_DOWN, true)) { + $this->index = max(0, min(count($this->items) - 1, $this->index + 1)); + } elseif (in_array($key, $enterKeys, true)) { + if ($key === "\r") { + $this->command->finishInputEnter(); + } + return; + } elseif ($key === ' ' && $toggle !== null) { + $toggle($this->index); + } else { + continue; } + if ($this->index !== $previous || $key === ' ') { + $this->clearLines(count($this->items) + ($this->helperText === null ? 0 : 3)); + $render($this->index); + } + } + } - $lines = count($this->items) + 3; - $this->clearLines($lines); - $call($this->index); + /** @param list $knownKeys */ + private function readKey(array $knownKeys): string + { + $key = $this->readByte(); + // Assemble escape sequences even when the terminal delivers one byte at a time. + while (true) { + $key = $key[0] === "\033" ? $key : strtolower($key); + foreach ($knownKeys as $known) { + if ($known !== $key && str_starts_with($known, $key)) { + // A standalone Escape can also be the first byte of an arrow. + if (in_array($key, $knownKeys, true) && !$this->command->inputIsReady(50000)) { + return $key; + } + $byte = $this->readByte(); + $key = in_array($byte, ["\033", "\r", "\n"], true) ? $byte : $key . $byte; + continue 2; + } + } + return $key; } } + private function readByte(): string + { + $input = $this->command->getInput(); + $byte = $this->command->readInputByte(); + return match ($byte) { + "\x03" => throw new InputInterruptedException(), + "\x04" => throw new InputExhaustedException(), + '' => throw ($input->eof() ? new InputExhaustedException() : + new PromptException('The input stream did not return any data.')), + default => $byte + }; + } + /** * Get the expected navigation key * @@ -140,6 +333,12 @@ public function input(callable $call): void */ protected function getKeyName(string $key): string { + if ($key === "\033") { + return 'escape'; + } + if ($key === "\r" || $key === "\r\n") { + return 'enter'; + } $check = $this->escBreaker($key); /** @var array $nav */ $nav = $this->command->getAnsi()::NAV; @@ -180,6 +379,9 @@ protected function escBreaker(string $string): string */ public function clearLines(int $lines): void { + if ($lines <= 0 || !$this->command->hasCursorOutput()) { + return; + } // Move the cursor up to the start $this->command->getStream()->write($this->command->getAnsi()->moveCursorTo($lines)); for ($i = 0; $i < $lines; $i++) { diff --git a/tests/unitary-navigation.php b/tests/unitary-navigation.php new file mode 100644 index 0000000..b9d0d15 --- /dev/null +++ b/tests/unitary-navigation.php @@ -0,0 +1,270 @@ +write($answers); + $input->rewind(); + return new Command(stream: new Stream('php://memory'), input: $input); +} + +group('Single selection validates numbered input and direct navigation preserves keys and callbacks', static function (TestCase $case) { + $command = promptsNavigationCommands("1.9\n2xyz\n 2 \nno\n2\n1\n"); + $items = [40 => 'First', 'second' => 'Second']; + $navigation = new Navigation($command); + $renders = []; + $render = static function (int $index, array $labels) use (&$renders, $navigation): void { + $navigation->clearLines(2); + $renders[] = [$index, $labels]; + }; + + $case->expect($command->select('Numbered', $items) === 'second')->isTrue()->validate(); + $case->expect($command->toggle('Toggle') === 0)->isTrue()->validate(); + $navigation->navigate(message: 'Choose', items: $items, call: $render); + $case->expect($navigation->getValue() === 'second' && $navigation->getItem() === 'Second')->isTrue()->validate(); + $navigation->navigation(message: 'Choose again', items: ['start' => 'New'], call: $render); + $case->expect($navigation->getValue() === 'start' && $navigation->getItem() === 'New')->isTrue()->validate(); + $case->expect($renders === [[0, ['First', 'Second']], [1, ['First', 'Second']], [0, ['New']]])->isTrue()->validate(); + $case->expect(!str_contains((string)$command->getStream(), "\033[2K"))->isTrue()->validate(); + $case->expect(fn () => $navigation->navigate('Empty', [], $render))->isThrowable(InvalidArgumentException::class)->validate(); + $case->expect(fn () => $navigation->navigate('EOF', $items, $render))->isThrowable(InputExhaustedException::class)->validate(); + + $legacy = new class ($command) extends Navigation { + public function navigation(string $message, array $items, callable $call): void + { + $call($message, $items); + } + }; + $received = []; + $legacy->navigate(message: 'Legacy', items: $items, call: static function (...$args) use (&$received): void { + $received = $args; + }); + $case->expect($received === ['Legacy', $items])->isTrue()->validate(); +}); + +group('Numbered multi-select retries entire invalid lines and returns unique original keys in order', static function (TestCase $case) { + $command = promptsNavigationCommands("3, 0\n2,\n1x,3\n 3, 1, 3 \n\nnone\n2\n"); + $items = [40 => 'First', 'second' => 'Second', 2 => 'Third']; + $case->expect($command->multiSelect(message: 'Choose', items: $items, defaults: ['second']) === [40, 2]) + ->isTrue()->validate(); + $case->expect($command->multiSelect('Defaults', $items, [2, 40, 2]) === [40, 2])->isTrue()->validate(); + $case->expect($command->multiSelect('Clear defaults', $items, ['second']) === [])->isTrue()->validate(); + $case->expect($command->multiSelect('Replace defaults', $items, [40]) === ['second'])->isTrue()->validate(); + $case->expect(fn () => $command->multiSelect('Exhausted', $items))->isThrowable(InputExhaustedException::class)->validate(); + $case->expect(fn () => $command->multiSelect('Empty', []))->isThrowable(InvalidArgumentException::class)->validate(); + foreach ([['missing'], ['40'], [null]] as $invalid) { + $case->expect(fn () => $command->multiSelect('Invalid default', $items, $invalid)) + ->isThrowable(InvalidArgumentException::class)->validate(); + } +}); + +group('Progress uses the bar width for frame count and retains the callback scale', static function (TestCase $case) { + foreach ([[1, 100], [5, 5], [PHP_INT_MAX, 3]] as [$rows, $width]) { + $command = promptsNavigationCommands(''); + $command->getAnsi()->disableAnsi(true); + $frames = []; + $command->progress(expectedRows: $rows, maxLength: $width, sleep: static function ($i, $length) use (&$frames): int { + $frames[] = [$i, $length]; + return 0; + }); + $ratio = (float)(min($rows, $width) / max($rows, $width)); + $total = ($width - 0.5) * $ratio; + $case->expect((string)$command->getStream())->isEqualTo(str_repeat('-', $width) . "\n")->validate(); + $case->expect(count($frames) === $width && $frames[0] === [0, $total] && + $frames[$width - 1] === [($width - 1) * $ratio, $total])->isTrue()->validate(); + } + $command = promptsNavigationCommands(''); + $unexpected = static function (): never { + throw new LogicException('An empty progress bar cannot render a frame'); + }; + $command->progress(0, 100, $unexpected); + $command->progress(1, 0, $unexpected); + $command->progress(0, 0, $unexpected); + $case->expect((string)$command->getStream())->isEqualTo("\n\n\n")->validate(); + $case->expect(fn () => $command->progress(-1, 5))->isThrowable(InvalidArgumentException::class)->validate(); + $case->expect(fn () => $command->progress(1, -5))->isThrowable(InvalidArgumentException::class)->validate(); +}); + +group('Redirected standard input exhausts without entering terminal navigation', static function (TestCase $case) { + $code = <<<'PHP' + require 'vendor/autoload.php'; + $command = new \MaplePHP\Prompts\Command(); + $command->getAnsi()->disableAnsi(true); + $items = [20 => 'First', 'second' => 'Second']; + if ($command->select('Single', $items) !== 'second') { + exit(1); + } + try { + $command->multiSelect('Multiple', $items); + } catch (\MaplePHP\Prompts\Exceptions\InputExhaustedException) { + exit(0); + } + exit(2); + PHP; + $process = proc_open([PHP_BINARY, '-r', $code], [['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']], $pipes, dirname(__DIR__)); + if (!is_resource($process)) { + throw new RuntimeException('Could not run the redirected selection fixture'); + } + fwrite($pipes[0], "2\n"); + fclose($pipes[0]); + $stdout = stream_get_contents($pipes[1]); + $stderr = stream_get_contents($pipes[2]); + fclose($pipes[1]); + fclose($pipes[2]); + $case->expect(proc_close($process) === 0 && $stderr === '')->isTrue()->validate($stderr); + $case->expect(str_contains($stdout, "Single (1-2)\n1: First\n2: Second\n") && + str_contains($stdout, "Multiple\n1: [ ] First\n2: [ ] Second\n") && !str_contains($stdout, "\033")) + ->isTrue()->validate($stdout); +}); + +$pty = TestConfig::make('A Unix pseudo-terminal restores exact state after selection, Ctrl+C, Ctrl+D and callback errors') + ->withSkip(!in_array(PHP_OS_FAMILY, ['Darwin', 'Linux'], true) || !function_exists('exec')); +group($pty, static function (TestCase $case) { + $code = <<<'PHP' + require 'vendor/autoload.php'; + putenv('TERM=xterm-256color'); + exec('stty -echo icanon isig'); + $terminalState = static function (): string { + $state = exec('stty -g'); + if (PHP_OS_FAMILY !== 'Darwin') { + return $state; + } + // Darwin sets PENDIN on canonical-mode transitions until the next kernel read. + return preg_replace_callback('/lflag=([0-9a-f]+)/', static function (array $match): string { + return 'lflag=' . dechex(hexdec($match[1]) & ~0x20000000); + }, $state); + }; + $before = $terminalState(); + $verify = static function (bool $result) use ($before, $terminalState): void { + if (!$result) { + throw new RuntimeException('Unexpected selection'); + } + $after = $terminalState(); + if ($after !== $before) { + throw new RuntimeException("Unrestored terminal mode\nBefore: $before\nAfter: $after"); + } + }; + $command = new \MaplePHP\Prompts\Command(); + $items = [29 => 'First', 'middle' => 'Middle', 7 => 'Last']; + $nav = new \MaplePHP\Prompts\Navigation($command); + $render = static function (int $index, array $labels) use ($command, $before, $terminalState): void { + if ($terminalState() === $before) { + throw new RuntimeException('Navigation did not configure the terminal'); + } + foreach ($labels as $position => $label) { + $command->line($index === $position ? "[x] $label" : "[ ] $label"); + } + }; + + $nav->navigate('First session', $items, $render); + $verify($nav->getValue() === 'middle'); + $nav->navigate('Second session', $items, $render); + $verify($nav->getValue() === 7); + $nav->setAcceptKey("\033"); + $nav->navigation('Escape session', $items, $render); + $verify($nav->getValue() === 'middle'); + $nav->setAcceptKey('x'); + $nav->navigate('Custom session', $items, $render); + $verify($nav->getValue() === 29); + + $verify($command->multiSelect('Multiple session', $items, ['middle']) === [29, 7]); + $verify($command->toggle('Toggle session') === 0); + + try { + $command->select('Interrupt session', $items); + throw new RuntimeException('Ctrl+C did not interrupt selection'); + } catch (\MaplePHP\Prompts\Exceptions\InputInterruptedException) { + $verify(true); + } + try { + $command->select('EOF session', $items); + throw new RuntimeException('Ctrl+D did not exhaust selection'); + } catch (\MaplePHP\Prompts\Exceptions\InputExhaustedException) { + $verify(true); + } + $failure = new LogicException('Renderer failed'); + try { + $nav->navigate('Throwing session', $items, static function () use ($failure): never { + throw $failure; + }); + throw new RuntimeException('Renderer did not run'); + } catch (LogicException $exception) { + $verify($exception === $failure); + } + + $memory = new \MaplePHP\Http\Stream('php://memory'); + $copy = $command->withStream($memory); + $command->line('Redirected output session'); + $verify($copy->select('Numbered fallback', $items) === 'middle'); + $verify(str_contains((string)$memory, '(1-3)') && !str_contains((string)$memory, "\033[2K")); + + $injected = new \MaplePHP\Http\Stream('php://memory'); + $injected->write("3\n"); + $injected->rewind(); + $verify((new \MaplePHP\Prompts\Command(input: $injected))->select('Injected input', $items) === 7); + + $commandWithoutCursor = new \MaplePHP\Prompts\Command(); + $commandWithoutCursor->getAnsi()->disableAnsi(true); + $verify($commandWithoutCursor->toggle('Plain session') === 0); + echo "Completed\n"; + PHP; + $process = proc_open([PHP_BINARY, '-r', $code], [['pty'], ['redirect', 0], ['pipe', 'w']], $pipes, dirname(__DIR__)); + if (!is_resource($process)) { + throw new RuntimeException('Could not open the Unix pseudo-terminal'); + } + + $answers = [ + ['First session', ["\033", '[', 'B', "\r\n"]], + ['Second session', ["\033[B\033OB\n"]], + ['Escape session', ["\033", '[', 'B', "\033"]], + ['Custom session', ["\r", 'x']], + ['Multiple session', ["\033[A \033[B \033[B\033[B \r"]], + ['Toggle session', ["\033[B\n"]], + ['Interrupt session', ["\033[", "\x03"]], + ['EOF session', ["\x04"]], + ['Redirected output session', ["2\n"]], + ['Plain session', ["no\n"]], + ]; + $terminal = $pipes[0]; + stream_set_blocking($terminal, false); + $output = ''; + $deadline = microtime(true) + 8; + try { + do { + $output .= (string)@stream_get_contents($terminal); + if ($answers !== [] && str_contains($output, $answers[0][0])) { + [, $chunks] = array_shift($answers); + foreach ($chunks as $chunk) { + fwrite($terminal, $chunk); + usleep(12000); + } + } + $status = proc_get_status($process); + if (!$status['running']) { + $output .= (string)@stream_get_contents($terminal); + break; + } + usleep(5000); + } while (microtime(true) < $deadline); + } finally { + if ($status['running'] ?? true) { + proc_terminate($process, 9); + } + fclose($terminal); + $errors = stream_get_contents($pipes[2]); + fclose($pipes[2]); + proc_close($process); + } + $case->expect(($status['exitcode'] ?? -1) === 0 && $errors === '')->isTrue()->validate($output . $errors); + $case->expect($answers === [] && str_contains($output, 'Completed') && str_contains($output, "\033[2K")) + ->isTrue()->validate($output); +}); From 268eecd4f5c0e7a90edf10667b475d9b3247f471 Mon Sep 17 00:00:00 2001 From: Daniel Ronkainen Date: Mon, 30 Nov 2026 18:09:00 +0100 Subject: [PATCH 04/15] feat: run replayable prompt definitions --- src/Prompt.php | 271 +++++++++++++++++++++------------ src/PromptDefinition.php | 275 ++++++++++++++++++++++++++++++++++ tests/unitary-definitions.php | 207 +++++++++++++++++++++++++ 3 files changed, 661 insertions(+), 92 deletions(-) create mode 100644 src/PromptDefinition.php create mode 100644 tests/unitary-definitions.php diff --git a/src/Prompt.php b/src/Prompt.php index b9ebb47..eccb7c1 100755 --- a/src/Prompt.php +++ b/src/Prompt.php @@ -3,7 +3,6 @@ namespace MaplePHP\Prompts; use ErrorException; -use Exception; use InvalidArgumentException; use MaplePHP\Prompts\Exceptions\InputExhaustedException; use MaplePHP\Prompts\Exceptions\InputInterruptedException; @@ -12,6 +11,11 @@ class Prompt { + private const TYPES = [ + 'message', 'text', 'invisible', 'mask', 'password', 'list', 'select', 'multiselect', 'toggle', 'confirm', + 'continue', + ]; + private Command $command; private array $data = []; private ?string $title = null; @@ -103,20 +107,37 @@ public function add(string $name, array $data): self * @return mixed * @throws ErrorException * @throws PromptException - * @throws \MaplePHP\Prompts\PromptException - * @throws Exception */ public function promptLine(array $row): mixed { - $input = false; - $default = $row['default'] ?? ""; + return $this->askRow($row); + } + + private function askRow(array $row, bool $stored = false): mixed + { + $default = $stored && array_key_exists('default', $row) ? $row['default'] : ($row['default'] ?? ''); $validate = $row['validate'] ?? []; + $validator = null; $message = (string)($row['message'] ?? ""); $error = $row['error'] ?? false; $items = $row['items'] ?? []; - $rowType = $row['type'] ?? "text"; + $rowType = self::checkType($row['type'] ?? 'text'); $confirm = $row['confirm'] ?? false; + if (!$stored && array_key_exists('validator', $row)) { + if (array_key_exists('validate', $row)) { + throw new InvalidArgumentException('Use either validate or validator for a prompt row.'); + } + $callback = $row['validator']; + if (!is_callable($callback)) { + throw new InvalidArgumentException('The validator must be callable.'); + } + $validator = $callback; + } + if (!is_array($validate) && ($stored || !is_callable($validate))) { + throw new InvalidArgumentException('The validate item must be a rule map or callable.'); + } + if (is_string($default) && $default !== "" && !in_array($rowType, ["invisible", "mask", "password"], true)) { $message .= " ($default)"; } @@ -125,55 +146,44 @@ public function promptLine(array $row): mixed throw new InvalidArgumentException("The message cannot be empty!", 1); } - switch ($rowType) { - case "message": - $input = $this->command->message($message); - break; - case "text": - $input = $this->command->message($message, true); - break; - case "invisible": - case "mask": - case "password": - $input = $this->command->mask($message); - break; - case "list": - $input = $this->command->list($message); - break; - case "select": - if (!is_array($items)) { - throw new InvalidArgumentException("The items must be an array!", 1); - } - $input = $this->command->select($message, $items); - break; - case "toggle": - $input = $this->command->toggle($message); - break; - case "confirm": - $input = (int) $this->command->confirm($message); - if (!$input) { - $this->command->message($this->command->getAnsi()->style(["red", "bold"], "Aborted...")); - return false; - } - break; - case "continue": - if (is_callable($items)) { - $items = $items($this->prevVal, $this->index); - if ($items === false) { - return true; - } - } - if (!is_array($items)) { - throw new InvalidArgumentException("The items must return a a valid array"); - } - $inst = new self($this->command); - $inst->disableHeaderInfo(true); - $inst->data = $items; - $input = $inst->run(); - if ($input === false) { - return false; + // A required multiselect needs at least one choice, even if its only key is zero. + $required = []; + if ($rowType === 'multiselect' && is_array($validate)) { + $required = array_intersect_key($validate, ['required' => true, 'isRequired' => true]); + $validate = array_diff_key($validate, $required); + } + + while (true) { + $choices = $items; + if (!$stored && $rowType === 'continue' && is_callable($items)) { + $choices = $items($this->prevVal, $this->index); + if ($choices === false) { + return true; } + } + + $input = $this->readRow($rowType, $message, $choices, $row['default'] ?? [], $stored); + if ($input === false && ($rowType === 'continue' || $rowType === 'confirm')) { + return false; + } + if ($this->isEmpty($input)) { + $input = $default; + } + + $errorType = $input === [] ? array_key_first($required) : null; + $valid = match (true) { + $errorType !== null => false, + $stored && is_array($validate) => PromptDefinition::validateInput($validate, $input, $errorType), + $validator !== null => $this->validateWithCallback($validator, $input, false, 'validator'), + default => $this->validateItems($validate, $input, $errorType), + }; + if ($valid) { break; + } + $this->reportError($error, $errorType, $input, $row, $stored); + if ($rowType === 'message') { + throw new InvalidArgumentException('A message prompt has no input to retry.'); + } } if (is_string($confirm)) { @@ -181,28 +191,56 @@ public function promptLine(array $row): mixed $this->command->message("..."); } - if ($this->isEmpty($input)) { - $input = $default; - } + $this->prevVal = $input; + return $input; + } - if (!(is_array($validate) || is_callable($validate))) { - throw new InvalidArgumentException("The validate item is wrong input data type", 1); + private function readRow(string $type, string $message, mixed $items, mixed $defaults, bool $stored): mixed + { + if (in_array($type, ['select', 'multiselect', 'continue'], true) && !is_array($items)) { + throw new InvalidArgumentException("The items for a $type prompt must be an array."); } + if ($type === 'multiselect' && !is_array($defaults)) { + throw new InvalidArgumentException('The default for a multiselect prompt must be an array of choice keys.'); + } + return match ($type) { + 'message' => $this->command->message($message), + 'text' => $this->command->message($message, true), + 'invisible', 'mask', 'password' => $this->command->mask($message), + 'list' => $this->command->list($message), + 'select' => $this->command->select($message, $items), + 'multiselect' => $this->command->multiSelect($message, $items, $defaults), + 'toggle' => $this->command->toggle($message), + 'continue' => $this->runNested($items, $stored), + 'confirm' => $this->command->confirm($message) ? 1 : $this->abort(), + }; + } - if (!$this->validateItems($validate, $input, $errorType)) { - if (is_string($error) && $error !== "") { - $this->command->message($this->command->getAnsi()->red($error)); - } elseif (is_callable($error)) { - $errorMsg = $error($errorType, $input, $row); - if (!is_string($errorMsg)) { - throw new InvalidArgumentException("The error callable has to return a string!", 1); - } - $this->command->message($this->command->getAnsi()->red($errorMsg)); + private function runNested(array $items, bool $stored): array|false + { + $nested = new self($this->command); + $nested->disableHeaderInfo(true); + $nested->data = $items; + return $nested->run($stored); + } + + private function abort(): false + { + $this->command->message($this->command->getAnsi()->style(['red', 'bold'], 'Aborted...')); + return false; + } + + private function reportError(mixed $error, ?string $type, mixed $input, array $row, bool $stored): void + { + if (is_string($error) && $error !== '') { + $this->command->message($this->command->getAnsi()->red($error)); + } elseif (!$stored && is_callable($error)) { + $message = $error($type, $input, $row); + if (!is_string($message)) { + throw new InvalidArgumentException('The error callable has to return a string!', 1); } - return $this->promptLine($row); + $this->command->message($this->command->getAnsi()->red($message)); } - $this->prevVal = $input; - return $input; } /** @@ -213,15 +251,38 @@ public function promptLine(array $row): mixed * @throws PromptException */ public function prompt(): array|false + { + return $this->runUntilAbort(); + } + + /** + * Run a data-only definition with a fresh queue and prompt context. + * + * @throws InvalidArgumentException If any row or rule is invalid. + */ + public function runDefinition(array $steps): array|false + { + $steps = PromptDefinition::check($steps, self::TYPES); + + $runner = new self($this->command); + $runner->data = $steps; + $runner->title = $this->title; + $runner->description = $this->description; + $runner->helperText = $this->helperText; + $runner->disableHeaderInfo = $this->disableHeaderInfo; + return $runner->runUntilAbort(stored: true); + } + + private function runUntilAbort(bool $stored = false): array|false { try { - return $this->run(); + return $this->run($stored); } catch (InputExhaustedException | InputInterruptedException) { return false; } } - private function run(): array|false + private function run(bool $stored): array|false { $result = []; $this->index = 0; @@ -232,11 +293,12 @@ private function run(): array|false if (!is_array($row)) { throw new PromptException("The data array has to return an array!", 1); } - $input = $this->promptLine($row); - if ($input === false) { + $type = $row['type'] ?? 'text'; + $input = $stored ? $this->askRow($row, stored: true) : $this->promptLine($row); + if ($input === false && (!$stored || $type === 'confirm' || $type === 'continue')) { return false; } - if (($row['type'] ?? "text") !== "message") { + if ($type !== 'message') { $result[$name] = $input; } unset($this->data[$name]); @@ -245,6 +307,15 @@ private function run(): array|false return $result; } + private static function checkType(mixed $type): string + { + if (!is_string($type) || !in_array($type, self::TYPES, true)) { + $name = is_string($type) ? "\"$type\"" : get_debug_type($type); + throw new InvalidArgumentException("Unknown prompt type $name."); + } + return $type; + } + /** * Prompt header information * @@ -291,29 +362,36 @@ protected function isEmpty(mixed $input): bool */ protected function validateItems(array|callable $validate, mixed $input, ?string &$error = ""): bool { + $error = null; + if (is_callable($validate)) { + return $this->validateWithCallback($validate, $input, true, 'validate'); + } + $input = (!is_array($input)) ? [$input] : $input; foreach ($input as $value) { - if (is_callable($validate)) { - $isValid = $validate($value); - if (!is_bool($isValid)) { - throw new InvalidArgumentException("The callable validate function must return a boolean!", 1); - } - if ($isValid) { - $error = null; + foreach ($validate as $method => $args) { + $method = (string)$method; + $args = is_array($args) ? $args : []; + if (!$this->validate((string)$value, $method, $args)) { + $error = $method; return false; } - } else { - foreach ($validate as $method => $args) { - $method = (string)$method; - $args = is_array($args) ? $args : []; - if (!$this->validate((string)$value, $method, $args)) { - $error = $method; - return false; - } - } } } - $error = null; + return true; + } + + private function validateWithCallback(callable $validator, mixed $input, bool $retryValue, string $field): bool + { + foreach (is_array($input) ? $input : [$input] as $value) { + $result = $validator($value); + if (!is_bool($result)) { + throw new InvalidArgumentException("The $field callable must return a boolean."); + } + if ($result === $retryValue) { + return false; + } + } return true; } @@ -328,6 +406,15 @@ protected function validateItems(array|callable $validate, mixed $input, ?string final protected function validate(string $value, string $method, array $args = []): bool { $inp = new Validator($value); + // Use the canonical methods where earlier Validate aliases ignore arguments or recurse. + if ($method === 'dateTime' || $method === 'isDateWithTime') { + $args = [$args['format'] ?? $args[0] ?? 'Y-m-d H:i:s']; + } + $method = match ($method) { + 'date', 'dateTime', 'isDateWithTime' => 'isDate', + 'validVersion' => 'isValidVersion', + default => $method, + }; if (!method_exists($inp, $method)) { throw new InvalidArgumentException("The validation method \"$method\" does not exist", 1); } diff --git a/src/PromptDefinition.php b/src/PromptDefinition.php new file mode 100644 index 0000000..97058ee --- /dev/null +++ b/src/PromptDefinition.php @@ -0,0 +1,275 @@ + 'isRequired', + 'email' => 'isEmail', + 'number' => 'isNumber', + 'url' => 'isUrl', + 'phone' => 'isPhone', + 'date' => 'isDate', + 'dateTime' => 'isDateWithTime', + 'bool' => 'isBool', + 'boolVal' => 'isBoolVal', + 'float' => 'isFloat', + 'int' => 'isInt', + 'positive' => 'isPositive', + 'negative' => 'isNegative', + 'validVersion' => 'isValidVersion', + 'zip' => 'isZip', + 'hex' => 'isHexColor', + 'age' => 'isAge', + 'domain' => 'isDomain', + 'equal' => 'isEqualTo', + 'notEqual' => 'isNotEqualTo', + 'string' => 'isString', + 'equalLength' => 'isLengthEqualTo', + 'lossyPassword' => 'isLossyPassword', + 'strictPassword' => 'isStrictPassword', + 'pregMatch' => 'isMatchingPattern', + 'atoZ' => 'isAlpha', + 'lowerAtoZ' => 'isLowerAlpha', + 'upperAtoZ' => 'isUpperAlpha', + ]; + + /** + * Check the full definition and copy its values before issuing any prompts. + * + * @param list $types + */ + public static function check(array $steps, array $types, string $path = 'steps', int $depth = 0): array + { + self::checkDepth($depth, $path); + $checked = []; + foreach ($steps as $name => $row) { + $location = "{$path}[$name]"; + if (!is_array($row)) { + throw new InvalidArgumentException("The prompt row at $location must be an array."); + } + $type = array_key_exists('type', $row) ? $row['type'] : 'text'; + if (!in_array($type, $types, true)) { + $label = is_string($type) ? "\"$type\"" : get_debug_type($type); + throw new InvalidArgumentException("Unknown prompt type $label at $location."); + } + if ($type !== 'continue' && (!isset($row['message']) || $row['message'] === '')) { + throw new InvalidArgumentException("The message at $location cannot be empty."); + } + if ($type === 'message' && ($row['validate'] ?? []) !== []) { + throw new InvalidArgumentException("A message at $location cannot validate input."); + } + + $data = []; + foreach ($row as $key => $value) { + $data[$key] = match ($key) { + 'type' => $type, + 'message', 'error', 'confirm' => is_string($value) ? $value : + throw new InvalidArgumentException("The $key at $location must be a string."), + 'default' => self::checkDefault($type, $row, $value, $location), + 'items' => self::checkItems($type, $types, $value, "$location.items", $depth), + 'validate' => self::checkRules($value, "$location.validate", $depth + 1), + default => throw new InvalidArgumentException("Unknown definition field \"$key\" at $location."), + }; + } + if (in_array($type, ['select', 'multiselect', 'continue'], true) && !array_key_exists('items', $data)) { + throw new InvalidArgumentException("The $type prompt at $location requires items."); + } + $checked[$name] = $data; + } + return $checked; + } + + private static function checkDefault(string $type, array $row, mixed $value, string $path): mixed + { + if ($type !== 'multiselect') { + if (!in_array($type, ['text', 'invisible', 'mask', 'password'], true)) { + throw new InvalidArgumentException("A $type prompt at $path does not use a default."); + } + if (is_scalar($value) || $value === null) { + return $value; + } + throw new InvalidArgumentException("The default at $path must be a scalar or null."); + } + + if (!is_array($value) || !array_is_list($value)) { + throw new InvalidArgumentException("The multiselect default at $path must be a list of choice keys."); + } + $items = $row['items'] ?? null; + $keys = is_array($items) ? array_keys($items) : []; + $defaults = []; + foreach ($value as $key) { + if (!in_array($key, $keys, true)) { + throw new InvalidArgumentException("Each multiselect default at $path must be an available choice key."); + } + $defaults[] = $key; + } + return $defaults; + } + + /** @param list $types */ + private static function checkItems(string $type, array $types, mixed $items, string $path, int $depth): array + { + if (!is_array($items)) { + throw new InvalidArgumentException("The items at $path must be an array."); + } + if ($type === 'continue') { + return self::check($items, $types, $path, $depth + 1); + } + if (!in_array($type, ['select', 'multiselect'], true) || $items === []) { + throw new InvalidArgumentException("The items at $path require a selection prompt and at least one choice."); + } + + $choices = []; + foreach ($items as $key => $label) { + if (!is_string($label)) { + throw new InvalidArgumentException("Each choice label at $path must be a string."); + } + $choices[$key] = $label; + } + return $choices; + } + + /** @return array> */ + private static function checkRules(mixed $rules, string $path, int $depth): array + { + self::checkDepth($depth, $path); + if (!is_array($rules)) { + throw new InvalidArgumentException("The validation at $path must be a rule map."); + } + $checked = []; + foreach ($rules as $name => $args) { + if (!is_string($name)) { + throw new InvalidArgumentException("The validation at $path must be a map of named rules."); + } + $method = self::methodFor($name, $path); + if (!is_array($args) || !array_is_list($args) || !self::acceptsArguments($method, $args)) { + throw new InvalidArgumentException("Invalid arguments for validation rule \"$name\" at $path."); + } + if ($method === 'oneOf' || $method === 'allOf') { + $checked[$name] = [self::checkRules($args[0], "$path.$name", $depth + 1)]; + } else { + // Copy scalar arguments so references in PHP arrays cannot change a checked definition. + $checked[$name] = array_map(static fn (mixed $value): mixed => $value, $args); + } + } + return $checked; + } + + private static function methodFor(string $name, string $path): string + { + $method = self::ALIASES[$name] ?? $name; + if (!in_array($method, self::RULES, true)) { + throw new InvalidArgumentException("Unknown validation rule \"$name\" at $path."); + } + return $method; + } + + /** @param list $args */ + private static function acceptsArguments(string $method, array $args): bool + { + $count = count($args); + $first = $args[0] ?? null; + $second = $args[1] ?? null; + + return match ($method) { + 'oneOf', 'allOf' => $count === 1 && is_array($first), + 'length', 'isZip' => $count <= 2 && is_int($first) && $first >= 0 && + ($second === null || (is_int($second) && $second >= $first)), + 'min', 'max' => $count === 1 && (is_int($first) || (is_float($first) && is_finite($first))), + 'isAge', 'isLengthEqualTo' => $count === 1 && is_int($first) && $first >= 0, + 'isStrictPassword', 'isLossyPassword' => $count === 0 || + ($count === 1 && is_int($first) && $first >= 0 && $first <= 65535), + 'isDate', 'isDateWithTime' => $count === 0 || + ($count === 1 && is_string($first) && $first !== '' && !str_contains($first, "\0")), + 'isValidVersion', 'isDomain' => $count === 0 || ($count === 1 && is_bool($first)), + 'versionCompare' => $count <= 2 && is_string($first) && $first !== '' && + ($count === 1 || in_array($second, Validator::WHITELIST_OPERATORS, true)), + 'isEqualTo', 'isNotEqualTo' => $count === 1 && (is_scalar($first) || $first === null), + 'isMatchingPattern' => $count === 1 && is_string($first) && @preg_match("/^[$first]+$/", '') !== false, + default => $count === 0, + }; + } + + private static function checkDepth(int $depth, string $path): void + { + // Bound recursion for manually assembled arrays, which can contain cycles. + if ($depth >= 512) { + throw new InvalidArgumentException("The prompt definition is nested too deeply at $path."); + } + } + + public static function validateInput(array $rules, mixed $input, ?string &$error): bool + { + /** @var array> $rules Checked rule names and arguments from checkRules(). */ + foreach (is_array($input) ? $input : [$input] as $value) { + foreach ($rules as $name => $args) { + if (!self::matches($value, $name, $args)) { + $error = $name; + return false; + } + } + } + return true; + } + + /** @param list $args */ + private static function matches(mixed $value, string $name, array $args): bool + { + $method = self::methodFor($name, 'validate'); + if ($method === 'oneOf' || $method === 'allOf') { + // Dispatch composite rules here so their subrules use the same allowlist. + $all = $method === 'allOf'; + /** @var array> $subrules Checked recursively by checkRules(). */ + $subrules = $args[0]; + foreach ($subrules as $subrule => $subargs) { + if (self::matches($value, $subrule, $subargs) !== $all) { + return !$all; + } + } + return $all; + } + $validator = new Validator($value); + if ($method === 'isDateWithTime') { + // Earlier Validate releases route this predicate through an alias that ignores the format. + $args = [$args[0] ?? 'Y-m-d H:i:s']; + $method = 'isDate'; + } + if (in_array($method, ['isDate', 'isAge'], true) && + (!is_scalar($value) || str_contains((string)$value, "\0"))) { + return false; + } + if (!is_scalar($value) && in_array($method, [ + 'isMatchingPattern', 'isAlpha', 'isLowerAlpha', 'isUpperAlpha', 'isHexColor', 'isLossyPassword', + 'isStrictPassword', 'isBoolVal', 'isValidVersion', 'versionCompare', 'isDomain', + ], true)) { + return false; + } + if ($method === 'isAge') { + // Validate parses the supplied date with DateTime, which throws on invalid input. + try { + return $validator->$method(...$args) === true; + } catch (Exception) { + return false; + } + } + return $validator->$method(...$args) === true; + } +} diff --git a/tests/unitary-definitions.php b/tests/unitary-definitions.php new file mode 100644 index 0000000..379da54 --- /dev/null +++ b/tests/unitary-definitions.php @@ -0,0 +1,207 @@ +write($answers); + $input->rewind(); + $output = new Stream('php://memory'); + $command = new Command(stream: $output, input: $input); + $command->getAnsi()->disableAnsi(true); + return [new Prompt($command), $input, $output]; +} + +group('Decoded definitions replay with a fresh queue and literal text', static function (TestCase $case) { + $steps = json_decode(<<<'JSON' + { + "notice": {"type":"message","message":"strlen"}, + "zero": {"message":"Zero","validate":{"oneOf":[{"length":[2,4],"allOf":[{"int":[],"isFalsy":[]}]}]},"error":"strlen","confirm":"trim"}, + "choice": {"type":"select","message":"Pick","items":{"-1":"strlen","0":"trim"}}, + "nested": {"type":"continue","items":{ + "more": {"type":"message","message":"Inside"}, + "toggle": {"type":"toggle","message":"Toggle"}, + "approval": {"type":"confirm","message":"Continue?"} + }}, + "password": {"type":"password","message":"Password","default":"secret default"}, + "flag": {"message":"Flag","default":false,"validate":{"isFalse":[]}}, + "null": {"message":"Null","default":null} + } + JSON, true, flags: JSON_THROW_ON_ERROR); + [$prompt, , $output] = promptDefinitionSession(str_repeat("x\n0\n1\nno\nyes\n\n\n\n", 2)); + $prompt->setTitle('Title')->setDescription('Description'); + $expected = ['zero' => '0', 'choice' => -1, 'nested' => ['toggle' => 0, 'approval' => 1], + 'password' => 'secret default', 'flag' => false, 'null' => null]; + + $case->expect($prompt->runDefinition($steps) === $expected)->isTrue()->validate(); + $case->expect($prompt->runDefinition($steps) === $expected)->isTrue()->validate(); + $rendered = (string)$output; + $case->expect(substr_count($rendered, "Title\nDescription\n\n") === 2)->isTrue()->validate(); + $case->expect(str_contains($rendered, "Zero: strlen\nZero: trim\n...\n"))->isTrue()->validate(); + $case->expect(str_contains($rendered, 'secret default'))->isFalse()->validate(); +}); + +group('Stored rows and nested rule maps are checked before input or output', static function (TestCase $case) { + $callback = static fn () => throw new LogicException('Stored callbacks must never run'); + $object = new class () { + public function invoke(): never + { + throw new LogicException('Stored callbacks must never run'); + } + }; + + $invalid = [ + $object, + ['type' => 'unknown', 'message' => 'Unknown'], + ['message' => ''], + ['message' => 'Invalid', 'validator' => $callback], + ['message' => 'Invalid', 'validate' => 'strlen'], + ['message' => 'Invalid', 'validate' => [$object, 'invoke']], + ['message' => 'Invalid', 'confirm' => $callback], + ['message' => 'Invalid', 'error' => [$object, 'invoke']], + ['message' => 'Invalid', 'default' => [get_class($object), 'invoke']], + ['message' => 'Invalid', 'validate' => ['getValue' => []]], + ['message' => 'Invalid', 'validate' => ['eq' => ['key']]], + ['message' => 'Invalid', 'validate' => ['min' => ['one']]], + ['message' => 'Invalid', 'validate' => ['length' => ['min' => 1]]], + ['message' => 'Invalid', 'validate' => ['pregMatch' => ['/']]], + ['message' => 'Invalid', 'validate' => ['equal' => [[$object, 'invoke']]]], + ['message' => 'Invalid', 'validate' => ['oneOf' => [['length' => [1], 'allOf' => [['init' => []]]]]]], + ['message' => 'Invalid', 'validate' => ['oneOf' => [['required' => [], 'validateInData' => []]]]], + ['message' => 'Invalid', 'validate' => ['allOf' => [[get_class($object), 'invoke']]]], + ['message' => 'Invalid', 'type' => 'message', 'validate' => ['required' => []]], + ['message' => 'Invalid', 'type' => 'select', 'items' => []], + ['message' => 'Invalid', 'type' => 'select', 'items' => ['one'], 'default' => 0], + ['message' => 'Invalid', 'type' => 'multiselect', 'items' => ['one'], 'default' => ['0']], + ['type' => 'continue', 'items' => [$object, 'invoke']], + ]; + foreach ($invalid as $index => $row) { + [$prompt, $input, $output] = promptDefinitionSession("unused\n"); + $steps = ['first' => ['message' => 'First'], 'nested' => ['type' => 'continue', 'items' => ['bad' => $row]]]; + $case->expect(fn () => $prompt->runDefinition($steps))->isThrowable(InvalidArgumentException::class) + ->validate("invalid definition $index"); + $case->expect((string)$output === '' && $input->tell() === 0)->isTrue()->validate("no I/O for $index"); + } +}); + +group('Stored rules use canonical Validate predicates and isolate the original answer', static function (TestCase $case) { + [$prompt, , $output] = promptDefinitionSession( + "1.2\n1.2.0\nbad\0date\n30/11/2026\n2026-11-30 17:30\n12-34\nnot-a-date\n1990-01-01\n" + ); + $prompt->disableHeaderInfo(true); + $case->expect($prompt->runDefinition([ + 'version' => ['message' => 'Version', 'validate' => ['validVersion' => [true]], 'error' => 'Try again'], + 'date' => ['message' => 'Date', 'validate' => ['date' => ['d/m/Y']]], + 'time' => ['message' => 'Time', 'validate' => ['dateTime' => ['Y-m-d H:i']]], + 'zip' => ['message' => 'ZIP', 'validate' => ['allOf' => [['zip' => [4], 'length' => [5, 5]]]]], + 'age' => ['message' => 'Birthday', 'validate' => ['age' => [18]]], + ]) === ['version' => '1.2.0', 'date' => '30/11/2026', 'time' => '2026-11-30 17:30', 'zip' => '12-34', + 'age' => '1990-01-01'])->isTrue()->validate(); + $case->expect(str_contains((string)$output, "Version: Try again\nVersion: "))->isTrue()->validate(); +}); + +group('Trusted validator callbacks preserve per-item values and retry ordering', static function (TestCase $case) { + [$prompt, , $output] = promptDefinitionSession("first, bad, skipped\nfirst, valid\n0\n\n"); + $prompt->disableHeaderInfo(true); + $seen = []; + $row = [ + 'type' => 'list', + 'message' => 'Values', + 'validator' => static function (string $value) use (&$seen): bool { + $seen[] = $value; + return $value !== 'bad'; + }, + 'error' => static function (?string $type, mixed $input, array $row) use (&$seen): string { + $seen[] = [$type, $input, $row['message']]; + return 'Try again'; + }, + 'confirm' => 'Accepted', + ]; + $case->expect($prompt->promptLine($row) === ['first', 'valid'])->isTrue()->validate(); + $case->expect($seen === ['first', 'bad', [null, ['first', 'bad', 'skipped'], 'Values'], 'first', 'valid']) + ->isTrue()->validate(); + $case->expect((string)$output)->isEqualTo("Values (comma separate): Try again\nValues (comma separate): Accepted\n...\n") + ->validate(); + $case->expect(fn () => $prompt->promptLine(['message' => 'Both', 'validate' => [], 'validator' => 'is_string'])) + ->isThrowable(InvalidArgumentException::class)->validate(); + $case->expect(str_contains((string)$output, 'Both: '))->isFalse()->validate(); + $case->expect($prompt->promptLine(['message' => 'Callable name', 'validator' => 'is_string']) === '0') + ->isTrue()->validate(); + $case->expect(fn () => $prompt->promptLine(['message' => 'Bad return', 'validator' => 'strlen'])) + ->isThrowable(InvalidArgumentException::class)->validate(); +}); + +group('Stored and trusted multiselect distinguish empty, zero and original defaults', static function (TestCase $case) { + [$prompt, , $output] = promptDefinitionSession("\nnone\nnone\n1\n\n"); + $prompt->disableHeaderInfo(true); + $row = ['type' => 'multiselect', 'message' => 'Pick', 'items' => [0 => 'Zero', 'last' => 'Last'], + 'default' => ['last', 0]]; + $case->expect($prompt->set(['choices' => $row])->prompt() === ['choices' => [0, 'last']])->isTrue()->validate(); + $case->expect($prompt->runDefinition(['choices' => $row]) === ['choices' => []])->isTrue()->validate(); + $row['validate'] = ['required' => []]; + $row['error'] = 'Choose at least one'; + $case->expect($prompt->runDefinition(['choices' => $row]) === ['choices' => [0]])->isTrue()->validate(); + $case->expect(substr_count((string)$output, "Choose at least one\n") === 1)->isTrue()->validate(); + $row['validate'] = ['isRequired' => []]; + $case->expect($prompt->promptLine($row) === [0, 'last'])->isTrue()->validate(); + $case->expect($prompt->runDefinition(['choices' => $row]))->isFalse()->validate('end of input cancels'); +}); + +group('Nested retries consume input without changing the trusted context during replay', static function (TestCase $case) { + $answers = "seed\nx\nlong\nno\n" . str_repeat("x\n", 10000) . "long\nyes\nqueued\n"; + [$prompt, , $output] = promptDefinitionSession($answers); + $prompt->disableHeaderInfo(true); + $seen = null; + $prompt->set([ + 'skip' => ['type' => 'continue', 'items' => static function (mixed $previous, int $index) use (&$seen): bool { + $seen = [$previous, $index]; + return false; + }], + 'queued' => ['message' => 'Queued'], + ]); + $case->expect($prompt->promptLine(['message' => 'Seed']) === 'seed')->isTrue()->validate(); + $steps = ['nested' => ['type' => 'continue', 'items' => [ + 'answer' => ['message' => 'Answer', 'validate' => ['length' => [2]]], + 'confirm' => ['type' => 'confirm', 'message' => 'Confirm'], + ]]]; + $case->expect($prompt->runDefinition($steps))->isFalse()->validate(); + $case->expect($prompt->runDefinition($steps) === ['nested' => ['answer' => 'long', 'confirm' => 1]]) + ->isTrue()->validate(); + $case->expect($prompt->prompt() === ['skip' => true, 'queued' => 'queued'])->isTrue()->validate(); + $case->expect($seen === ['seed', 0])->isTrue()->validate(); + $case->expect(substr_count((string)$output, 'Answer: ') === 10003)->isTrue()->validate(); +}); + +group('Stored definitions snapshot references and leave the trusted queue intact after exceptions', static function (TestCase $case) { + $input = new Stream('php://memory'); + $input->write("first\nqueued\n"); + $input->rewind(); + $output = new Stream('php://memory'); + $command = new class (stream: $output, input: $input) extends Command { + public string $expected = 'first'; + + public function readline(string $message): string + { + if ($message === 'Throw') { + throw new LogicException('Read failed'); + } + $this->expected = 'changed during the run'; + return parent::readline($message); + } + }; + $prompt = (new Prompt($command))->disableHeaderInfo(true)->set(['queued' => ['message' => 'Queued']]); + $steps = [ + 'first' => ['message' => 'First', 'validate' => ['equal' => [&$command->expected]]], + 'second' => ['type' => 'continue', 'items' => [['message' => 'Throw']]], + ]; + $case->expect(fn () => $prompt->runDefinition($steps))->isThrowable(LogicException::class)->validate(); + $case->expect((string)$output === 'First: ')->isTrue()->validate(); + $case->expect($prompt->prompt() === ['queued' => 'queued'])->isTrue()->validate(); +}); From 67712f048538b7bf02cadd0fbfe872cca2d9a6b0 Mon Sep 17 00:00:00 2001 From: Daniel Ronkainen Date: Mon, 30 Nov 2026 18:18:10 +0100 Subject: [PATCH 05/15] feat: improve terminal blocks and ANSI styling --- README.md | 38 +++++ src/Navigation.php | 4 +- src/Themes/Ansi.php | 26 +++- src/Themes/Blocks.php | 230 +++++++++++++++++++++--------- tests/unitary-themes.php | 298 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 524 insertions(+), 72 deletions(-) create mode 100644 tests/unitary-themes.php diff --git a/README.md b/README.md index 2d71574..d7c7079 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ _Note that the prompt may not look as polished on Windows as on Unix, but it wil - [Available Options](#available-options) - [Available Prompt Types](#available-prompt-types) - [Command instance](#command-instance) +- [Terminal output](#terminal-output) - [Progress Bar](#progress-bar) - [Validation](#validation-and-error-handling) @@ -297,6 +298,43 @@ $command->approve("Print green approve message"); $command->approve("Print red error message"); ``` +## Terminal output + +`Command::getAnsi()` styles messages using the current terminal settings, including +messages written to a response stream. Call `disableAnsi(true)` to turn off +generated ANSI styles and `disableAnsi(false)` to restore automatic detection. +Cursor-based interactions also require a terminal stream. Check +`Command::hasCursorOutput()` before writing cursor controls. Use +`Ansi::cursorUp($lines)` to move up by a relative number of lines. The older +`moveCursorTo($line)` method is deprecated. + +```php +$command = new \MaplePHP\Prompts\Command(); +$blocks = new \MaplePHP\Prompts\Themes\Blocks($command); + +$blocks->table(['Command', 'Description'], [ + ['app list', 'List items'], + ['app add', 'Add an item'], +]); + +$blocks->addSection('Examples', fn ($section) => $section + ->addExample('app add "New item"', 'Add a named item')); +``` + +Pass a non-empty list of headings and a list of rows with one cell per heading. +An empty row list prints only the headings. Cells accept scalars and stringable +objects whose text is printable UTF-8 on a single line. Line breaks, tabs, and +cursor controls are rejected. Existing ANSI text styles are retained and take no +space in alignment. Wide CJK characters count as two columns and combining +marks take no extra space. Emoji widths can vary by terminal. + +Section descriptions given as strings are printed literally. For a function or +method callback, use a first-class callable or a callable array. `addExample()` +returns a new builder, as does the deprecated `addExamples()` method. +Use `addCode()` to print PHP with optional syntax highlighting. The source text +is preserved, including its whitespace, and plain output is available without +the tokenizer extension. + ## Progress Bar The `progress` method of the `Command` class allows displaying a progress bar with customizable sleep intervals to indicate ongoing operations. diff --git a/src/Navigation.php b/src/Navigation.php index 63dfcdd..e4bc11c 100755 --- a/src/Navigation.php +++ b/src/Navigation.php @@ -383,11 +383,11 @@ public function clearLines(int $lines): void return; } // Move the cursor up to the start - $this->command->getStream()->write($this->command->getAnsi()->moveCursorTo($lines)); + $this->command->getStream()->write($this->command->getAnsi()->cursorUp($lines)); for ($i = 0; $i < $lines; $i++) { $this->command->getStream()->write($this->command->getAnsi()->clearDown()); } // Move the cursor "back" up to the start - $this->command->getStream()->write($this->command->getAnsi()->moveCursorTo($lines)); + $this->command->getStream()->write($this->command->getAnsi()->cursorUp($lines)); } } diff --git a/src/Themes/Ansi.php b/src/Themes/Ansi.php index 34e300f..9527eaf 100755 --- a/src/Themes/Ansi.php +++ b/src/Themes/Ansi.php @@ -48,13 +48,14 @@ public function style(string|array|null $styles, string $message): string } /** - * Disable ANSI + * Disable ANSI or restore automatic terminal detection. * @param bool $disableAnsi * @return self */ public function disableAnsi(bool $disableAnsi): self { $this->disableAnsi = $disableAnsi; + $this->hasAnsi = null; return $this; } @@ -565,11 +566,12 @@ public function clearLine(): string } /** - * Move cursor to specified line + * Move the cursor up by the specified number of lines. * * @param int $line * @return string * @throws Exception + * @deprecated Use cursorUp(). */ public function moveCursorTo(int $line): string { @@ -579,6 +581,20 @@ public function moveCursorTo(int $line): string return "\033[{$line}A"; } + /** + * Move the cursor up by the specified number of lines. + * + * @param int $lines + * @return string + * @throws Exception + */ + public function cursorUp(int $lines): string + { + // Keep dispatching to existing overrides of the legacy cursor method. + /** @psalm-suppress DeprecatedMethod */ + return $this->moveCursorTo($lines); + } + /** * Move cursor down * @@ -679,14 +695,14 @@ final public function supportsUnicode(): bool final public function isSupported(): bool { if ($this->disableAnsi) { - $this->hasAnsi = false; + return false; } if ($this->hasAnsi === null) { if (stripos(PHP_OS, 'WIN') === 0) { $this->hasAnsi = false; } else { - $term = getenv('TERM') !== false ? getenv('TERM') : ""; - $this->hasAnsi = ($term !== "" && str_contains((string)$term, 'xterm')); + $term = getenv('TERM'); + $this->hasAnsi = is_string($term) && str_contains($term, 'xterm'); } } return $this->hasAnsi; diff --git a/src/Themes/Blocks.php b/src/Themes/Blocks.php index 54079a5..e5031b8 100644 --- a/src/Themes/Blocks.php +++ b/src/Themes/Blocks.php @@ -2,10 +2,15 @@ namespace MaplePHP\Prompts\Themes; +use InvalidArgumentException; use MaplePHP\Prompts\Command; +use ParseError; +use Stringable; class Blocks { + private const SGR = '/\x1b\[[0-9;:]*m/'; + private Command $command; private string $space; private array $options = []; @@ -13,6 +18,7 @@ class Blocks private int $optionsLength = 0; private array $list = []; private int $listLength = 0; + /** @var list */ private array $table = []; private int $tableLength = 0; @@ -84,7 +90,7 @@ public function addPadding(callable $content): void * Add a new section with a title and description * * @param string|null $title The title of the section - * @param string|callable $description The description text or a callback function that returns an instance of this class + * @param string|callable $description Literal description text or a non-string callable returning a Blocks instance * @return void */ public function addSection(?string $title, string|callable $description): void @@ -94,7 +100,7 @@ public function addSection(?string $title, string|callable $description): void $this->command->message(""); $this->command->message($this->command->getAnsi()->bold("{$title}:")); } - if (is_callable($description)) { + if (!is_string($description)) { $inst = $description($this); if ($inst instanceof self) { $inst->writeOptionLines(); @@ -127,7 +133,7 @@ public function severityLevel(string $severity, ?string $title = null): string /** * Create a row for cell - * @param callable $description + * @param callable(self): self $description * @return void */ public function addRow(callable $description): void @@ -137,6 +143,58 @@ public function addRow(callable $description): void $inst->writeTableLines(); } + /** + * Write a table with one line per row and two spaces between columns. + * + * @param array $headers A non-empty list of scalar or stringable column headings. + * @param array $rows Lists with one single-line UTF-8 scalar or stringable value per heading. + * @throws InvalidArgumentException If a row or cell cannot be rendered. + */ + public function table(array $headers, array $rows): void + { + if ($headers === [] || !array_is_list($headers) || !array_is_list($rows)) { + throw new InvalidArgumentException('A table requires a list of headings and a list of rows.'); + } + + $columnCount = count($headers); + $columnWidths = array_fill(0, $columnCount, 0); + $table = []; + foreach (array_merge([$headers], $rows) as $row) { + if (!is_array($row) || !array_is_list($row) || count($row) !== $columnCount) { + throw new InvalidArgumentException('Every table row must be a list with one cell per heading.'); + } + + $cells = []; + foreach ($row as $column => $cell) { + if (!is_scalar($cell) && !$cell instanceof Stringable) { + throw new InvalidArgumentException('Table cells must be scalars or stringable objects.'); + } + $text = (string)$cell; + $visible = self::withoutStyles($text); + if (preg_match('/[\p{Cc}\p{Zl}\p{Zp}]/u', $visible) !== 0) { + throw new InvalidArgumentException('Table cells must contain single-line printable UTF-8 text.'); + } + $width = self::textWidth($visible); + $columnWidths[$column] = max($columnWidths[$column], $width); + $cells[] = [$text, $width]; + } + $table[] = $cells; + } + + $ansi = $this->command->getAnsi(); + foreach ($table as $index => $row) { + $cells = []; + foreach ($row as $column => [$text, $width]) { + $cell = $index === 0 ? $ansi->bold($text) : $text; + if ($column < $columnCount - 1) { + $cell .= str_repeat(' ', $columnWidths[$column] - $width); + } + $cells[] = $cell; + } + $this->command->message(implode($this->space, $cells)); + } + } + /** * Adds a code block * @@ -159,38 +217,58 @@ public function addCode(string $code): void */ public function addCodeStyle(string $code, Ansi $ansi): string { + if (!$ansi->isSupported() || !function_exists('token_get_all')) { + return $code; + } - // Keywords like "use", "function", "new" - $code = preg_replace_callback('/\b(use|new)\b/', function ($m) use ($ansi) { - return $ansi->blue($m[1]); - }, $code); - - // Variables like $unit, $case, $valid - $code = preg_replace_callback('/(\$[a-zA-Z_]\w*)/', function ($m) use ($ansi) { - return $ansi->brightMagenta($m[1]); - }, $code); - - // Strings like "Lorem ipsum" - $code = preg_replace_callback('/(["\'])(.*?)(\1)/', function ($m) use ($ansi) { - return $ansi->cyan($m[1] . $m[2] . $m[3]); - }, $code); - - // Data types - $code = preg_replace_callback('/\b(callable|Closure|null|string|bool|float|int)\b/', function ($m) use ($ansi) { - return $ansi->brightCyan($m[1]); - }, $code); - - $code = preg_replace_callback('/\b(Unit|TestCase|TestConfig|Expect)\b/', function ($m) use ($ansi) { - return $ansi->brightCyan($m[1]); - }, $code); + try { + $tokens = token_get_all($code); + if (count($tokens) === 1 && is_array($tokens[0]) && $tokens[0][0] === T_INLINE_HTML) { + // Tokenize an untagged snippet as PHP, omitting the synthetic opening tag. + $tokens = token_get_all('brightBlue($m[1]) . '('; - }, $code); + $highlighted = ''; + foreach ($tokens as $index => $token) { + if (is_string($token)) { + $highlighted .= $token === '"' || $token === '`' ? $ansi->cyan($token) : $token; + continue; + } + [$type, $text] = $token; + $highlighted .= match ($type) { + T_OPEN_TAG, T_OPEN_TAG_WITH_ECHO, T_CLOSE_TAG, T_USE, T_NEW, T_FUNCTION, + T_FN, T_CLASS, T_RETURN, T_ECHO, T_PRINT => $ansi->blue($text), + T_VARIABLE => $ansi->brightMagenta($text), + T_CONSTANT_ENCAPSED_STRING, T_ENCAPSED_AND_WHITESPACE, T_START_HEREDOC, + T_END_HEREDOC => $ansi->cyan($text), + T_COMMENT, T_DOC_COMMENT => $ansi->grey($text), + T_CALLABLE, T_ARRAY => $ansi->brightCyan($text), + T_STRING, T_NAME_QUALIFIED, T_NAME_FULLY_QUALIFIED, T_NAME_RELATIVE => + $this->highlightName($text, $tokens, $index, $ansi), + default => $text, + }; + } + return $highlighted; + } + /** @param list $tokens */ + private function highlightName(string $text, array $tokens, int $index, Ansi $ansi): string + { + if (in_array(strtolower($text), [ + 'closure', 'null', 'string', 'bool', 'float', 'int', 'unit', 'testcase', 'testconfig', 'expect' + ], true)) { + return $ansi->brightCyan($text); + } - return $code; + // Comments and whitespace between a function name and "(" remain separate tokens. + do { + $next = $tokens[++$index] ?? null; + } while (is_array($next) && in_array($next[0], [T_WHITESPACE, T_COMMENT, T_DOC_COMMENT], true)); + return $next === '(' ? $ansi->brightBlue($text) : $text; } /** @@ -202,7 +280,7 @@ public function addCodeStyle(string $code, Ansi $ansi): string private function writeOptionLines(): void { foreach ($this->options as $key => $value) { - $space2 = str_repeat(" ", ($this->optionsLength - strlen($key) + 5)); + $space2 = str_repeat(" ", $this->optionsLength - self::labelWidth((string)$key) + 5); $this->command->message( $this->command->getAnsi()->cyan("{$this->space}{$key}{$space2}{$value}") ); @@ -218,7 +296,7 @@ private function writeOptionLines(): void private function writeListLines(): void { foreach ($this->list as $key => $value) { - $space2 = str_repeat(" ", ($this->listLength - strlen($key) + 5)); + $space2 = str_repeat(" ", $this->listLength - self::labelWidth((string)$key) + 5); $this->command->message( $this->command->getAnsi()->yellow("{$key}{$space2}{$value}") ); @@ -233,34 +311,13 @@ private function writeListLines(): void */ private function writeTableLines(): void { - $lineLength = 0; - $row = $this->buildRowsAndCells($this->table, $this->tableLength, $lineLength); - foreach ($row as $value) { - $this->command->message($value); - - } - $this->command->message(" "); - } - - private function buildRowsAndCells(array $arr, int $length, int &$lineLength): array - { - $row = []; - $lineLength = 0; - foreach ($arr as $value) { - $col1 = $value[0]; - $col2 = $value[1]; - $space2 = str_repeat(" ", ($length - strlen($col1) + 5)); - - $title = "{$col1}{$space2}"; + foreach ($this->table as [$label, $description]) { + $padding = str_repeat(" ", $this->tableLength - self::labelWidth($label) + 5); + $title = "{$label}{$padding}"; $title = $this->command->getAnsi()->style(["greyBg", "bold"], $title); - - $out = "{$title} {$col2}"; - $row[] = $out; - if(strlen($out) > $lineLength) { - $lineLength = strlen($out); - } + $this->command->message("{$title} {$description}"); } - return $row; + $this->command->message(" "); } @@ -276,7 +333,7 @@ private function writeExampleLines(): void $this->command->message( $this->command->getAnsi()->style(['yellow'], "{$this->space}{$key}") ); - if ($value) { + if ($value !== null && $value !== '') { $this->command->message( $this->command->getAnsi()->style(['grey', 'italic'], "{$this->space}{$this->space}{$value}") ); @@ -295,7 +352,7 @@ private function writeExampleLines(): void public function addOption(string $option, string $description): self { $inst = clone $this; - $length = strlen($option); + $length = self::labelWidth($option); $inst->options[$option] = $description; if ($length > $inst->optionsLength) { $inst->optionsLength = $length; @@ -314,7 +371,7 @@ public function addOption(string $option, string $description): self public function addList(string $option, string $description): self { $inst = clone $this; - $length = strlen($option); + $length = self::labelWidth($option); $inst->list[$option] = $description; if ($length > $inst->listLength) { $inst->listLength = $length; @@ -328,11 +385,11 @@ public function addList(string $option, string $description): self * * @param string $option The option name/flag to add * @param string $description The description text for this option - * @return self New instance with the option added + * @return self This instance with the cell added */ public function addCell(string $option, string $description): self { - $length = strlen($option); + $length = self::labelWidth($option); $this->table[] = [$option, $description]; if ($length > $this->tableLength) { $this->tableLength = $length; @@ -348,10 +405,53 @@ public function addCell(string $option, string $description): self * @param string|null $description Optional description text for this example * @return self New instance with the example added */ - public function addExamples(string $example, ?string $description = null): self + public function addExample(string $example, ?string $description = null): self { $inst = clone $this; $inst->examples[$example] = $description; return $inst; } + + /** @deprecated Use addExample(). */ + public function addExamples(string $example, ?string $description = null): self + { + return $this->addExample($example, $description); + } + + private static function withoutStyles(string $text): string + { + return preg_replace(self::SGR, '', $text) ?? $text; + } + + private static function labelWidth(string $label): int + { + return self::textWidth(self::withoutStyles($label)); + } + + private static function textWidth(string $text): int + { + $visible = $text; + // Some PHP builds use older external PCRE versions without the emoji properties. + if (PCRE_VERSION_MAJOR > 10 || PCRE_VERSION_MINOR >= 40) { + $emoji = '(?:\p{Emoji_Presentation}|\p{Emoji}(?=[\x{fe0f}\x{20e3}]|\p{Emoji_Modifier}))'; + $suffix = '\x{fe0f}?(?:\x{20e3}|\p{Emoji_Modifier})?'; + // Group flags, skin tones and joined emoji without merging adjacent base emoji. + $pattern = '/(?:\p{Regional_Indicator}{2}|' . $emoji . $suffix . '(?:\x{200d}\p{Emoji}' . $suffix . ')*)/u'; + $visible = preg_replace($pattern, ' ', $text) ?? $text; + } + + // Combining marks, format characters and trailing Hangul Jamo do not advance the cursor. + $visible = preg_replace('/[\p{M}\p{Cf}\x{1160}-\x{11ff}]/u', '', $visible); + if ($visible === null) { + // Older help builders also accept labels in byte-oriented encodings. + return strlen($text); + } + + // East Asian wide and fullwidth ranges occupy a second column. + $wide = '/[\x{1100}-\x{115f}\x{2329}\x{232a}\x{2e80}-\x{303e}\x{3040}-\x{a4cf}' . + '\x{ac00}-\x{d7a3}\x{f900}-\x{faff}\x{fe10}-\x{fe19}\x{fe30}-\x{fe6f}' . + '\x{ff01}-\x{ff60}\x{ffe0}-\x{ffe6}\x{16fe0}-\x{18dff}\x{1aff0}-\x{1b2ff}' . + '\x{1f200}-\x{1f251}\x{20000}-\x{3fffd}]/u'; + return (int)preg_match_all('/./su', $visible) + (int)preg_match_all($wide, $visible); + } } diff --git a/tests/unitary-themes.php b/tests/unitary-themes.php new file mode 100644 index 0000000..9e282ca --- /dev/null +++ b/tests/unitary-themes.php @@ -0,0 +1,298 @@ +getAnsi(); + $supportsAnsi = PHP_OS_FAMILY !== 'Windows'; + + $case->expect($standalone->isSupported() === $supportsAnsi && !$command->hasCursorOutput()) + ->isTrue()->validate(); + $command->title('Styled response'); + $case->expect((string)$stream === ($supportsAnsi ? "\033[1mStyled response\033[0m\n" : "Styled response\n")) + ->isTrue()->validate(); + + $case->expect($ansi->disableAnsi(disableAnsi: true) === $ansi && !$ansi->isSupported()) + ->isTrue()->validate(); + $case->expect($ansi->greenBg(' PASS ') === '[ PASS ]')->isTrue()->validate(); + $case->expect(fn () => $ansi->cursorUp(lines: 3))->isThrowable(Exception::class)->validate(); + putenv('TERM=dumb'); + $case->expect(!$ansi->disableAnsi(disableAnsi: false)->isSupported())->isTrue()->validate(); + + $ansi->disableAnsi(true); + putenv('TERM=xterm-256color'); + $case->expect($ansi->disableAnsi(false)->isSupported() === $supportsAnsi)->isTrue()->validate(); + if ($supportsAnsi) { + $case->expect($ansi->cursorUp(lines: 3) === "\033[3A")->isTrue()->validate(); + $case->expect($ansi->moveCursorTo(line: 3) === "\033[3A")->isTrue()->validate(); + } + $before = (string)$stream; + (new Navigation($command))->clearLines(3); + $case->expect((string)$stream === $before)->isTrue()->validate(); + } finally { + putenv($term === false ? 'TERM' : "TERM=$term"); + } +}); + +group('Navigation retains its cursor override contract', static function (TestCase $case) { + $styles = new class extends Ansi { + public function moveCursorTo(int $line): string + { + return ""; + } + + public function clearDown(): string + { + return ''; + } + }; + $makeCommand = static fn (Ansi $styles): Command => new class ($styles) extends Command { + public function __construct(private Ansi $styles) + { + parent::__construct(new Stream('php://memory')); + } + + public function getAnsi(): Ansi + { + return $this->styles; + } + + public function hasCursorOutput(): bool + { + return true; + } + }; + $command = $makeCommand($styles); + (new Navigation($command))->clearLines(2); + $case->expect((string)$command->getStream() === '') + ->isTrue()->validate(); + + $newStyles = new class extends Ansi { + public function cursorUp(int $lines): string + { + return ""; + } + + public function clearDown(): string + { + return ''; + } + }; + $command = $makeCommand($newStyles); + (new Navigation($command))->clearLines(1); + $case->expect((string)$command->getStream() === '') + ->isTrue()->validate(); +}); + +group('Blocks aligns table columns using visible text width', static function (TestCase $case) { + $term = getenv('TERM'); + try { + putenv('TERM=xterm-256color'); + $output = new Stream('php://memory'); + $command = new Command($output); + $blocks = new Blocks($command); + $ansi = $command->getAnsi(); + $decomposed = "e\u{0301}"; + $styled = "\033[38:2::41:42:43m界\033[0m"; + $counted = new class implements Stringable { + public int $casts = 0; + + public function __toString(): string + { + $this->casts++; + return 'É'; + } + }; + + $headers = ['Key', 'Value', 'Flag']; + $rows = [[$styled, $decomposed, true], [$counted, 0, false], ['漢字', 2.5, 'ok']]; + $blocks->table(headers: $headers, rows: $rows); + + $expected = "Key Value Flag\n界 $decomposed 1\nÉ 0 \n漢字 2.5 ok\n"; + $colored = (string)$output; + $heading = $ansi->bold('Key') . ' ' . $ansi->bold('Value') . ' ' . $ansi->bold('Flag'); + $case->expect(str_starts_with($colored, $heading . "\n") && str_contains($colored, $styled)) + ->isTrue()->validate(); + $case->expect(promptsThemeWithoutSgr($colored) === $expected)->isTrue()->validate($colored); + $case->expect($counted->casts === 1)->isTrue()->validate(); + + $ansi->disableAnsi(true); + $blocks->table(headers: [0], rows: []); + $blocks->table(headers: $headers, rows: $rows); + $case->expect((string)$output === $colored . "0\n" . str_replace('界 ', $styled . ' ', $expected)) + ->isTrue()->validate((string)$output); + } finally { + putenv($term === false ? 'TERM' : "TERM=$term"); + } +}); + +group('Blocks rejects invalid tables before any output', static function (TestCase $case) { + $output = new Stream('php://memory'); + $blocks = new Blocks(new Command($output)); + $validRow = ['ok', 0]; + foreach ([ + [[], []], + [[1 => 'Name'], []], + [['Name'], [1 => ['Value']]], + [['Name'], ['Value']], + [['Name'], [['named' => 'Value']]], + [['Name', 'Value'], [$validRow, ['Too short']]], + [['Name', 'Value'], [$validRow, ['Too', 'many', 'cells']]], + [['Name', 'Value'], [$validRow, ['Invalid', null]]], + [['Name', 'Value'], [$validRow, ['Invalid', []]]], + [['Name', 'Value'], [$validRow, ['Invalid', new stdClass()]]], + [['Name', 'Value'], [$validRow, ["Two\nlines", 'Invalid']]], + [['Name', 'Value'], [$validRow, ["Two\rlines", 'Invalid']]], + [['Name', 'Value'], [$validRow, ["Two\u{2028}lines", 'Invalid']]], + [['Name', 'Value'], [$validRow, ["Tab\tstop", 'Invalid']]], + [['Name', 'Value'], [$validRow, ["\033[2K", 'Invalid']]], + [['Name', 'Value'], [$validRow, ["\xff", 'Invalid']]], + ] as [$headers, $rows]) { + $case->expect(fn () => $blocks->table($headers, $rows))->isThrowable(InvalidArgumentException::class) + ->validate(); + } + $case->expect((string)$output === '')->isTrue()->validate(); +}); + +$emojiWidth = TestConfig::make('Blocks measures common emoji sequences in terminal columns') + ->withSkip(PCRE_VERSION_MAJOR === 10 && PCRE_VERSION_MINOR < 40); +group($emojiWidth, static function (TestCase $case) { + $output = new Stream('php://memory'); + $command = new Command($output); + $command->getAnsi()->disableAnsi(true); + (new Blocks($command))->table(['A', 'B'], [ + ['🙂', 1], ['👩🏽‍💻', 2], ['🇸🇪', 3], ["1\u{fe0f}\u{20e3}", 4], ['🙂🙂', 5], ['☝🏽', 6], + ]); + $case->expect((string)$output === "A B\n🙂 1\n👩🏽‍💻 2\n🇸🇪 3\n1️⃣ 4\n🙂🙂 5\n☝🏽 6\n") + ->isTrue()->validate((string)$output); +}); + +group('Blocks keeps literal section text and the legacy builder contracts', static function (TestCase $case) { + $output = new Stream('php://memory'); + $command = new Command($output); + $command->getAnsi()->disableAnsi(true); + $blocks = new Blocks($command); + $blocks->addSection(null, 'strlen'); + $blocks->addSection(null, 'DateTime::createFromFormat'); + + $styled = "\033[3m界\033[0m"; + $decomposed = "e\u{0301}"; + $builder = new class ($styled, $decomposed) { + public function __construct(private string $styled, private string $decomposed) + { + } + + public function section(Blocks $blocks): Blocks + { + return $blocks->addOption(option: $this->styled, description: 'First') + ->addOption($this->decomposed, 'Second') + ->addList($this->styled, 'Third') + ->addList('A', 'Fourth') + ->addExample(example: 'app new', description: '0') + ->addExamples(example: 'app old'); + } + }; + $blocks->addSection(null, [$builder, 'section']); + $blocks->addSection(null, static fn (Blocks $section): Blocks => $section); + $blocks->addRow(static function (Blocks $row) use ($case, $styled, $decomposed): Blocks { + $case->expect($row->addCell(option: $styled, description: 'First') === $row)->isTrue()->validate(); + return $row->addCell($decomposed, 'Second'); + }); + $blocks->addRow(static fn (Blocks $row): Blocks => $row); + + $case->expect(promptsThemeWithoutSgr((string)$output) === + " strlen\n DateTime::createFromFormat\n 界 First\n $decomposed Second\n" . + "界 Third\nA Fourth\n app new\n 0\n app old\n[界 ] First\n[$decomposed ] Second\n \n \n") + ->isTrue()->validate((string)$output); +}); + +group('PHP highlighting preserves token text, whitespace and mixed HTML', static function (TestCase $case) { + $term = getenv('TERM'); + try { + putenv('TERM=xterm-256color'); + $output = new Stream('php://memory'); + $command = new Command($output); + $blocks = new Blocks($command); + $ansi = $command->getAnsi(); + $snippet = <<<'PHP' + $value = factory /* new Example('x') */ ('it\'s $safe'); + $other = <<expect(promptsThemeWithoutSgr($blocks->addCodeStyle($code, $ansi)) === $code) + ->isTrue()->validate($code); + } + + if ($ansi->isSupported() && function_exists('token_get_all')) { + $colored = $blocks->addCodeStyle($snippet, $ansi); + $case->expect(str_contains($colored, $ansi->brightMagenta('$value')) && + str_contains($colored, $ansi->brightBlue('factory') . ' ' . $ansi->grey("/* new Example('x') */")) && + str_contains($colored, $ansi->cyan("'it\\'s \$safe'")) && + str_contains($colored, $ansi->cyan(" Use new and call(\"a\").\r\n"))) + ->isTrue()->validate($colored); + $colored = $blocks->addCodeStyle($tagged, $ansi); + $case->expect(str_starts_with($colored, "

new example() \$variable

\r\n") && + str_ends_with($colored, '

new()

') && + str_contains($colored, $ansi->blue('echo') . ' ' . $ansi->brightMagenta('$value'))) + ->isTrue()->validate($colored); + } + + $ansi->disableAnsi(true); + $case->expect($blocks->addCodeStyle($snippet, $ansi) === $snippet && + $blocks->addCodeStyle($tagged, $ansi) === $tagged)->isTrue()->validate(); + $blocks->addCode($snippet); + $case->expect((string)$output === "\n$snippet\n\n")->isTrue()->validate(); + } finally { + putenv($term === false ? 'TERM' : "TERM=$term"); + } +}); + +group('PHP highlighting falls back to the source when tokenizer is unavailable', static function (TestCase $case) { + $code = <<<'PHP' + require 'vendor/autoload.php'; + putenv('TERM=xterm-256color'); + $ansi = new \MaplePHP\Prompts\Themes\Ansi(); + $blocks = new \MaplePHP\Prompts\Themes\Blocks(new \MaplePHP\Prompts\Command()); + $source = "\$example = new Example();\n"; + echo $blocks->addCodeStyle($source, $ansi); + PHP; + $process = proc_open([PHP_BINARY, '-d', 'disable_functions=token_get_all', '-r', $code], + [['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']], $pipes, dirname(__DIR__)); + if (!is_resource($process)) { + throw new RuntimeException('Could not start PHP without tokenizer'); + } + + fclose($pipes[0]); + $stdout = stream_get_contents($pipes[1]); + $stderr = stream_get_contents($pipes[2]); + fclose($pipes[1]); + fclose($pipes[2]); + $case->expect(proc_close($process) === 0 && $stderr === '')->isTrue()->validate($stderr); + $case->expect($stdout === "\$example = new Example();\n")->isTrue()->validate($stdout); +}); From 6e5ed9209fad65662586bab916981cc5de5dea18 Mon Sep 17 00:00:00 2001 From: Daniel Ronkainen Date: Mon, 30 Nov 2026 18:23:11 +0100 Subject: [PATCH 06/15] fix: type public API and terminal handles --- src/Command.php | 104 +++++++++++++------ src/Exceptions/InputExhaustedException.php | 1 + src/Exceptions/InputInterruptedException.php | 1 + src/Exceptions/PromptException.php | 1 + src/Navigation.php | 1 + src/Prompt.php | 1 + src/SttyWrapper.php | 4 + src/Themes/Ansi.php | 3 +- src/Themes/Blocks.php | 1 + tests/unitary-input.php | 36 ++++++- 10 files changed, 122 insertions(+), 31 deletions(-) diff --git a/src/Command.php b/src/Command.php index 4d05817..346173f 100755 --- a/src/Command.php +++ b/src/Command.php @@ -15,6 +15,7 @@ /** * Class Command * @package MaplePHP\Prompts + * @api */ class Command { @@ -83,12 +84,18 @@ public function readInputByte(): string /** @internal Whether native input has a byte ready within the given microseconds. */ public function inputIsReady(int $microseconds): bool { + if ($this->inputLookahead->byte !== '') { + return true; + } $input = $this->getInput(); - $unread = $input->getMetadata('unread_bytes'); - if ($this->inputLookahead->byte !== '' || (is_int($unread) && $unread > 0)) { + $resource = $input instanceof Stream ? $this->nativeResource($input) : null; + if ($input instanceof Stream && $resource === null) { + return false; + } + if ($this->hasUnreadBytes($input->getMetadata('unread_bytes'))) { return true; } - if (!function_exists('stream_select') || !$input instanceof Stream || !is_resource($resource = $input->getResource())) { + if (!function_exists('stream_select') || $resource === null) { return false; } $read = [$resource]; @@ -112,10 +119,19 @@ public function finishInputEnter(): void */ public function hasTerminalInput(): bool { - return defined('STDIN') && - ($this->input === null || ($this->input instanceof Stream && - ($this->input->getResource() === STDIN || $this->input->getStream() === Stream::STDIN))) && - $this->standardInputIsTerminal(); + $stdin = $this->standardInputResource(); + if ($stdin === null) { + return false; + } + if ($this->input !== null) { + if (!$this->input instanceof Stream || ($resource = $this->nativeResource($this->input)) === null) { + return false; + } + if ($resource !== $stdin && $this->input->getStream() !== Stream::STDIN) { + return false; + } + } + return $this->standardInputIsTerminal($stdin); } /** @@ -127,8 +143,8 @@ public function hasCursorOutput(): bool if (!$this->getAnsi()->isSupported() || !$output instanceof Stream) { return false; } - $resource = $output->getResource(); - return is_resource($resource) && stream_isatty($resource); + $resource = $this->nativeResource($output); + return $resource !== null && stream_isatty($resource); } /** @@ -168,12 +184,15 @@ public function getAnsi(): Ansi */ public function readline(string $message): string { - if (function_exists('readline') && $this->hasCursorOutput() && defined('STDIN') && is_resource(STDIN) && - $this->inputLookahead->byte === '' && !stream_get_meta_data(STDIN)['unread_bytes'] && $this->hasTerminalInput() && - defined('STDOUT') && stream_isatty(STDOUT) && + $stdin = $this->standardInputResource(); + /** @var resource|closed-resource|null $stdout The CLI handle can have been closed. */ + $stdout = defined('STDOUT') ? STDOUT : null; + if (function_exists('readline') && $this->hasCursorOutput() && $stdin !== null && + $this->inputLookahead->byte === '' && !$this->hasUnreadBytes(stream_get_meta_data($stdin)['unread_bytes']) && + $this->hasTerminalInput() && is_resource($stdout) && stream_isatty($stdout) && $this->stream instanceof Stream && - ($this->stream->getResource() === STDOUT || $this->stream->getStream() === Stream::STDOUT) && - ($this->input === null || !$this->input->getMetadata('unread_bytes'))) { + ($this->stream->getResource() === $stdout || $this->stream->getStream() === Stream::STDOUT) && + ($this->input === null || !$this->hasUnreadBytes($this->input->getMetadata('unread_bytes')))) { $line = readline("$message: "); if ($line === false) { throw new InputExhaustedException(); @@ -236,6 +255,7 @@ public function title(string $message, bool $break = true): void * @param bool $break Add new line * @return string|false * @deprecated Use success() to display a success message. + * @api */ public function approve(string $message, bool $break = true): string|false { @@ -248,6 +268,8 @@ public function approve(string $message, bool $break = true): string|false */ public function success(string $message, bool $break = true): void { + // Keep dispatching to existing overrides of approve(). + /** @psalm-suppress DeprecatedMethod */ $this->approve($message, $break); } @@ -258,6 +280,7 @@ public function success(string $message, bool $break = true): void * @param bool $break Add new line * @return string|false * @deprecated Use status() to display a status message. + * @api */ public function statusMsg(string $message, bool $break = true): string|false { @@ -270,6 +293,8 @@ public function statusMsg(string $message, bool $break = true): string|false */ public function status(string $message, bool $break = true): void { + // Keep dispatching to existing overrides of statusMsg(). + /** @psalm-suppress DeprecatedMethod */ $this->statusMsg($message, $break); } @@ -488,13 +513,32 @@ private function selectMenu(string $message, array $items): int|string return $navigation->getValue(); } - private function standardInputIsTerminal(): bool + /** @return resource|null */ + private function standardInputResource() { - if (!defined('STDIN') || !is_resource(STDIN)) { - return false; - } - if (!stream_get_meta_data(STDIN)['unread_bytes']) { - return stream_isatty(STDIN); + /** @var resource|closed-resource|null $stdin The CLI handle can have been closed. */ + $stdin = defined('STDIN') ? STDIN : null; + return is_resource($stdin) ? $stdin : null; + } + + /** @return resource|null */ + private function nativeResource(Stream $stream) + { + /** @var resource|closed-resource|null $resource The underlying handle can be closed or detached. */ + $resource = $stream->getResource(); + return is_resource($resource) ? $resource : null; + } + + private function hasUnreadBytes(mixed $unreadBytes): bool + { + return is_int($unreadBytes) && $unreadBytes > 0; + } + + /** @param resource $stdin */ + private function standardInputIsTerminal($stdin): bool + { + if (!$this->hasUnreadBytes(stream_get_meta_data($stdin)['unread_bytes'])) { + return stream_isatty($stdin); } // Older PHP versions can disturb buffered input when casting a stream for stream_isatty(). @@ -508,19 +552,21 @@ private function standardInputIsTerminal(): bool private function isUnverifiedTerminalInput(): bool { - if ($this->input === null) { + $input = $this->input; + if ($input === null) { + return false; + } + $resource = $input instanceof Stream ? $this->nativeResource($input) : null; + if ($input instanceof Stream && $resource === null) { return false; } - $uri = $this->input->getMetadata('uri'); + $uri = $input->getMetadata('uri'); if ($uri === Stream::STDIN || $uri === 'php://fd/0') { - return $this->standardInputIsTerminal(); + $stdin = $this->standardInputResource(); + return $stdin !== null && $this->standardInputIsTerminal($stdin); } - if ($this->input instanceof Stream) { - $resource = $this->input->getResource(); - if (!is_resource($resource)) { - return false; - } - if ($this->input->getMetadata('unread_bytes')) { + if ($resource !== null) { + if ($this->hasUnreadBytes($input->getMetadata('unread_bytes'))) { // Avoid casting an input with pending bytes. TTYs are character devices. $stat = fstat($resource); return $stat === false || ($stat['mode'] & 0170000) === 0020000; diff --git a/src/Exceptions/InputExhaustedException.php b/src/Exceptions/InputExhaustedException.php index 7ee41c6..c8bb64e 100644 --- a/src/Exceptions/InputExhaustedException.php +++ b/src/Exceptions/InputExhaustedException.php @@ -2,6 +2,7 @@ namespace MaplePHP\Prompts\Exceptions; +/** @api */ class InputExhaustedException extends PromptException { public function __construct() diff --git a/src/Exceptions/InputInterruptedException.php b/src/Exceptions/InputInterruptedException.php index b73a25b..7e92f17 100644 --- a/src/Exceptions/InputInterruptedException.php +++ b/src/Exceptions/InputInterruptedException.php @@ -2,6 +2,7 @@ namespace MaplePHP\Prompts\Exceptions; +/** @api */ class InputInterruptedException extends PromptException { public function __construct() diff --git a/src/Exceptions/PromptException.php b/src/Exceptions/PromptException.php index a758fe6..447d8a1 100755 --- a/src/Exceptions/PromptException.php +++ b/src/Exceptions/PromptException.php @@ -4,6 +4,7 @@ use Exception; +/** @api */ class PromptException extends Exception { } diff --git a/src/Navigation.php b/src/Navigation.php index e4bc11c..d26746d 100755 --- a/src/Navigation.php +++ b/src/Navigation.php @@ -11,6 +11,7 @@ /** * Class Navigation * @package MaplePHP\Prompts + * @api */ class Navigation { diff --git a/src/Prompt.php b/src/Prompt.php index eccb7c1..882d0db 100755 --- a/src/Prompt.php +++ b/src/Prompt.php @@ -9,6 +9,7 @@ use MaplePHP\Prompts\Exceptions\PromptException; use MaplePHP\Validate\Validator; +/** @api */ class Prompt { private const TYPES = [ diff --git a/src/SttyWrapper.php b/src/SttyWrapper.php index 13592c4..7334271 100755 --- a/src/SttyWrapper.php +++ b/src/SttyWrapper.php @@ -7,6 +7,7 @@ /** * Class SttyWrapper * @package MaplePHP\Prompts + * @api */ class SttyWrapper { @@ -139,6 +140,9 @@ public function hasSttySupport(): bool /** * Apply settings to standard input for the duration of a terminal operation. * + * @template T + * @param callable(): T $callback + * @return T * @throws PromptException */ public function withTerminalMode(callable $callback, string ...$settings): mixed diff --git a/src/Themes/Ansi.php b/src/Themes/Ansi.php index 9527eaf..e62eddb 100755 --- a/src/Themes/Ansi.php +++ b/src/Themes/Ansi.php @@ -8,6 +8,7 @@ /** * Class Ansi * @package MaplePHP\Prompts + * @api */ class Ansi { @@ -100,7 +101,7 @@ public function line(int $lineLength, int $color = 90): string public function dashedLine(int $lineLength, int $color = 90): string { $thin = $this->supportsUnicode() ? "\u{200A}" : ""; - $line = str_repeat("─$thin", round($lineLength/2)); + $line = str_repeat("─$thin", (int)round($lineLength/2)); if ($this->isSupported()) { return "\033[1;{$color}m$line\033[0m"; } diff --git a/src/Themes/Blocks.php b/src/Themes/Blocks.php index e5031b8..c1363c6 100644 --- a/src/Themes/Blocks.php +++ b/src/Themes/Blocks.php @@ -7,6 +7,7 @@ use ParseError; use Stringable; +/** @api */ class Blocks { private const SGR = '/\x1b\[[0-9;:]*m/'; diff --git a/tests/unitary-input.php b/tests/unitary-input.php index 0d840c1..4ce948c 100644 --- a/tests/unitary-input.php +++ b/tests/unitary-input.php @@ -143,6 +143,39 @@ public function getMetadata(?string $key = null): mixed $case->expect(fn () => $blocked->ask('Blocked'))->isThrowable(PromptException::class)->validate(); }); +group('Command capability checks handle closed and detached native streams', static function (TestCase $case) { + $resource = fopen('php://memory', 'r+'); + $input = new Stream($resource); + $output = new Stream('php://memory'); + $command = new Command(stream: $output, input: $input); + + fclose($resource); + $output->detach(); + $case->expect($command->inputIsReady(0))->isFalse()->validate(); + $case->expect($command->hasTerminalInput())->isFalse()->validate(); + $case->expect($command->hasCursorOutput())->isFalse()->validate(); +}); + +group('Command success and status retain legacy subclass overrides', static function (TestCase $case) { + $output = new Stream('php://memory'); + $command = new class ($output) extends Command { + public function approve(string $message, bool $break = true): string|false + { + $this->line("Approved $message", $break); + return false; + } + + public function statusMsg(string $message, bool $break = true): string|false + { + $this->line("Status $message", $break); + return false; + } + }; + $command->success(message: 'result', break: false); + $command->status(message: 'ready'); + $case->expect((string)$output)->isEqualTo("Approved resultStatus ready\n")->validate(); +}); + group('Masked input preserves whitespace and keeps passwords out of output', static function (TestCase $case) { $output = new Stream('php://memory'); $command = new Command(stream: $output, input: new PromptsPsrInput(" secret \\ \t\r\n\n")); @@ -206,7 +239,8 @@ public function getMetadata(?string $key = null): mixed try { $copy->ask('Exhausted'); } catch (\MaplePHP\Prompts\Exceptions\InputExhaustedException) { - exit(0); + fclose(STDIN); + exit((int)($copy->hasTerminalInput() || $copy->inputIsReady(0))); } exit(1); PHP; From d12b394f00b8f299ed802a1c9ab97efd2cfbd22a Mon Sep 17 00:00:00 2001 From: Daniel Ronkainen Date: Mon, 30 Nov 2026 18:29:59 +0100 Subject: [PATCH 07/15] docs: explain Prompts workflows and verify supported platforms --- .github/workflows/php.yml | 48 ++++ README.md | 555 +++----------------------------------- docs/guide.md | 229 ++++++++++++++++ docs/migration.md | 52 ++++ examples/command.php | 40 +++ examples/example.php | 194 ++++++------- 6 files changed, 489 insertions(+), 629 deletions(-) create mode 100644 .github/workflows/php.yml create mode 100644 docs/guide.md create mode 100644 docs/migration.md create mode 100644 examples/command.php diff --git a/.github/workflows/php.yml b/.github/workflows/php.yml new file mode 100644 index 0000000..31094b6 --- /dev/null +++ b/.github/workflows/php.yml @@ -0,0 +1,48 @@ +name: PHP Prompts + +on: + push: + branches: [main, develop] + pull_request: + branches: [main, develop] + workflow_dispatch: + +permissions: + contents: read + +jobs: + test: + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest] + php: ['8.2', '8.3', '8.4', '8.5'] + include: + - os: windows-latest + php: '8.4' + env: + COMPOSER_ROOT_VERSION: 1.2.x-dev + TERM: dumb + + steps: + - uses: actions/checkout@v4 + + - name: Set up PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + coverage: none + tools: composer:v2 + + - name: Install dependencies + run: composer install --prefer-dist --no-interaction --no-progress + + - name: Run suite, including piped-input fixtures + run: php vendor/bin/unitary + + - name: Run errors-only suite with terminal formatting + if: matrix.os == 'ubuntu-latest' && matrix.php == '8.4' + env: + TERM: xterm-256color + run: php vendor/bin/unitary --errors-only diff --git a/README.md b/README.md index d7c7079..1797c3e 100644 --- a/README.md +++ b/README.md @@ -1,543 +1,74 @@ # MaplePHP Prompts -PHP Prompts is a pretty, interactive, lightweight, and user-friendly CLI (Command Line Interface) PHP library designed for seamless use across Linux, Unix, Darwin, and Windows. It allows you to create and manage user prompts in a command-line environment, enabling the collection of various types of input with built-in validation and feedback. - -![Prompt demo](http://wazabii.se/github-assets/maplephp-prompt-v2.gif) - -_Note that the prompt may not look as polished on Windows as on Unix, but it will work just as well._ - -### Table of Contents -- [Installation](#installation) -- [Usage Example](#usage-example) -- [Available Options](#available-options) -- [Available Prompt Types](#available-prompt-types) -- [Command instance](#command-instance) -- [Terminal output](#terminal-output) -- [Progress Bar](#progress-bar) -- [Validation](#validation-and-error-handling) +Build PHP command-line tools with questions, menus, hidden input, validation, and formatted output. Use `Command` to control the interaction step by step or `Prompt` to run a workflow such as an installer. Both use the same terminal and piped-input support. ## Installation -To install PHP Prompts, use Composer: +Prompts requires PHP 8.2 or later. Install it in your application with Composer. -```bash +```sh composer require maplephp/prompts ``` -## Usage Example - -Below is an example demonstrating how to use the PHP Prompts library to create interactive prompts and validate user input. - -### Step-by-Step Guide - -1. **Initialize** - -```php -$prompt = new \MaplePHP\Prompts\Prompt(); -``` - -2. **Set the Title and Description for the Prompts** - - This step is optional but provides context for the user. - - ```php - $prompt->setTitle("Hello there!"); - $prompt->setDescription("We need your contact information to stay in touch, thank you."); - ``` - -3. **Define the Prompts** - - Define the prompts and their respective settings, including type, message, validation rules, and error messages. - ```php - $prompt->set([ - "name" => [ - "type" => "text", - "message" => "Full Name", - "validate" => [ - "length" => [1,200] - ] - ], - "email" => [ - "type" => "text", - "message" => "Email", - "validate" => [ - "length" => [1,200], - "email" => [] - ], - "error" => "The email address entered is not valid." - ], - "newsletter" => [ - "type" => "toggle", - "message" => "Receive newsletter?", - ], - "method" => [ - "type" => "select", - "message" => "Preferred contact method?", - "items" => [ - "email" => "Email", - "phone" => "Phone" - ], - ], - "contactByPhone" => [ - "type" => "continue", - "items" => function($prevVal) { - if($prevVal === "phone") { - return [ - "phone" => [ - "type" => "text", - "message" => "Phone", - "validate" => [ - "length" => [1,30], - "phone" => [] - ] - ] - ]; - } - return false; - } - ], - "confirm" => [ - "type" => "confirm", - "message" => "Do you wish to continue?" - ] - ]); - ``` -4. **Execute the Prompt** - - Prompt the user for input based on the defined prompts above. The collected user input will be saved in the `$prompt` variable. - - ```php - // Execute the prompt - $prompt = $prompt->prompt(); - // Print out the user inputs - print_r($prompt); - ``` - - -## Available Options - -1. **type** - - **Description**: Specifies the type of the prompt (e.g., `text`, `password`, `toggle`, `select`, `list`, `continue`, `message`, `confirm`). - - **Example**: `"type" => "text"` - -2. **message** - - **Description**: The message or question displayed to the user. - - **Example**: `"message" => "Enter your full name"` - -3. **default** - - **Description**: A default value for the prompt, used if the user does not provide input. - - **Example**: `"default" => "Your default value"` - -4. **items** - - **Description**: An array of items to choose from, used with `select` type prompts. - - **Example**: `"items" => ["Option 1", "Option 2", "Option 3"]` +The quickstarts use the API in this checkout. To try it before it is available in a release, run `composer install` in the package root and use the included demos. -5. **validate** - - **Description**: Validation rules for the input. Can be an array of rules or a custom function. - - **Examples**: - - Length validation: `"validate" => ["length" => [1, 200]]` - - Custom function validation: - ```php - "validate" => function($input) { - return strlen($input) >= 3; - } - ``` +## Quickstart with Command -6. **error** - - **Description**: Error message or function to display when validation fails. - - **Examples**: - - Static message: `"error" => "Input is required"` - - Custom function error: - ```php - "error" => function($errorType, $input, $row) { - if ($errorType === "length") { - return "Is required"; - } - return "Must be a number"; - } - ``` - -7. **confirm** - - **Description**: Message to display upon user confirmation, used with `confirm` type prompts. - - **Example**: `"confirm" => "Are you sure you want to continue?"` - -## Available Prompt Types - -### Summary - -- **text**: Prompts for regular text input. -- **password**: Prompts for masked password input. -- **toggle**: Asks a yes/no question. -- **select**: Provides a list of options for selection. -- **list**: Prompts for a comma-separated list of values. -- **continue**: Continue with input dependent on previous value -- **message**: Displays a message (no input). -- **confirm**: Asks for confirmation before proceeding. - -### Details - -1. **text** - - **Description**: Prompts the user for regular text input. - - **Usage Example**: - ```php - "firstname" => [ - "type" => "text", - "message" => "First name" - ] - ``` - -2. **password** - - **Description**: Prompts the user for password input, masking the characters as they are typed. - - **Usage Example**: - ```php - "password" => [ - "type" => "password", - "message" => "Password" - ] - ``` - -3. **toggle** - - **Description**: Asks the user a yes/no question. - - **Usage Example**: - ```php - "ssl" => [ - "type" => "toggle", - "message" => "Do you want SSL?" - ] - ``` - -4. **select** - - **Description**: Provides a list of options for the user to choose from. - - **Usage Example**: - ```php - "select" => [ - "type" => "select", - "message" => "Select an item below", - "items" => [ - "Lorem 1", - "Lorem 2", - "Lorem 3" - ] - ] - ``` - -5. **list** - - **Description**: Prompts the user for a comma-separated list of values. - - **Usage Example**: - ```php - "keyword" => [ - "type" => "list", - "message" => "Keywords" - ] - ``` -5. **continue** - - **Description**: Continue with input dependent on previous value. - - **Usage Example**: - ```php - "continue" => [ - "type" => "continue", - "items" => function($prevVal) { - if($prevVal === "phone") { - return [ - "phone" => [ - "type" => "text", - "message" => "Phone", - "validate" => [ - "length" => [1,30], - "phone" => [] - ] - ] - ]; - } - return false; - } - ] - ``` -6. **message** - - **Description**: Displays a message to the user. This type does not collect input and will be excluded from the end result array. - - **Usage Example**: - ```php - "message" => [ - "type" => "message", - "message" => "Lorem ipsum dolor" - ] - ``` - -7. **confirm** - - **Description**: Asks the user for confirmation before proceeding. Can display a custom confirmation message. - - **Usage Example**: - ```php - "confirm" => [ - "type" => "confirm", - "message" => "Do you wish to continue?" - ] - ``` - -These prompt types enable a variety of user interactions in a CLI environment, making it easy to collect and validate different kinds of input using the PHP Prompts library. - -## Command instance -You also execute some of the prompt above command directly with the Command class. +Use direct method calls when application code decides what to ask and what to print. Save this as `command.php` next to your application's `vendor` directory and run `php command.php`. ```php -$command = new \MaplePHP\Prompts\Command(); -// Print messages and return input -$input = $command->message("Text field", true); -$input = $command->mask("Masked input (password)"); -$input = $command->toggle("Toggle yes/no"); -$input = $command->select("Choose a value", [ - //... -]); -$input = $command->list("Comma seperated list"); -$input = $command->confirm("Confirm"); +message("Print message"); -$command->title("Print bolded message"); -$command->statusMsg("Print blue status message"); -$command->approve("Print green approve message"); -$command->approve("Print red error message"); -``` - -## Terminal output +require __DIR__ . '/vendor/autoload.php'; -`Command::getAnsi()` styles messages using the current terminal settings, including -messages written to a response stream. Call `disableAnsi(true)` to turn off -generated ANSI styles and `disableAnsi(false)` to restore automatic detection. -Cursor-based interactions also require a terminal stream. Check -`Command::hasCursorOutput()` before writing cursor controls. Use -`Ansi::cursorUp($lines)` to move up by a relative number of lines. The older -`moveCursorTo($line)` method is deprecated. +use MaplePHP\Prompts\Command; +use MaplePHP\Prompts\Exceptions\PromptException; -```php -$command = new \MaplePHP\Prompts\Command(); -$blocks = new \MaplePHP\Prompts\Themes\Blocks($command); +$command = new Command(); +$command->title('Export report'); -$blocks->table(['Command', 'Description'], [ - ['app list', 'List items'], - ['app add', 'Add an item'], -]); - -$blocks->addSection('Examples', fn ($section) => $section - ->addExample('app add "New item"', 'Add a named item')); +try { + $name = $command->ask('Report name'); + $format = $command->select('Output format', ['text' => 'Plain text', 'json' => 'JSON']); + $command->success("Selected $format for $name."); +} catch (PromptException $exception) { + $command->error($exception->getMessage()); + exit(1); +} ``` -Pass a non-empty list of headings and a list of rows with one cell per heading. -An empty row list prints only the headings. Cells accept scalars and stringable -objects whose text is printable UTF-8 on a single line. Line breaks, tabs, and -cursor controls are rejected. Existing ANSI text styles are retained and take no -space in alignment. Wide CJK characters count as two columns and combining -marks take no extra space. Emoji widths can vary by terminal. - -Section descriptions given as strings are printed literally. For a function or -method callback, use a first-class callable or a callable array. `addExample()` -returns a new builder, as does the deprecated `addExamples()` method. -Use `addCode()` to print PHP with optional syntax highlighting. The source text -is preserved, including its whitespace, and plain output is available without -the tokenizer extension. +Enter a report name, then choose the format. The repository demo adds multi-select, confirmation, a table, and progress output. Run it from the package root with `php examples/command.php`. [Command demo](examples/command.php) -## Progress Bar +## Quickstart with Prompt -The `progress` method of the `Command` class allows displaying a progress bar with customizable sleep intervals to indicate ongoing operations. +Define the steps and validation rules for a workflow such as an installer. Save this as `installer.php` next to your application's `vendor` directory and run `php installer.php`. ```php -$command = new \MaplePHP\Prompts\Command(); -$command->progress(1, 100, function($i, $length) { - return 20; -}); -``` - -## Validation and Error Handling + []` - -2. **length** - - **Description**: Checks if the string length is between a specified start and end length. - - **Usage**: `"length" => [1, 200]` - -3. **email** - - **Description**: Validates email addresses. - - **Usage**: `"email" => []` - -4. **number** - - **Description**: Checks if the value is numeric. - - **Usage**: `"number" => []` - -5. **min** - - **Description**: Checks if the value is greater than or equal to a specified minimum. - - **Usage**: `"min" => [10]` - -6. **max** - - **Description**: Checks if the value is less than or equal to a specified maximum. - - **Usage**: `"max" => [100]` - -7. **url** - - **Description**: Checks if the value is a valid URL (http|https is required). - - **Usage**: `"url" => []` - -8. **phone** - - **Description**: Validates phone numbers. - - **Usage**: `"phone" => []` - -9. **date** - - **Description**: Checks if the value is a valid date with the specified format. - - **Usage**: `"date" => ["Y-m-d"]` - -10. **dateTime** - - **Description**: Checks if the value is a valid date and time with the specified format. - - **Usage**: `"dateTime" => ["Y-m-d H:i"]` - -11. **bool** - - **Description**: Checks if the value is a boolean. - - **Usage**: `"bool" => []` - -12. **oneOf** - - **Description**: Validates if one of the provided conditions is met. - - **Usage**: `"oneOf" => [["length", [1, 200]], "email"]` - -13. **allOf** - - **Description**: Validates if all of the provided conditions are met. - - **Usage**: `"allOf" => [["length", [1, 200]], "email"]` - -14. **float** - - **Description**: Checks if the value is a float. - - **Usage**: `"float" => []` - -15. **int** - - **Description**: Checks if the value is an integer. - - **Usage**: `"int" => []` - -16. **positive** - - **Description**: Checks if the value is a positive number. - - **Usage**: `"positive" => []` - -17. **negative** - - **Description**: Checks if the value is a negative number. - - **Usage**: `"negative" => []` - -18. **validVersion** - - **Description**: Checks if the value is a valid version number. - - **Usage**: `"validVersion" => [true]` - -19. **versionCompare** - - **Description**: Validates and compares if a version is equal/more/equalMore/less... e.g., than withVersion. - - **Usage**: `"versionCompare" => ["1.0.0", ">="]` - -20. **zip** - - **Description**: Validates ZIP codes within a specified length range. - - **Usage**: `"zip" => [5, 9]` - -21. **hex** - - **Description**: Checks if the value is a valid hex color code. - - **Usage**: `"hex" => []` - -22. **age** - - **Description**: Checks if the value represents an age equal to or greater than the specified minimum. - - **Usage**: `"age" => [18]` - -23. **domain** - - **Description**: Checks if the value is a valid domain. - - **Usage**: `"domain" => [true]` - -24. **dns** - - **Description**: Checks if the host/domain has a valid DNS record (A, AAAA, MX). - - **Usage**: `"dns" => []` - -25. **matchDNS** - - **Description**: Matches DNS records by searching for a specific type and value. - - **Usage**: `"matchDNS" => [DNS_A]` - -26. **equal** - - **Description**: Checks if the value is equal to a specified value. - - **Usage**: `"equal" => ["someValue"]` - -27. **notEqual** - - **Description**: Checks if the value is not equal to a specified value. - - **Usage**: `"notEqual" => ["someValue"]` - -28. **string** - - **Description**: Checks if the value is a string. - - **Usage**: `"string" => []` - -29. **equalLength** - - **Description**: Checks if the string length is equal to a specified length. - - **Usage**: `"equalLength" => [10]` - -30. **lossyPassword** - - **Description**: Validates password with allowed characters `[a-zA-Z\d$@$!%*?&]` and a minimum length. - - **Usage**: `"lossyPassword" => [8]` - -31. **strictPassword** - - **Description**: Validates strict password with specific character requirements and a minimum length. - - **Usage**: `"strictPassword" => [8]` - -32. **pregMatch** - - **Description**: Validates if the value matches a given regular expression pattern. - - **Usage**: `"pregMatch" => ["a-zA-Z"]` - -33. **atoZ** - - **Description**: Checks if the value consists of characters between `a-z` or `A-Z`. - - **Usage**: `"atoZ" => []` - -34. **lowerAtoZ** - - **Description**: Checks if the value consists of lowercase characters between `a-z`. - - **Usage**: `"lowerAtoZ" => []` - -35. **upperAtoZ** - - **Description**: Checks if the value consists of uppercase characters between `A-Z`. - - **Usage**: `"upperAtoZ" => []` - -36. **isArray** - - **Description**: Checks if the value is an array. - - **Usage**: `"isArray" => []` - -37. **isObject** - - **Description**: Checks if the value is an object. - - **Usage**: `"isObject" => []` - -38. **boolVal** - - **Description**: Checks if the value is a boolean-like value (e.g., "on", "yes", "1", "true"). - - **Usage**: `"boolVal" => []` - -### Usage Example - -Here is an example of how to use the validation functions in the prompt library: - -```php -$inp->set([ - "firstname" => [ - "type" => "text", - "message" => "First name", - "validate" => [ - "length" => [1, 200], - "required" => [] - ], - "error" => "Required" - ], - "email" => [ - "type" => "text", - "message" => "Email", - "validate" => [ - "length" => [1, 200], - "email" => [] - ] +$installer = (new Prompt())->setTitle('Project installer')->set([ + 'project' => [ + 'message' => 'Project name', + 'validate' => ['length' => [3, 40]], + 'error' => 'Enter a name with 3 to 40 characters.', ], - "age" => [ - "type" => "text", - "message" => "Age", - "validate" => [ - "number" => [], - "min" => [18] - ] - ] + 'install' => ['type' => 'confirm', 'message' => 'Install this project?'], ]); + +$answers = $installer->prompt(); +if ($answers === false) { + exit(1); +} +$installer->getCommand()->success('Installation approved for ' . $answers['project'] . '.'); ``` -## Conclusion +Enter at least three characters for the project name and answer `yes` to confirm. The repository demo adds a nested workflow, list validation, and hidden input. Run it from the package root with `php examples/example.php`. [Prompt demo](examples/example.php) + +## Documentation -PHP Prompts provides a straightforward way to create interactive command-line interfaces in PHP. By defining prompts, validation rules, and error messages, developers can easily gather and validate user input in a CLI environment. \ No newline at end of file +- [Package guide](docs/guide.md) covers direct input, workflow options, stored definitions, and formatted output. +- [Migrating from Prompts 1.x](docs/migration.md) lists method replacements and behavior to check when upgrading. diff --git a/docs/guide.md b/docs/guide.md new file mode 100644 index 0000000..041fc74 --- /dev/null +++ b/docs/guide.md @@ -0,0 +1,229 @@ +# Prompts guide + +The [quickstarts](../README.md) show direct calls with `Command` and a workflow with `Prompt`. The PHP examples below are standalone scripts. Save them next to your project's `vendor` directory and run them with `php`. + +## Command input and output + +A `Command` reads from standard input and writes to standard output by default. Pass a PSR-7 output stream or response as `stream` and a separate PSR-7 stream as `input`. When given a response, `Command` writes to its body. To send prompts to stderr while reading stdin, pass a `MaplePHP\Http\Stream` wrapping `STDERR` as `stream`. `withStream()` returns a copy with a different output stream and keeps the same input. Pass the command to `new Prompt($command)` to use those streams for the full workflow, including nested prompts. + +| Method | Result | +| --- | --- | +| `ask($message)` | A `string`, including an empty line as `''`. Leading and trailing whitespace are preserved. | +| `mask($message)` | A `string` read without echoing the answer. Use it for passwords. | +| `list($message)` | An array of trimmed strings split on commas. Blank entries remain as `''`. | +| `select($message, $items)` | The chosen `int` or `string` key from a non-empty array of choices. | +| `multiSelect($message, $items, $defaults = [])` | A list of unique original choice keys in declaration order. Defaults are original keys. | +| `toggle($message)` | Integer `1` for yes or `0` for no. | +| `confirm($message)` | Boolean `true` for yes or `false` for no. | +| `line($message = '', $break = true)` | Writes a line. Pass `false` for `$break` to omit the newline. Returns `void`. | +| `title()`, `success()`, `status()`, `warning()` | Write styled output and return `void`. | +| `error($message, $break = true)` | Writes an error to the configured output and returns `false`. | + +### Terminals, pipes, and end of input + +- Arrow-key menus require terminal stdin, cursor-capable output, and usable Unix `stty`. Use Up and Down to move and Enter to accept. In a multi-select menu, Space toggles the current choice. +- With a pipe, redirected output, plain terminal settings, or Windows, a single choice uses one-based positions. A multi-select accepts comma-separated positions, a blank line to keep the defaults, or `none` to clear them. Invalid positions retry. The selected values are the original keys, including integer `0`. `inputSelect()` and `inputToggle()` explicitly use line input. Both `confirm()` and the line-based toggle expect `yes` or `no`. +- Masked input uses `stty` on a supported Unix stdin terminal and PowerShell on a native Windows stdin console. For injected input, use a recognized stdin terminal or a genuinely non-echoing source such as a pipe or memory stream. The caller controls whether a custom PSR stream echoes input. Recognized terminals that cannot be masked raise `PromptException`. The package's Windows CI job exercises redirected input. +- Direct reads and `promptLine()` throw `InputExhaustedException` if no answer remains. A final non-empty line without a newline still counts as an answer, and a blank line can apply a default. Raw terminal menus and masked reads report a handled Ctrl+C as `InputInterruptedException`. Both exceptions extend `PromptException`. `prompt()` and `runDefinition()` return `false` for either exception. Other input failures, such as failure to configure masked entry, can still throw `PromptException`. +- `getAnsi()->disableAnsi(true)` disables generated ANSI styling and cursor navigation. Passing `false` restores automatic detection. The detection uses `TERM` and the OS. A redirected stream can still receive text styles when `TERM` indicates ANSI support. Check `hasCursorOutput()` before writing cursor controls or set `TERM=dumb` for plain output. + +## Trusted PHP workflows + +`Prompt::set($rows)` replaces the queue, `add($name, $row)` adds or replaces one row, and `promptLine($row)` asks one question directly without consuming the queue. `setTitle()` and `setDescription()` customize the header. `disableHeaderInfo(true)` hides the header and its keyboard hint. + +Call `prompt()` to process queued rows in declaration order and get answers keyed by row name. Successful rows are removed as the run advances. If a confirmation is declined, EOF occurs, or input is interrupted, the run returns `false` and discards its partial results. A subsequent call on the same `Prompt` resumes at the first unfinished row using the available input and returns answers for the remaining rows. If a nested workflow aborts, its `continue` row stays queued and starts over when resumed. Call `set($rows)` again to repeat the full sequence, or use `runDefinition()` for a data-only workflow that starts fresh on every call. + +### Row options + +| Key | Use | +| --- | --- | +| `type` | One of the types below, with `text` as the default. | +| `message` | The prompt or notice to display. Required except on `continue`. | +| `default` | A replacement for an empty text or masked answer. For `multiselect`, use a list of original choice keys. Defaults on masked input stay hidden. | +| `items` | A choice map for `select` or `multiselect`, or nested rows for `continue`. In trusted PHP a `continue` row also accepts a callable. | +| `validate` | A rule map such as `['length' => [3, 40], 'isEmail' => []]` or a legacy callable in trusted PHP. | +| `validator` | A trusted PHP callable. Return `true` to accept or `false` to retry. Use either `validator` or `validate` on a row. | +| `error` | A string to print on a failed validation attempt, or a trusted PHP callable taking `($rule, $input, $row)` and returning a string. The rule is `null` for callback validation. | +| `confirm` | A message printed after successful validation. On a `confirm` row it prints only after `yes`. | + +| `type` | Value returned in the workflow | +| --- | --- | +| `text` | The typed string or its default. | +| `password`, `mask`, `invisible` | The hidden answer or its default. | +| `list` | An array of trimmed comma-separated strings. | +| `select` | The original choice key. | +| `multiselect` | A list of selected keys in declaration order. A top-level `required` or `isRequired` rule requires at least one selection and accepts a key of `0`. | +| `toggle` | Integer `1` or `0`. | +| `confirm` | Integer `1` for yes. A no aborts the workflow. | +| `continue` | An array of nested answers. A trusted `items` callback can return `false` to skip its nested questions, recording `true` for the row. | +| `message` | Displays text without adding an answer. | + +Text `0` and the integer choice key `0` count as answers. For workflows that handle passwords, read the masked field from the result only where it is needed and omit it from summaries. + +### Nested rows and callbacks + +A `continue` row reuses the parent command and suppresses the nested header. In trusted PHP, an `items` callable receives the preceding accepted value and the current zero-based row index. A nested decline also aborts the parent workflow. + +Save this as `database.php`. Answer `yes`, provide a host, and confirm with `yes` to see the nested host in the summary. + +```php +set([ + 'remote' => ['type' => 'toggle', 'message' => 'Use a remote database?'], + 'database' => [ + 'type' => 'continue', + 'items' => static fn (int $remote, int $index): array|false => $remote === 1 ? [ + 'host' => [ + 'message' => 'Database host', + 'validator' => static fn (string $host): bool => strlen($host) >= 3, + 'error' => 'Enter at least three characters.', + ], + 'connect' => ['type' => 'confirm', 'message' => 'Use this host?'], + ] : false, + ], +]); + +$answers = $prompt->prompt(); +if ($answers === false) { + exit(1); +} +$prompt->getCommand()->line($answers['database']['host'] ?? 'Using the local database.'); +``` + +## Stored workflow definitions + +Use `runDefinition(array $steps)` to replay rows from JSON or another data store. It checks all rows, nested `items`, defaults, and rule arguments before writing a prompt or reading input. On invalid data it throws `InvalidArgumentException`. Each call starts with fresh rows and shares the configured command and header. The trusted queue set with `set()` and `add()` remains independent. + +Store an object keyed by row name. Use scalar values, `null`, and arrays or objects that decode to PHP arrays. `items` on `continue` contains more named rows. `items` on selections is a non-empty map of keys to string labels. A text or masked `default` must be scalar or `null`. A multiselect `default` must be a list of existing choice keys with matching types. Use strings for `message`, `error`, and `confirm`. `validate` accepts only rule maps from the allowlist, and `message` rows only display text. PHP callables, arbitrary validation methods, DNS or file rules, and unknown fields are rejected. [Stored rule reference](#stored-rule-reference) + +Save the definition as `setup.json`. + +```json +{ + "contact": { + "message": "Email address or five-digit PIN", + "validate": { + "oneOf": [{ + "isEmail": [], + "allOf": [{"isMatchingPattern": ["0-9"], "length": [5, 5]}] + }] + }, + "error": "Enter an email address or a five-digit PIN." + }, + "details": { + "type": "continue", + "items": { + "date": {"message": "Start date", "validate": {"isDate": ["d/m/Y"]}, "error": "Use DD/MM/YYYY."}, + "confirm": {"type": "confirm", "message": "Save these settings?"} + } + } +} +``` + +Save this as `stored.php` beside `setup.json` and run `php stored.php`. Try `12345`, `05/03/2027`, then `yes`. + +```php +setTitle('Setup'); +$answers = $prompt->runDefinition($definition); +if ($answers === false) { + exit(1); +} +$prompt->getCommand()->success('Setup approved for ' . $answers['details']['date'] . '.'); +``` + +To run that definition again, pass it to `runDefinition()` again with fresh answers available on the input stream. The definition contains workflow configuration. The returned values are available to application code for persistence. + +### Validation maps + +A validation map keys each rule by name and provides an array of arguments in parameter order. Use `[]` for rules with no arguments. Top-level rules all need to pass. `oneOf` and `allOf` take one nested rule map, so the map must appear inside the argument array, as in `['oneOf' => [['isEmail' => [], 'isUrl' => []]]]`. `oneOf` passes if any nested rule passes and `allOf` passes if every nested rule passes. An empty `oneOf` fails and an empty `allOf` passes. + +For array answers such as a comma-separated list or multi-select, rules and callable validators run on each item or choice key. The top-level multiselect required rule checks the selection as a whole. Trusted rule maps pass each value as a string to MaplePHP Validate. Stored rule maps check the typed value, so a strict comparison to `0` matches an integer key, while a comparison to `'0'` matches text input. In trusted PHP, a callable in `validate` uses the legacy polarity of `true` for retry and `false` for accept. Both callable forms must return a boolean. + +### Stored rule reference + +The names in either column below are accepted in a stored definition, including inside `oneOf` and `allOf`. + +| Canonical rules | Aliases | Positional arguments | +| --- | --- | --- | +| `isRequired`, `isEmail`, `isNumber`, `isUrl`, `isPhone` | `required`, `email`, `number`, `url`, `phone` | `[]` | +| `isBool`, `isBoolVal`, `isFloat`, `isInt`, `isPositive`, `isNegative` | `bool`, `boolVal`, `float`, `int`, `positive`, `negative` | `[]` | +| `isTrue`, `isFalse`, `isTruthy`, `isFalsy`, `isArray`, `isObject` | | `[]` | +| `isHexColor`, `isString`, `isAlpha`, `isLowerAlpha`, `isUpperAlpha` | `hex`, `string`, `atoZ`, `lowerAtoZ`, `upperAtoZ` | `[]` | +| `length`, `isZip` | `zip` for `isZip` | `[minimum]` or `[minimum, maximum]`. Non-negative integers, with an optional `null` maximum and any numeric maximum at least the minimum. | +| `min`, `max` | | `[limit]` as a finite number. | +| `isAge`, `isLengthEqualTo` | `age`, `equalLength` | `[minimumAge]` or `[length]` respectively, as a non-negative integer. | +| `isLossyPassword`, `isStrictPassword` | `lossyPassword`, `strictPassword` | `[]` or `[length]` as an integer from 0 to 65535. | +| `isDate`, `isDateWithTime` | `date`, `dateTime` | `[]` or `[format]` as a non-empty date format string. The defaults are `Y-m-d` and `Y-m-d H:i:s`. | +| `isValidVersion`, `isDomain` | `validVersion`, `domain` | `[]` or `[strict]` as a boolean. Strict mode is off for versions and on for domains by default. Domain validation checks syntax. | +| `versionCompare` | | `[version]` or `[version, operator]`, both strings. Operators are `!=`, `<`, `<=`, `<>`, `=`, `==`, `>`, `>=`, `eq`, `ge`, `gt`, `le`, `lt`, `ne`. The default is `==`. | +| `isEqualTo`, `isNotEqualTo` | `equal`, `notEqual` | `[expected]` as a scalar or `null`, compared strictly. | +| `isMatchingPattern` | `pregMatch` | `[range]`, a character-class contents string such as `'A-Z0-9'`. | +| `oneOf`, `allOf` | | `[ruleMap]`, recursively subject to the same rules and argument checks. | + +For trusted workflows, use `isDate` with an explicit format for dates and date-times, and `isValidVersion` for versions. These canonical methods are available at the package's Validate 2.0.0 floor, including when nested in a trusted `oneOf` or `allOf` rule. + +## Formatted output + +`Command::getAnsi()` styles strings, for example `style(['bold', 'blue'], $text)`. `Blocks` writes help text through a `Command`. A section can use a literal description or a callback. Return the builder from a section callback to display its options, list entries, or examples. `addOption()`, `addList()`, and `addExample()` return a new builder, so chain the calls or reassign the result. `addCode()` prints the source with PHP token styles when ANSI and the tokenizer are available. + +`table($headers, $rows)` takes a non-empty list of column headings and a list of rows with one cell per heading. Cells are scalars or stringable objects with single-line, printable UTF-8 text. Empty rows print only the headings. ANSI text styles are preserved without taking up columns. Wide characters and combining marks are accounted for, and emoji widths can vary by terminal. + +`progress($expectedRows, $maxLength, $sleep)` writes `$maxLength` cells and a newline when both dimensions are positive. Either dimension can be zero to write a blank line. Negative dimensions throw `InvalidArgumentException`. The optional delay is in milliseconds. A delay callback runs once per cell and receives `($i, $length)` using the original scale. For scale `min($expectedRows, $maxLength) / max($expectedRows, $maxLength)`, `$i` is the zero-based frame times the scale and `$length` is `($maxLength - 0.5)` times the scale. The callback can return a positive integer delay or `0` to continue immediately. + +```php +addHeadline('Export help'); +$blocks->addSection('Usage', static fn (Blocks $section): Blocks => $section + ->addOption('--format', 'Choose an output format') + ->addExample('report --format=json', 'Export a JSON report')); +$blocks->table(['Format', 'Description'], [['text', 'Plain text'], ['json', 'JSON']]); +$blocks->addCode('$command->status("Preparing report");'); +$command->progress(3, 12, static fn ($i, $length): int => 20); +``` + +### Custom navigation + +Use `Navigation::navigate()` when you need to render a menu yourself. Its callback receives the zero-based highlighted index and the ordered list of labels. For cursor navigation, print exactly one terminal row per item. Keep labels short enough to avoid wrapping because the renderer moves up by a relative row count before redrawing. Numbered fallback calls the renderer before displaying the numbered choices and again if the chosen index changes. After acceptance, `getValue()` returns the original choice key and `getItem()` returns its label. Use `setAcceptKey()` to change the terminal acceptance key from Enter. + +```php +setHelperText(Navigation::HELPER_TEXT); +$navigation->navigate('Choose a format', ['text' => 'Plain text', 'json' => 'JSON'], + static function (int $current, array $labels) use ($command): void { + foreach ($labels as $index => $label) { + $marker = $current === $index ? '>' : ' '; + $command->line("$marker $label"); + } + } +); +$command->success('Selected ' . $navigation->getItem()); +``` diff --git a/docs/migration.md b/docs/migration.md new file mode 100644 index 0000000..20cc8a6 --- /dev/null +++ b/docs/migration.md @@ -0,0 +1,52 @@ +# Migrating from Prompts 1.x + +The existing `Command` entry points remain available. Replace legacy names when updating a script, and check any code that uses their return values. + +| Legacy call | Current call | Return behavior | +| --- | --- | --- | +| `Command::message($message, true)` | `Command::ask($message)` | Both return a string. `readline()` remains available and backs `ask()`. | +| `Command::message($message)` or `message($message, false)` | `Command::line($message)` | Legacy returns `false`. `line()` returns `void`. | +| `Command::approve($message, $break)` | `Command::success($message, $break)` | Legacy returns `false`. `success()` returns `void`. | +| `Command::statusMsg($message, $break)` | `Command::status($message, $break)` | Legacy returns `false`. `status()` returns `void`. | +| `Navigation::navigation($message, $items, $call)` | `Navigation::navigate($message, $items, $call)` | Both return `void`. Read the selection with `getValue()` or `getItem()`. | +| `Blocks::addExamples($example, $description)` | `Blocks::addExample($example, $description)` | Both return a new `Blocks` builder. Keep the returned builder or chain the call. | +| `Ansi::moveCursorTo($line)` | `Ansi::cursorUp($lines)` | Both return a relative upward cursor sequence as a string. Check `Command::hasCursorOutput()` before writing it. | + +`Command::error()` still returns `false`. Use `warning()` for yellow output. + +## Validators and row definitions + +Keep callable `validate` entries in trusted PHP if they already return `true` to reject an answer. When moving to `validator`, invert that condition to make `true` accept the value. For example, a legacy `validate` callback returning `strlen($value) < 3` becomes a `validator` callback returning `strlen($value) >= 3`. Use one validation field per row. Validation rule maps continue to use `validate`, including `oneOf` and `allOf` with one nested map argument each. An unknown prompt type now throws `InvalidArgumentException`. + +Use `isDate` with an explicit format and `isValidVersion` when calling Validate 2.0.0–2.0.2 directly or from a trusted composite rule. Prompts handles the legacy `date`, `dateTime`, `isDateWithTime`, and `validVersion` forms when used as top-level rules and in stored maps. For example, use `['isDate' => ['Y-m-d H:i']]` for a date and time without seconds, or `['isValidVersion' => [true]]` for strict version validation. + +Use `set()` and `prompt()` for trusted PHP workflows that depend on custom validators, callable errors, or callable nested `items`. Use `runDefinition()` for replayable data from storage, with static nested `continue` rows and the supported rule maps. Convert callback-based rules to allowlisted rules where possible and keep application-specific checks in trusted code. The [package guide](guide.md#stored-workflow-definitions) includes a JSON example and the complete argument reference. + +## Streams and workflow outcomes + +`new Command($stream, $input)` uses `$stream` for output and `$input` for input. `withStream()` changes output on the returned command. Pass that command to `Prompt` to use those endpoints for nested prompts as well. + +Check for `false` before using a workflow result. A declined confirmation, handled interrupt, or EOF returns `false` from `prompt()` or `runDefinition()`. A direct read raises the corresponding input exception. An empty line can still select a default. `prompt()` retains unfinished rows for a later call and returns only that call's answers. Reload the rows with `set()` to repeat the sequence. `runDefinition()` begins at the first row each time. + +Selections can now use numbered input when cursor navigation is unavailable. In automated input, supply one-based positions using digits only and keep reading original choice keys from the result. A value such as `1x` retries the question. For a custom `Navigation` renderer, print one terminal row per item so relative cursor movement redraws the right lines. A recognized live terminal that cannot disable echo raises `PromptException` for masked input. + +## Section callbacks + +`Blocks::addSection()` prints string descriptions literally, including strings that name functions or static methods. If a function name came from trusted PHP, wrap it with `Closure::fromCallable()` to invoke it as a section callback. Save and run this example from a project with the package installed. + +```php +addExample('report --format=json', 'Write a JSON report'); +} + +$blocks = new Blocks(new Command()); +$blocks->addSection('Examples', Closure::fromCallable('reportHelp')); +``` diff --git a/examples/command.php b/examples/command.php new file mode 100644 index 0000000..5b33952 --- /dev/null +++ b/examples/command.php @@ -0,0 +1,40 @@ +title('Export report'); + +try { + $name = $command->ask('Report name'); + $format = $command->select('Output format', ['text' => 'Plain text', 'json' => 'JSON']); + $sections = $command->multiSelect('Report sections', ['summary' => 'Summary', 'details' => 'Details'], ['summary']); + $command->line(); + + $blocks = new Blocks($command); + $blocks->addHeadline('Export preview'); + $blocks->table(['Setting', 'Value'], [ + ['Report', $name], + ['Format', $format], + ['Sections', implode(', ', $sections)], + ]); + + if (!$command->confirm('Approve this export?')) { + $command->warning('Export cancelled.'); + exit(1); + } + + $command->line(); + $command->status('Preparing report'); + $command->progress(3, 12, 20); + $command->success('Export approved.'); +} catch (PromptException $exception) { + $command->error($exception->getMessage()); + exit(1); +} diff --git a/examples/example.php b/examples/example.php index 13adcc2..4a79e80 100755 --- a/examples/example.php +++ b/examples/example.php @@ -1,131 +1,91 @@ #!/usr/bin/env php setTitle("Your prompt title"); -$inp->setDescription("Your prompt description, lorem ipsum dolor"); +$installer = new Prompt(); +$command = $installer->getCommand(); -$inp->set([ - "firstname" => [ - "type" => "text", - "message" => "First name", - "validate" => [ - "length" => [1,200] +$installer->setTitle('Project installer') + ->setDescription('Collect installation settings and review your choices.') + ->set([ + 'firstName' => [ + 'message' => 'First name', + 'validate' => ['length' => [1, 200]], + 'error' => 'Enter a first name.', ], - "error" => "Required" - ], - "lastname" => [ - "type" => "text", - "message" => "Last name", - "default" => "Doe", - "error" => "The last name must be more then 2 characters!", - "validate" => function($input) { - return (strlen($input) < 3); - } - ], - "email" => [ - "type" => "text", - "message" => "email", - "validate" => [ - "length" => [1,200], - "email" => [], - ] - ], - "ssl" => [ - "type" => "toggle", - "message" => "Do you want SSL", - ], - "url" => [ - "type" => "continue", - "items" => function($value) { - return [ - "url" => [ - "type" => "text", - "message" => ((int)$value === 1) ? "Secure URL" : "Insecure URL" - ] - ]; - } - ], - "message" => [ - "type" => "message", // Will be excluded form the end result array! - "message" => "Lorem ipsum dolor", - ], - "select" => [ - "type" => "select", - "message" => "Select item bellow", - "items" => [ - "Lorem 1", - "Lorem 2", - "Lorem 3" + 'lastName' => [ + 'message' => 'Last name', + 'default' => 'Doe', + 'validator' => static fn (string $value): bool => strlen($value) >= 3, + 'error' => 'Enter at least three characters.', ], - ], - "keyword" => [ - "type" => "list", - "message" => "Keywords", - "validate" => [ - "length" => [1,200], - "number" => [] + 'email' => [ + 'message' => 'Email', + 'validate' => ['isEmail' => []], + 'error' => 'Enter a valid email address.', ], - "error" => function($errorType, $input, $row) { - if($errorType === "length") { - return "Is required"; - } - return "Must be a number"; - - } - ], - "password" => [ - "type" => "password", - "message" => "Password", - "validate" => [ - "length" => [1,200] - ] - ], - "confirm" => [ - "type" => "confirm", - "message" => "Do you wish to continue?", - "confirm" => "Continuing..." - ] -]); + 'ssl' => ['type' => 'toggle', 'message' => 'Use SSL?'], + 'site' => [ + 'type' => 'continue', + 'items' => static fn (int $ssl): array => [ + 'url' => [ + 'message' => $ssl === 1 ? 'Secure URL' : 'Insecure URL', + 'validate' => ['isUrl' => []], + 'error' => 'Enter a full URL.', + ], + ], + ], + 'notice' => ['type' => 'message', 'message' => 'Choose the settings for your first installation.'], + 'environment' => [ + 'type' => 'select', + 'message' => 'Environment', + 'items' => ['local' => 'Local', 'staging' => 'Staging', 'production' => 'Production'], + ], + 'features' => [ + 'type' => 'multiselect', + 'message' => 'Optional features', + 'items' => ['reports' => 'Reports', 'alerts' => 'Alerts'], + 'default' => ['reports'], + ], + 'groupIds' => [ + 'type' => 'list', + 'message' => 'Group IDs', + 'validate' => ['isRequired' => [], 'isNumber' => []], + 'error' => static fn (?string $rule): string => $rule === 'isRequired' + ? 'Enter at least one group ID.' + : 'Every group ID must be a number.', + ], + 'password' => [ + 'type' => 'password', + 'message' => 'Administrator password', + 'validate' => ['length' => [8, 200]], + 'error' => 'Enter a password with 8 to 200 characters.', + ], + 'confirm' => ['type' => 'confirm', 'message' => 'Approve these settings?', 'confirm' => 'Settings accepted'], + ]); try { - $prompt = $inp->prompt(); - if($prompt) $command->progress(1, 100, function($i, $length) { - return 20; - }); - print_r($prompt); - -} catch (\MaplePHP\Prompts\Exceptions\PromptException $e) { - $command->error($e->getMessage()); + $answers = $installer->prompt(); + if ($answers === false) { + $command->warning('Installation cancelled.'); + exit(1); + } + + $command->progress(4, 12, 20); + $command->success(sprintf( + 'Installation approved for %s %s at %s (%s).', + $answers['firstName'], + $answers['lastName'], + $answers['site']['url'], + $answers['environment'] + )); +} catch (PromptException $exception) { + $command->error($exception->getMessage()); + exit(1); } - - - - From 4d62ff63935f13e5be40bfe4470c23a3353e5b7a Mon Sep 17 00:00:00 2001 From: Daniel Ronkainen Date: Mon, 30 Nov 2026 19:59:45 +0100 Subject: [PATCH 08/15] feat: compose ANSI text styles --- src/Themes/Ansi.php | 49 +++++++++++++++++++- tests/unitary-themes.php | 96 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 144 insertions(+), 1 deletion(-) diff --git a/src/Themes/Ansi.php b/src/Themes/Ansi.php index e62eddb..b4c56a7 100755 --- a/src/Themes/Ansi.php +++ b/src/Themes/Ansi.php @@ -70,7 +70,10 @@ public function disableAnsi(bool $disableAnsi): self public function ansiStyle(int $ansiNum, string $message): string { if ($this->isSupported()) { - return "\033[{$ansiNum}m$message\033[0m"; + $start = "\033[{$ansiNum}m"; + // Resume the enclosing style after internal resets. Keep trailing resets contiguous. + $message = preg_replace('/\x1b\[0?m(?!\x1b\[0?m|\z)/', '$0' . $start, $message) ?? $message; + return $start . $message . "\033[0m"; } return $message; } @@ -131,6 +134,17 @@ public function bold(string $message): string return $this->ansiStyle(1, $message); } + /** + * Dim input + * + * @param string $message + * @return string + */ + public function dim(string $message): string + { + return $this->ansiStyle(2, $message); + } + /** * Italic input * @@ -142,6 +156,39 @@ public function italic(string $message): string return $this->ansiStyle(3, $message); } + /** + * Underline input + * + * @param string $message + * @return string + */ + public function underline(string $message): string + { + return $this->ansiStyle(4, $message); + } + + /** + * Reverse input foreground and background colors + * + * @param string $message + * @return string + */ + public function reverse(string $message): string + { + return $this->ansiStyle(7, $message); + } + + /** + * Strike through input + * + * @param string $message + * @return string + */ + public function strikethrough(string $message): string + { + return $this->ansiStyle(9, $message); + } + /** * Black input text color * diff --git a/tests/unitary-themes.php b/tests/unitary-themes.php index 9e282ca..f513cd2 100644 --- a/tests/unitary-themes.php +++ b/tests/unitary-themes.php @@ -16,6 +16,102 @@ function promptsThemeWithoutSgr(string $text): string return preg_replace('/\x1b\[[0-9;:]*m/', '', $text); } +function promptsThemeStyledSegments(string $text): array +{ + $segments = []; + $styles = []; + foreach (preg_split('/(\x1b\[[0-9]*m)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) as $part) { + if (preg_match('/^\x1b\[([0-9]*)m$/D', $part, $sgr) === 1) { + $code = (int)$sgr[1]; + if ($code === 0) { + $styles = []; + } elseif ($code >= 30 && $code <= 37) { + $styles['foreground'] = $code; + } elseif ($code >= 40 && $code <= 47) { + $styles['background'] = $code; + } else { + $styles[$code] = $code; + } + } else { + $active = array_values($styles); + sort($active); + $segments[] = [$part, $active]; + } + } + return $segments; +} + +group('Ansi exposes text attributes through its helpers and dispatcher', static function (TestCase $case) { + $ansi = new Ansi(); + foreach (['dim' => 2, 'underline' => 4, 'reverse' => 7, 'strikethrough' => 9] as $style => $code) { + $expected = $ansi->isSupported() ? "\033[{$code}mText\033[0m" : 'Text'; + $case->expect($ansi->{$style}('Text') === $expected)->isTrue()->validate($style); + $case->expect($ansi->style($style, 'Text') === $expected)->isTrue()->validate($style); + } + + $ansi->disableAnsi(true); + $suppliedStyle = "\033[3mExisting\033[0m"; + $case->expect($ansi->style(['dim', 'underline', 'reverse', 'strikethrough'], $suppliedStyle) === $suppliedStyle) + ->isTrue()->validate(); + $case->expect($ansi->style(['greenBg', 'underline'], $ansi->dim('Text')) === '[Text]')->isTrue()->validate(); +}); + +group('Ansi restores enclosing attributes after adjacent and nested spans', static function (TestCase $case) { + $term = getenv('TERM'); + try { + putenv('TERM=xterm-256color'); + $ansi = new Ansi(); + $adjacent = $ansi->style( + ['blueBg', 'dim'], + 'a' . $ansi->green('b') . $ansi->style(['underline', 'strikethrough'], 'c') . 'd' + ) . 'e'; + if (!$ansi->isSupported()) { + $case->expect($adjacent === '[abcd]e')->isTrue()->validate(); + return; + } + + $case->expect(promptsThemeStyledSegments($adjacent) === [ + ['a', [2, 44]], ['b', [2, 32, 44]], ['c', [2, 4, 9, 44]], ['d', [2, 44]], ['e', []] + ])->isTrue()->validate($adjacent); + + $nested = $ansi->red('a' . $ansi->green('b' . $ansi->blue('c') . 'd') . 'e') . 'f'; + $case->expect(promptsThemeStyledSegments($nested) === [ + ['a', [31]], ['b', [32]], ['c', [34]], ['d', [32]], ['e', [31]], ['f', []] + ])->isTrue()->validate($nested); + + $defaultReset = $ansi->reverse("a\033[4mb\033[mc") . 'd'; + $case->expect(promptsThemeStyledSegments($defaultReset) === [ + ['a', [7]], ['b', [4, 7]], ['c', [7]], ['d', []] + ])->isTrue()->validate($defaultReset); + + $case->expect($ansi->strikethrough($ansi->reverse($ansi->dim('Text'))) === + "\033[9m\033[7m\033[2mText\033[0m\033[0m\033[0m")->isTrue()->validate(); + } finally { + putenv($term === false ? 'TERM' : "TERM=$term"); + } +}); + +group('Ansi dispatches to named styles and existing subclass hooks', static function (TestCase $case) { + $ansi = new class extends Ansi { + public function ansiStyle(int $ansiNum, string $message): string + { + return "style($ansiNum,$message)"; + } + + public function underline(string $message): string + { + return "underline($message)"; + } + + public function bg(int $int, string $message): string + { + return "background($int,$message)"; + } + }; + $actual = $ansi->style(['strikethrough', 'blueBg', 'underline', 'reverse', 'dim'], 'Text'); + $case->expect($actual === 'style(2,style(7,underline(background(44,style(9,Text)))))')->isTrue()->validate(); +}); + group('Ansi disabling is reversible without treating response streams as terminals', static function (TestCase $case) { $term = getenv('TERM'); try { From 73e65ba73737f8357c009e093a151f7e5b163c77 Mon Sep 17 00:00:00 2001 From: Daniel Ronkainen Date: Mon, 30 Nov 2026 20:03:03 +0100 Subject: [PATCH 09/15] feat: add direct validated input --- src/Command.php | 19 ++++++++ src/InputValidator.php | 30 ++++++++++++ src/PromptDefinition.php | 4 +- tests/unitary-definitions.php | 87 +++++++++++++++++++++++++++++++++++ 4 files changed, 138 insertions(+), 2 deletions(-) create mode 100644 src/InputValidator.php diff --git a/src/Command.php b/src/Command.php index 346173f..b1010be 100755 --- a/src/Command.php +++ b/src/Command.php @@ -212,6 +212,25 @@ public function ask(string $message): string return $this->readline($message); } + /** + * Ask until a checked rule map or a trusted callable accepts the input. + * A callable receives the answer as a string and returns true to accept or false to retry. + * + * @throws InvalidArgumentException For an invalid rule map or a callable returning a non-boolean. + * @throws InputExhaustedException If input ends before an answer is accepted. + */ + public function askValidated(string $message, array|callable $validator, string $error = 'Please try again.'): string + { + $validate = InputValidator::prepare($validator); + while (true) { + $answer = $this->ask($message); + if ($validate($answer)) { + return $answer; + } + $this->error($error); + } + } + /** * Write a line of output. */ diff --git a/src/InputValidator.php b/src/InputValidator.php new file mode 100644 index 0000000..8758e61 --- /dev/null +++ b/src/InputValidator.php @@ -0,0 +1,30 @@ + PromptDefinition::validateInput($rules, $input); + } +} diff --git a/src/PromptDefinition.php b/src/PromptDefinition.php index 97058ee..747bc7b 100644 --- a/src/PromptDefinition.php +++ b/src/PromptDefinition.php @@ -148,7 +148,7 @@ private static function checkItems(string $type, array $types, mixed $items, str } /** @return array> */ - private static function checkRules(mixed $rules, string $path, int $depth): array + public static function checkRules(mixed $rules, string $path, int $depth): array { self::checkDepth($depth, $path); if (!is_array($rules)) { @@ -216,7 +216,7 @@ private static function checkDepth(int $depth, string $path): void } } - public static function validateInput(array $rules, mixed $input, ?string &$error): bool + public static function validateInput(array $rules, mixed $input, ?string &$error = null): bool { /** @var array> $rules Checked rule names and arguments from checkRules(). */ foreach (is_array($input) ? $input : [$input] as $value) { diff --git a/tests/unitary-definitions.php b/tests/unitary-definitions.php index 379da54..068c60e 100644 --- a/tests/unitary-definitions.php +++ b/tests/unitary-definitions.php @@ -4,6 +4,7 @@ use MaplePHP\Http\Stream; use MaplePHP\Prompts\Command; +use MaplePHP\Prompts\Exceptions\InputExhaustedException; use MaplePHP\Prompts\Prompt; use MaplePHP\Unitary\TestCase; @@ -205,3 +206,89 @@ public function readline(string $message): string $case->expect((string)$output === 'First: ')->isTrue()->validate(); $case->expect($prompt->prompt() === ['queued' => 'queued'])->isTrue()->validate(); }); + +group('Direct validation accepts checked composite rules and returns the original answer', static function (TestCase $case) { + [$prompt, , $output] = promptDefinitionSession("invalid\n0\n30/11/2026 17:30\n\n"); + $command = $prompt->getCommand(); + $rules = ['oneOf' => [['dateTime' => ['d/m/Y H:i'], 'allOf' => [['int' => [], 'isFalsy' => []]]]]]; + + $case->expect($command->askValidated(message: 'Value', validator: $rules, error: 'Use zero or a date') === '0') + ->isTrue()->validate(); + $case->expect($command->askValidated('Date', $rules) === '30/11/2026 17:30')->isTrue()->validate(); + $case->expect($command->askValidated('Blank', []) === '')->isTrue()->validate(); + $case->expect((string)$output)->isEqualTo("Value: Use zero or a date\nValue: Date: Blank: ")->validate(); +}); + +group('Direct validation preflights every rule and argument before input or output', static function (TestCase $case) { + [$prompt, $input, $output] = promptDefinitionSession("unused\n"); + $command = $prompt->getCommand(); + $invalidRules = [ + ['getValue' => []], + ['length' => ['min' => 1]], + ['oneOf' => [['required' => [], 'allOf' => [['date' => [3]]]]]], + ['allOf' => [['strlen', 'trim']]], + ]; + foreach ($invalidRules as $index => $rules) { + $case->expect(fn () => $command->askValidated('Unused', $rules)) + ->isThrowable(InvalidArgumentException::class)->validate("invalid rule map $index"); + $case->expect((string)$output === '' && $input->tell() === 0)->isTrue()->validate("no I/O for $index"); + } +}); + +group('Direct validation uses command hooks and keeps callable array input unchanged', static function (TestCase $case) { + $input = new Stream('php://memory'); + $input->write("bad\n padded\0answer \t\r\n0\n"); + $input->rewind(); + $output = new Stream('php://memory'); + $command = new class (stream: $output, input: $input) extends Command { + public string $expected = ''; + + public function ask(string $message): string + { + $this->expected = 'changed during the prompt'; + return parent::ask("Ask $message"); + } + + public function error(string $message, bool $break = true): string|false + { + $this->line("Error $message", $break); + return false; + } + }; + $validator = new class () { + public array $seen = []; + + public function accept(string &$answer): bool + { + $this->seen[] = $answer; + $valid = $answer === " padded\0answer \t"; + $answer = 'overwritten'; + return $valid; + } + }; + $case->expect($command->askValidated('Value', [$validator, 'accept']) === " padded\0answer \t") + ->isTrue()->validate(); + $case->expect($validator->seen === ['bad', " padded\0answer \t"])->isTrue()->validate(); + $command->expected = '0'; + $case->expect($command->askValidated('Snapshot', ['equal' => [&$command->expected]]) === '0') + ->isTrue()->validate(); + $case->expect((string)$output)->isEqualTo("Ask Value: Error Please try again.\nAsk Value: Ask Snapshot: ") + ->validate(); +}); + +group('Direct validation retries iteratively and propagates EOF and validator exceptions', static function (TestCase $case) { + [$prompt, , $output] = promptDefinitionSession("0\n0\n0\n" . str_repeat("no\n", 10000)); + $command = $prompt->getCommand(); + + $case->expect(fn () => $command->askValidated('Return type', 'strlen')) + ->isThrowable(InvalidArgumentException::class)->validate(); + $case->expect(fn () => $command->askValidated('Parameter type', static fn (int $value): bool => $value === 0)) + ->isThrowable(TypeError::class)->validate(); + $case->expect(fn () => $command->askValidated('Callback', static fn () => throw new LogicException('Failed'))) + ->isThrowable(LogicException::class)->validate(); + $case->expect((string)$output)->isEqualTo('Return type: Parameter type: Callback: ')->validate(); + $case->expect(fn () => $command->askValidated('Retry', static fn (string $value): bool => $value === 'yes')) + ->isThrowable(InputExhaustedException::class)->validate(); + $case->expect(substr_count((string)$output, "Retry: Please try again.\n") === 10000)->isTrue()->validate(); + $case->expect(str_ends_with((string)$output, 'Retry: '))->isTrue()->validate(); +}); From 33cb67f475b9ec341a5a21df8d35c30a3353e454 Mon Sep 17 00:00:00 2001 From: Daniel Ronkainen Date: Mon, 30 Nov 2026 20:12:06 +0100 Subject: [PATCH 10/15] feat: add searchable selection --- src/Command.php | 32 ++++++ src/Navigation.php | 102 +++++++++++++------ src/NavigationInput.php | 143 ++++++++++++++++++++++++++ src/Prompt.php | 8 +- src/PromptDefinition.php | 5 +- src/SearchSelection.php | 121 ++++++++++++++++++++++ src/SttyWrapper.php | 17 ++++ tests/unitary-search.php | 211 +++++++++++++++++++++++++++++++++++++++ 8 files changed, 607 insertions(+), 32 deletions(-) create mode 100644 src/NavigationInput.php create mode 100644 src/SearchSelection.php create mode 100644 tests/unitary-search.php diff --git a/src/Command.php b/src/Command.php index b1010be..a08f7e0 100755 --- a/src/Command.php +++ b/src/Command.php @@ -367,6 +367,38 @@ public function select(string $message, array $items): int|string return $this->inputSelect($message, $items); } + /** + * Filter choices by a case-insensitive substring and return the original choice key. + * + * Type to filter on a terminal. Other streams read a filter line, then a choice number. + * + * @param array $items Printable single-line UTF-8 labels. + * @throws InvalidArgumentException If the choices are empty or a label is invalid. + */ + public function selectWithSearch(string $message, array $items): int|string + { + $items = SearchSelection::checkItems($items); + if ($this->supportsNavigation()) { + [$rows, $columns] = $this->getStty()->terminalSize(); + if ($rows >= 3 && $columns >= 6) { + return (new Navigation($this))->navigateSearch( + $message, + $items, + $rows, + $columns, + fn (int $index, array $labels) => $this->showMenu($index, $labels) + ); + } + } + while (true) { + $matches = SearchSelection::filter($items, $this->ask("$message (filter, or leave blank for all)")); + if ($matches !== []) { + return $this->inputSelect($message, $matches); + } + $this->line('No matches.'); + } + } + /** * Select zero or more items. The original keys are returned in declaration order. * diff --git a/src/Navigation.php b/src/Navigation.php index d26746d..057ea2b 100755 --- a/src/Navigation.php +++ b/src/Navigation.php @@ -4,8 +4,6 @@ use Exception; use InvalidArgumentException; -use MaplePHP\Prompts\Exceptions\InputExhaustedException; -use MaplePHP\Prompts\Exceptions\InputInterruptedException; use MaplePHP\Prompts\Exceptions\PromptException; /** @@ -19,8 +17,10 @@ class Navigation private const ARROW_UP = ["\033[A", "\033OA"]; private const ARROW_DOWN = ["\033[B", "\033OB"]; + private const SEARCH_ROWS = 8; private Command $command; + private NavigationInput $input; private int $index = 0; /** @var list */ private array $items = []; @@ -37,6 +37,7 @@ class Navigation public function __construct(Command $command) { $this->command = $command; + $this->input = new NavigationInput($command); $this->setAcceptKey($this->command->getAnsi()->keyEnter()); } @@ -107,7 +108,7 @@ public function navigation(string $message, array $items, callable $call): void return; } - $this->withNavigationMode(function () use ($message, $call): void { + $this->input->withMode(function () use ($message, $call): void { $render = function () use ($call): void { $call($this->index, $this->items); $this->streamHelperText(); @@ -118,6 +119,73 @@ public function navigation(string $message, array $items, callable $call): void }); } + /** + * @internal Use Command::selectWithSearch() to select a filtered item. + * @param non-empty-array $items + * @param callable(int, list): void $renderMenu + */ + public function navigateSearch( + string $message, + array $items, + int $rows, + int $columns, + callable $renderMenu + ): int|string { + $window = min(self::SEARCH_ROWS, $rows - 2); + $width = $columns - 1; + return $this->input->withMode(function () use ($message, $items, $renderMenu, $window, $width): int|string { + $this->command->title($message); + $this->command->line('Type to filter. Use arrows to move and Enter to select.'); + $query = ''; + $matches = $items; + $index = $offset = $height = 0; + while (true) { + $this->clearLines($height); + $this->command->line(SearchSelection::displayQuery($query, $width)); + $labels = array_values(array_slice($matches, $offset, $window)); + if ($labels === []) { + $this->command->line(SearchSelection::clip('No matches.', $width)); + } else { + $renderMenu($index - $offset, array_map( + static fn (string $label): string => SearchSelection::clip($label, $width - 5), + $labels + )); + } + $height = 1 + max(1, count($labels)); + + do { + $key = $this->input->readSearchKey(); + // A terminal or a paste can deliver CRLF in separate reads. + if ($key === "\r" && $this->command->inputIsReady(50000)) { + $this->command->finishInputEnter(); + } + if (($key === "\r" || $key === "\n") && $matches !== []) { + return array_keys($matches)[$index]; + } + $next = match (true) { + in_array($key, self::ARROW_UP, true) => max(0, $index - 1), + in_array($key, self::ARROW_DOWN, true) => max(0, min(count($matches) - 1, $index + 1)), + default => $index, + }; + $filter = match (true) { + $key === "\x08" || $key === "\x7f" => preg_replace('/.\z/u', '', $query) ?? $query, + $key !== '' && ord($key[0]) >= 0x20 => $query . $key, + default => $query, + }; + } while ($next === $index && $filter === $query); + + if ($filter !== $query) { + $query = $filter; + $matches = SearchSelection::filter($items, $query); + $index = $offset = 0; + } else { + $index = $next; + $offset = min($index, max($offset, $index - $window + 1)); + } + } + }, '-istrip'); + } + /** * @internal Use Command::multiSelect() to select several items. * @param array $defaults @@ -191,22 +259,13 @@ private function setItems(array $items): void $this->values = array_keys($items); } - private function withNavigationMode(callable $call): void - { - // Read Ctrl+C as a byte so an interrupt follows the same restoration path as EOF. - $this->command->getStty()->withTerminalMode( - $call, '-echo', '-echonl', '-icanon', '-isig', '-iexten', '-ixon', - '-igncr', '-inlcr', '-icrnl', 'min', '1', 'time', '0' - ); - } - /** * @param array $selected * @return array */ private function selectMultipleInTerminal(string $message, array $selected): array { - $this->withNavigationMode(function () use ($message, &$selected): void { + $this->input->withMode(function () use ($message, &$selected): void { $this->command->title($message); $this->setHelperText('Use arrow keys to navigate, Space to toggle and (%s) to accept.'); $render = function (int $index) use (&$selected): void { @@ -294,7 +353,7 @@ private function readKeys(callable $render, ?callable $toggle = null): void /** @param list $knownKeys */ private function readKey(array $knownKeys): string { - $key = $this->readByte(); + $key = $this->input->readByte(); // Assemble escape sequences even when the terminal delivers one byte at a time. while (true) { $key = $key[0] === "\033" ? $key : strtolower($key); @@ -304,7 +363,7 @@ private function readKey(array $knownKeys): string if (in_array($key, $knownKeys, true) && !$this->command->inputIsReady(50000)) { return $key; } - $byte = $this->readByte(); + $byte = $this->input->readByte(); $key = in_array($byte, ["\033", "\r", "\n"], true) ? $byte : $key . $byte; continue 2; } @@ -313,19 +372,6 @@ private function readKey(array $knownKeys): string } } - private function readByte(): string - { - $input = $this->command->getInput(); - $byte = $this->command->readInputByte(); - return match ($byte) { - "\x03" => throw new InputInterruptedException(), - "\x04" => throw new InputExhaustedException(), - '' => throw ($input->eof() ? new InputExhaustedException() : - new PromptException('The input stream did not return any data.')), - default => $byte - }; - } - /** * Get the expected navigation key * diff --git a/src/NavigationInput.php b/src/NavigationInput.php new file mode 100644 index 0000000..e09a053 --- /dev/null +++ b/src/NavigationInput.php @@ -0,0 +1,143 @@ +command->getStty()->withTerminalMode( + $callback, '-echo', '-echonl', '-icanon', '-isig', '-iexten', '-ixon', + '-igncr', '-inlcr', '-icrnl', 'min', '1', 'time', '0', ...$settings + ); + } + + public function readByte(): string + { + if ($this->pending !== '') { + $byte = $this->pending; + $this->pending = ''; + return $byte; + } + + $input = $this->command->getInput(); + return match ($byte = $this->command->readInputByte()) { + "\x03" => throw new InputInterruptedException(), + "\x04" => throw new InputExhaustedException(), + '' => throw ($input->eof() ? new InputExhaustedException() : + new PromptException('The input stream did not return any data.')), + default => $byte, + }; + } + + /** + * Read a search key as typed, assembling a complete UTF-8 code point. + * An empty result represents an ignored key or malformed input. + */ + public function readSearchKey(): string + { + $key = $this->readByte(); + if ($key === "\033") { + return $this->readEscape(); + } + if (in_array($key, ["\r", "\n", "\x08", "\x7f"], true)) { + return $key; + } + + $first = ord($key); + $length = match (true) { + $first >= 0xc2 && $first <= 0xdf => 2, + $first >= 0xe0 && $first <= 0xef => 3, + $first >= 0xf0 && $first <= 0xf4 => 4, + default => 1, + }; + for ($i = 1; $i < $length; $i++) { + $byte = $this->readByte(); + if ((ord($byte) & 0xc0) !== 0x80) { + $this->pending = $byte; + return ''; + } + $key .= $byte; + } + return preg_match('/\A[[:print:]]\z/u', $key) === 1 ? $key : ''; + } + + private function readEscape(): string + { + $prefix = $this->readEscapeByte(); + if (in_array($prefix, [']', 'P', 'X', '^', '_'], true)) { + // Terminal control strings end at BEL or ST. Their payload is not text input. + $previous = ''; + while (($byte = $this->readEscapeByte()) !== '' && $byte !== "\x07") { + if ($previous === "\033" && $byte === '\\') { + break; + } + $previous = $byte; + } + return ''; + } + if ($prefix !== '[' && $prefix !== 'O') { + // Some Escape sequences have intermediate bytes before their final byte. + while ($prefix !== '' && ord($prefix) >= 0x20 && ord($prefix) <= 0x2f) { + $prefix = $this->readEscapeByte(); + } + if ($prefix === "\033") { + $this->pending = $prefix; + } + return ''; + } + + $sequence = "\033" . $prefix; + while (($byte = $this->readEscapeByte()) !== '') { + // Linux console function keys also use a second '[' before the final byte. + if ($sequence === "\033[" && $byte === '[') { + $sequence .= $byte; + continue; + } + $code = ord($byte); + if ($code >= 0x40 && $code <= 0x7e) { + return $sequence . $byte; + } + if ($code < 0x20 || $code > 0x3f) { + if ($byte === "\033") { + $this->pending = $byte; + } + return ''; + } + $sequence .= $byte; + } + return ''; + } + + private function readEscapeByte(): string + { + if (!$this->command->inputIsReady(self::ESCAPE_WAIT)) { + return ''; + } + $byte = $this->readByte(); + if (in_array($byte, ["\r", "\n", "\x08", "\x7f"], true)) { + $this->pending = $byte; + return ''; + } + return $byte; + } +} diff --git a/src/Prompt.php b/src/Prompt.php index 882d0db..644ab02 100755 --- a/src/Prompt.php +++ b/src/Prompt.php @@ -13,7 +13,7 @@ class Prompt { private const TYPES = [ - 'message', 'text', 'invisible', 'mask', 'password', 'list', 'select', 'multiselect', 'toggle', 'confirm', + 'message', 'text', 'invisible', 'mask', 'password', 'list', 'select', 'search', 'multiselect', 'toggle', 'confirm', 'continue', ]; @@ -167,7 +167,8 @@ private function askRow(array $row, bool $stored = false): mixed if ($input === false && ($rowType === 'continue' || $rowType === 'confirm')) { return false; } - if ($this->isEmpty($input)) { + // Search always returns a choice key, which can itself be an empty string. + if ($rowType !== 'search' && $this->isEmpty($input)) { $input = $default; } @@ -198,7 +199,7 @@ private function askRow(array $row, bool $stored = false): mixed private function readRow(string $type, string $message, mixed $items, mixed $defaults, bool $stored): mixed { - if (in_array($type, ['select', 'multiselect', 'continue'], true) && !is_array($items)) { + if (in_array($type, ['select', 'search', 'multiselect', 'continue'], true) && !is_array($items)) { throw new InvalidArgumentException("The items for a $type prompt must be an array."); } if ($type === 'multiselect' && !is_array($defaults)) { @@ -210,6 +211,7 @@ private function readRow(string $type, string $message, mixed $items, mixed $def 'invisible', 'mask', 'password' => $this->command->mask($message), 'list' => $this->command->list($message), 'select' => $this->command->select($message, $items), + 'search' => $this->command->selectWithSearch($message, $items), 'multiselect' => $this->command->multiSelect($message, $items, $defaults), 'toggle' => $this->command->toggle($message), 'continue' => $this->runNested($items, $stored), diff --git a/src/PromptDefinition.php b/src/PromptDefinition.php index 747bc7b..19771da 100644 --- a/src/PromptDefinition.php +++ b/src/PromptDefinition.php @@ -89,7 +89,7 @@ public static function check(array $steps, array $types, string $path = 'steps', default => throw new InvalidArgumentException("Unknown definition field \"$key\" at $location."), }; } - if (in_array($type, ['select', 'multiselect', 'continue'], true) && !array_key_exists('items', $data)) { + if (in_array($type, ['select', 'search', 'multiselect', 'continue'], true) && !array_key_exists('items', $data)) { throw new InvalidArgumentException("The $type prompt at $location requires items."); } $checked[$name] = $data; @@ -133,6 +133,9 @@ private static function checkItems(string $type, array $types, mixed $items, str if ($type === 'continue') { return self::check($items, $types, $path, $depth + 1); } + if ($type === 'search') { + return SearchSelection::checkItems($items, $path); + } if (!in_array($type, ['select', 'multiselect'], true) || $items === []) { throw new InvalidArgumentException("The items at $path require a selection prompt and at least one choice."); } diff --git a/src/SearchSelection.php b/src/SearchSelection.php new file mode 100644 index 0000000..b06087f --- /dev/null +++ b/src/SearchSelection.php @@ -0,0 +1,121 @@ + + */ + public static function checkItems(array $items, string $path = 'items'): array + { + if ($items === []) { + throw new InvalidArgumentException("The search items at $path require at least one choice."); + } + $choices = []; + foreach ($items as $key => $label) { + if (!is_string($label) || preg_match('/\A[[:print:]]+\z/u', $label) !== 1) { + throw new InvalidArgumentException("Each search choice at $path must be a printable single-line UTF-8 string."); + } + $choices[$key] = $label; + } + return $choices; + } + + /** + * @param array $items + * @return array + */ + public static function filter(array $items, string $query): array + { + if ($query === '') { + return $items; + } + if (preg_match('//u', $query) !== 1) { + return []; + } + if (strlen($query) <= 4096) { + $pattern = '~' . preg_quote($query, '~') . '~iu'; + return array_filter($items, static fn (string $label): bool => preg_match($pattern, $label) === 1); + } + + // Match long queries in bounded pieces so PCRE's pattern size does not limit the input. + preg_match_all('/.{1,1024}/su', $query, $pieces); + if (!isset($pieces[0][0])) { + return []; + } + $start = '~' . preg_quote($pieces[0][0], '~') . '~iu'; + $rest = array_map( + static fn (string $part): string => '~\G' . preg_quote($part, '~') . '~iu', + array_slice($pieces[0], 1) + ); + return array_filter($items, static fn (string $label): bool => self::matchesPieces($label, $start, $rest)); + } + + /** + * @param non-empty-string $start + * @param list $rest + */ + private static function matchesPieces(string $label, string $start, array $rest): bool + { + $offset = 0; + while (preg_match($start, $label, $match, PREG_OFFSET_CAPTURE, $offset) === 1) { + [$text, $position] = $match[0]; + $end = $position + strlen($text); + foreach ($rest as $pattern) { + if (preg_match($pattern, $label, $next, 0, $end) !== 1) { + // Retry at the next code point because overlapping matches are possible. + $offset = self::characterBoundary($label, $position + 1); + continue 2; + } + $end += strlen($next[0]); + } + return true; + } + return false; + } + + public static function clip(string $text, int $width): string + { + // A byte budget is a conservative column limit, including double-width glyphs. + if (strlen($text) <= $width) { + return $text; + } + $ellipsis = $width > 3 ? '...' : ''; + $end = max(0, $width - strlen($ellipsis)); + while ($end > 0 && (ord($text[$end]) & 0xc0) === 0x80) { + $end--; + } + return substr($text, 0, $end) . $ellipsis; + } + + public static function displayQuery(string $query, int $width): string + { + $prefix = 'Filter: '; + $available = $width - strlen($prefix); + if ($available <= 0 || strlen($query) <= $available) { + return self::clip($prefix . $query, $width); + } + if ($available > 3) { + $start = self::characterBoundary($query, strlen($query) - $available + 3); + if ($start < strlen($query)) { + return $prefix . '...' . substr($query, $start); + } + } + $start = self::characterBoundary($query, strlen($query) - $available); + return $prefix . substr($query, $start); + } + + private static function characterBoundary(string $text, int $offset): int + { + while (isset($text[$offset]) && (ord($text[$offset]) & 0xc0) === 0x80) { + $offset++; + } + return $offset; + } +} diff --git a/src/SttyWrapper.php b/src/SttyWrapper.php index 7334271..cdd79a3 100755 --- a/src/SttyWrapper.php +++ b/src/SttyWrapper.php @@ -137,6 +137,23 @@ public function hasSttySupport(): bool return false; } + /** + * @internal + * @return array{int, int} Terminal rows and columns. + */ + public function terminalSize(): array + { + try { + $size = $this->runStty('size'); + } catch (PromptException) { + return [24, 80]; + } + if (preg_match('/\A([0-9]+)\s+([0-9]+)\z/', $size, $parts) !== 1) { + return [24, 80]; + } + return [(int)$parts[1] ?: 24, (int)$parts[2] ?: 80]; + } + /** * Apply settings to standard input for the duration of a terminal operation. * diff --git a/tests/unitary-search.php b/tests/unitary-search.php new file mode 100644 index 0000000..719ef67 --- /dev/null +++ b/tests/unitary-search.php @@ -0,0 +1,211 @@ +write("answer\n"); + $input->rewind(); + $command = new Command(new Stream('php://memory'), $input); + $prompt = (new Prompt($command))->setTitle('Search'); + foreach ([[], [123], [null], [''], ["split\nline"], ["tab\there"], ["\033[31mred"], ["\xff"], ["\u{2028}"]] as $items) { + $case->expect(fn () => $command->selectWithSearch('Invalid', $items)) + ->isThrowable(InvalidArgumentException::class)->validate(); + } + + foreach ([[], ['items' => []], ['items' => ["Invalid\rlabel"]]] as $fields) { + $case->expect(fn () => $prompt->runDefinition([ + 'first' => ['message' => 'First question'], + 'nested' => ['type' => 'continue', 'items' => [ + 'choice' => ['type' => 'search', 'message' => 'Choose'] + $fields, + ]], + ]))->isThrowable(InvalidArgumentException::class)->validate(); + } + $case->expect($input->tell() === 0 && (string)$command->getStream() === '')->isTrue()->validate(); + $case->expect(fn () => $prompt->promptLine(['type' => 'search', 'message' => 'Choose', 'items' => 'bad'])) + ->isThrowable(InvalidArgumentException::class)->validate(); +}); + +group('Search handles long Unicode queries and reports exhaustion after no matches', static function (TestCase $case) { + $label = str_repeat('É', 3000) . 'end'; + $query = str_repeat('é', 2500) . 'END'; + $input = new Stream('php://memory'); + $input->write("$query\n1\n" . str_repeat('z', 70000) . "\n"); + $input->rewind(); + $command = new Command(new Stream('php://memory'), $input); + $case->expect($command->selectWithSearch('Long', [42 => $label]) === 42)->isTrue()->validate(); + $case->expect(fn () => $command->selectWithSearch('Exhausted', [42 => 'Short'])) + ->isThrowable(InputExhaustedException::class)->validate(); +}); + +group('Piped search numbers all literal matches and preserves keys in direct and workflow prompts', static function (TestCase $case) { + $code = <<<'PHP' + require 'vendor/autoload.php'; + $command = new \MaplePHP\Prompts\Command(); + $command->getAnsi()->disableAnsi(true); + $items = [5 => 'Regular label', 0 => 'Text [é].', 'duplicate' => 'Text [é].', '' => 'Empty key']; + for ($i = 4; $i <= 10; $i++) { + $items["key-$i"] = "Choice $i"; + } + $row = ['type' => 'search', 'message' => 'Workflow', 'items' => $items]; + $prompt = (new \MaplePHP\Prompts\Prompt($command))->disableHeaderInfo(true); + $results = [ + $command->selectWithSearch('Literal', $items), + $command->selectWithSearch('All', $items), + $prompt->set(['result' => $row + ['default' => 'unused']])->prompt(), + $prompt->runDefinition(['result' => $row]), + $command->ask('Next'), + ]; + echo json_encode($results, JSON_THROW_ON_ERROR); + PHP; + $process = proc_open([PHP_BINARY, '-r', $code], [['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']], $pipes, dirname(__DIR__)); + if (!is_resource($process)) { + throw new RuntimeException('Could not run the piped search fixture'); + } + fwrite($pipes[0], "no results\r\n[É].\r\n2\r\n\r\n11\r\nempty key\r\n1\r\n[É].\r\n1\r\n next answer \r\n"); + fclose($pipes[0]); + $stdout = stream_get_contents($pipes[1]); + $stderr = stream_get_contents($pipes[2]); + fclose($pipes[1]); + fclose($pipes[2]); + + $case->expect(proc_close($process) === 0 && $stderr === '')->isTrue()->validate($stderr); + $case->expect(str_ends_with($stdout, '["duplicate","key-10",{"result":""},{"result":0}," next answer "]')) + ->isTrue()->validate($stdout); + $case->expect(str_contains($stdout, "No matches.\n") && + str_contains($stdout, "Literal (1-2)\n1: Text [é].\n2: Text [é].\n") && + str_contains($stdout, "11: Choice 10\n") && !str_contains($stdout, "\033")) + ->isTrue()->validate($stdout); +}); + +$pty = TestConfig::make('A Unix pseudo-terminal edits and scrolls search choices and restores mode on every exit') + ->withSkip(!in_array(PHP_OS_FAMILY, ['Darwin', 'Linux'], true) || !function_exists('exec')); +group($pty, static function (TestCase $case) { + $code = <<<'PHP' + require 'vendor/autoload.php'; + putenv('TERM=xterm-256color'); + exec('stty rows 18 cols 32 -echo icanon isig istrip'); + $terminalState = static function (): string { + $state = exec('stty -g'); + if (PHP_OS_FAMILY !== 'Darwin') { + return $state; + } + // Darwin sets PENDIN until the next canonical-mode kernel read. + return preg_replace_callback('/lflag=([0-9a-f]+)/', static function (array $match): string { + return 'lflag=' . dechex(hexdec($match[1]) & ~0x20000000); + }, $state); + }; + $before = $terminalState(); + $verify = static function (bool $result) use ($before, $terminalState): void { + $after = $terminalState(); + if (!$result || $after !== $before) { + throw new RuntimeException("Unexpected selection or terminal mode\nBefore: $before\nAfter: $after"); + } + }; + $command = new \MaplePHP\Prompts\Command(); + $long = str_repeat('界', 24) . 'long-label-tail'; + $items = ['duplicate' => 'Label É', 0 => 'Label É', 'long' => $long]; + for ($i = 4; $i <= 12; $i++) { + $items["key-$i"] = "Choice $i"; + } + + $verify($command->selectWithSearch('Edit session', $items) === 0); + // Use the ordinary stream line reader independently of the installed readline extension. + $command->getAnsi()->disableAnsi(true); + $verify($command->ask('Next question') === 'next answer'); + $command->getAnsi()->disableAnsi(false); + + $prompt = new \MaplePHP\Prompts\Prompt($command); + $verify($prompt->promptLine(['type' => 'search', 'message' => 'Scroll session', 'items' => $items]) === 'key-10'); + $verify($command->selectWithSearch('Long query session', $items) === 'long'); + exec('stty cols 13'); + $verify($command->selectWithSearch('Narrow session', [42 => '12345🙂']) === 42); + exec('stty cols 32'); + + try { + $command->selectWithSearch('Interrupt session', $items); + $verify(false); + } catch (\MaplePHP\Prompts\Exceptions\InputInterruptedException) { + $verify(true); + } + try { + $command->selectWithSearch('EOF session', $items); + $verify(false); + } catch (\MaplePHP\Prompts\Exceptions\InputExhaustedException) { + $verify(true); + } + $throwing = new class extends \MaplePHP\Prompts\Command { + protected function showMenu(int $selIndex, array $items): void + { + throw new LogicException('Renderer failed'); + } + }; + try { + $throwing->selectWithSearch('Renderer session', $items); + $verify(false); + } catch (LogicException $exception) { + $verify($exception->getMessage() === 'Renderer failed'); + } + echo "Completed\n"; + PHP; + + $process = proc_open([PHP_BINARY, '-r', $code], [['pty'], ['redirect', 0], ['pipe', 'w']], $pipes, dirname(__DIR__)); + if (!is_resource($process)) { + throw new RuntimeException('Could not open the Unix pseudo-terminal'); + } + $answers = [ + ['Edit session', ["\033", '', '', '', '', '', "\033[D\033[3~\033OH\033OP\033(B\033]ignored\x07\t", "\xc3", "\x89", 'Z', + "\xf0\x9f", "\xa7\xaa", "\r", "\n", "\x7f\x08", "\033", '[', 'B', "\r", "\n"]], + ['Next question', ["next answer\n"]], + ['Scroll session', [str_repeat("\033[B", 12), "\033OA\033[A\n"]], + ['Long query session', [str_repeat('界', 24) . "long-label-taix\x7fl\n"]], + ['Narrow session', ["12345🙂\n"]], + ['Interrupt session', ["\033[", "\x03"]], + ['EOF session', ["\xc3", "\x04"]], + ]; + $terminal = $pipes[0]; + stream_set_blocking($terminal, false); + $output = ''; + $deadline = microtime(true) + 8; + try { + do { + $output .= (string)@stream_get_contents($terminal); + if ($answers !== [] && str_contains($output, $answers[0][0])) { + [, $chunks] = array_shift($answers); + foreach ($chunks as $chunk) { + if ($chunk !== '') { + fwrite($terminal, $chunk); + } + usleep(12000); + } + } + $status = proc_get_status($process); + if (!$status['running']) { + $output .= (string)@stream_get_contents($terminal); + break; + } + usleep(5000); + } while (microtime(true) < $deadline); + } finally { + if ($status['running'] ?? true) { + proc_terminate($process, 9); + } + fclose($terminal); + $errors = stream_get_contents($pipes[2]); + fclose($pipes[2]); + proc_close($process); + } + $case->expect(($status['exitcode'] ?? -1) === 0 && $errors === '')->isTrue()->validate($output . $errors); + $case->expect($answers === [] && str_contains($output, 'Completed') && str_contains($output, "\033[9A") && + str_contains($output, "\033[2A") && str_contains($output, 'Filter: ÉZ🧪') && + str_contains($output, 'No matches.') && str_contains($output, 'Filter: ...') && + str_contains($output, 'Filter: 🙂') && + !str_contains($output, 'Filter: ignored'))->isTrue()->validate($output); +}); From a40d04c72f3adb1f7c6dc1a875746aa574ee89ed Mon Sep 17 00:00:00 2001 From: Daniel Ronkainen Date: Mon, 30 Nov 2026 20:19:07 +0100 Subject: [PATCH 11/15] feat: add work-driven progress bars --- src/Command.php | 11 +++ src/ProgressBar.php | 139 +++++++++++++++++++++++++++++++ src/SttyWrapper.php | 29 ++++++- tests/unitary-progress.php | 163 +++++++++++++++++++++++++++++++++++++ 4 files changed, 340 insertions(+), 2 deletions(-) create mode 100644 src/ProgressBar.php create mode 100644 tests/unitary-progress.php diff --git a/src/Command.php b/src/Command.php index a08f7e0..5ea03a9 100755 --- a/src/Command.php +++ b/src/Command.php @@ -520,6 +520,17 @@ public function confirm(string $message): bool return $line === "yes"; } + /** + * Show progress as the caller completes work. Terminal output updates the current line. + * Other streams receive a single completed/total summary when the bar finishes. + * + * @throws InvalidArgumentException For a negative total or nonpositive width. + */ + public function progressBar(int $total, int $width = 40): ProgressBar + { + return new ProgressBar($this, $total, $width); + } + /** * Create a progress bar * diff --git a/src/ProgressBar.php b/src/ProgressBar.php new file mode 100644 index 0000000..a7a7601 --- /dev/null +++ b/src/ProgressBar.php @@ -0,0 +1,139 @@ +stream = $command->getStream(); + if ($command->hasCursorOutput()) { + /** @var resource|closed-resource|null $terminal */ + $terminal = $this->stream instanceof Stream ? $this->stream->getResource() : null; + [, $columns] = is_resource($terminal) ? $command->getStty()->outputTerminalSize($terminal) : [24, 80]; + + // Reserve room for both counters, their slash and a spare column before allocating bar cells. + $available = $columns - 2 * strlen((string)$total) - 2; + if ($available >= 0) { + $this->width = min($width, max(0, $available - 3)); + $this->redraw = "\r" . $command->getAnsi()->clearLine(); + } + } + + $this->finished = $total === 0; + $this->render(0, $this->finished); + } + + /** + * Record completed work and finish automatically when the total is reached. + * + * @throws InvalidArgumentException For negative steps. + */ + public function advance(int $steps = 1): void + { + if ($steps < 0) { + throw new InvalidArgumentException('Progress steps cannot be negative.'); + } + if ($this->finished || $steps === 0) { + return; + } + + $completed = $this->completed + min($steps, $this->total - $this->completed); + $finished = $completed === $this->total; + $this->render($completed, $finished, redraw: true); + $this->completed = $completed; + $this->finished = $finished; + } + + /** Finish at the current count. Repeated calls leave the output alone. */ + public function finish(): void + { + if ($this->finished) { + return; + } + $this->write($this->redraw === null ? "$this->completed/$this->total\n" : "\n"); + $this->finished = true; + } + + private function render(int $completed, bool $finished, bool $redraw = false): void + { + if ($this->redraw === null && !$finished) { + // Check for a partial write even when this update emits no bytes. + $this->write(''); + return; + } + + $message = "$completed/$this->total"; + if ($this->width > 0) { + $filled = $this->filledCells($completed); + $message = '[' . str_repeat('=', $filled) . str_repeat('-', $this->width - $filled) . '] ' . $message; + } + $prefix = $redraw ? ($this->redraw ?? '') : ''; + $this->write($prefix . $message . ($finished ? "\n" : '')); + } + + private function filledCells(int $completed): int + { + if ($completed === $this->total) { + return $this->width; + } + $scaled = $completed * $this->width; + if (is_int($scaled)) { + return intdiv($scaled, $this->total); + } + + // Accumulate the ratio one cell at a time when multiplying would overflow. + $filled = $remainder = 0; + $gap = $this->total - $completed; + for ($cell = 0; $cell < $this->width; $cell++) { + if ($remainder >= $gap) { + $remainder -= $gap; + $filled++; + } else { + $remainder += $completed; + } + } + return $filled; + } + + private function write(string $message): void + { + if ($this->partialOutput !== null && $this->partialOutput !== $message) { + throw new RuntimeException('Retry the interrupted progress update before writing another.'); + } + $length = strlen($message); + while ($this->outputOffset < $length) { + $written = $this->stream->write(substr($message, $this->outputOffset)); + if ($written <= 0) { + throw new RuntimeException('Could not write progress output.'); + } + $this->partialOutput = $message; + $this->outputOffset += $written; + } + $this->partialOutput = null; + $this->outputOffset = 0; + } +} diff --git a/src/SttyWrapper.php b/src/SttyWrapper.php index cdd79a3..9c2757d 100755 --- a/src/SttyWrapper.php +++ b/src/SttyWrapper.php @@ -144,11 +144,36 @@ public function hasSttySupport(): bool public function terminalSize(): array { try { - $size = $this->runStty('size'); + return $this->parseSize($this->runStty('size')); } catch (PromptException) { return [24, 80]; } - if (preg_match('/\A([0-9]+)\s+([0-9]+)\z/', $size, $parts) !== 1) { + } + + /** + * @internal + * @param resource $terminal The terminal to measure. + * @return array{int, int} Terminal rows and columns. + */ + public function outputTerminalSize($terminal): array + { + if (!function_exists('proc_open') || !$this->isUnix()) { + return [24, 80]; + } + // stty queries its input descriptor. Supply the output terminal even when stdin is redirected. + $process = proc_open(['stty', 'size'], [$terminal, ['pipe', 'w'], ['redirect', 1]], $pipes); + if (!is_resource($process)) { + return [24, 80]; + } + $size = stream_get_contents($pipes[1]); + fclose($pipes[1]); + return proc_close($process) === 0 && $size !== false ? $this->parseSize($size) : [24, 80]; + } + + /** @return array{int, int} */ + private function parseSize(string $size): array + { + if (preg_match('/\A([0-9]+)\s+([0-9]+)\z/', trim($size), $parts) !== 1) { return [24, 80]; } return [(int)$parts[1] ?: 24, (int)$parts[2] ?: 80]; diff --git a/tests/unitary-progress.php b/tests/unitary-progress.php new file mode 100644 index 0000000..78c7710 --- /dev/null +++ b/tests/unitary-progress.php @@ -0,0 +1,163 @@ +progressBar(total: 5, width: 3); + $second = $command->progressBar(7); + $case->expect($first instanceof ProgressBar)->isTrue()->validate(); + + $first->advance(steps: 2); + $second->advance(0); + $second->advance(); + $case->expect((string)$stream)->isEqualTo('')->validate(); + + $second->finish(); + $case->expect((string)$stream)->isEqualTo("1/7\n")->validate(); + $first->advance(3); + $first->advance(PHP_INT_MAX); + $first->finish(); + $second->advance(5); + $second->finish(); + $case->expect((string)$stream)->isEqualTo("1/7\n5/5\n")->validate(); +}); + +group('Progress bars handle empty work and large steps without integer overflow', static function (TestCase $case) { + $stream = new Stream('php://memory'); + $command = new Command(stream: $stream); + $empty = $command->progressBar(0); + $case->expect((string)$stream)->isEqualTo("0/0\n")->validate(); + $empty->advance(); + $empty->finish(); + + $large = $command->progressBar(PHP_INT_MAX, PHP_INT_MAX); + $large->advance(5); + $large->advance(PHP_INT_MAX); + $large->finish(); + $case->expect((string)$stream)->isEqualTo('0/0' . "\n" . PHP_INT_MAX . '/' . PHP_INT_MAX . "\n")->validate(); +}); + +group('Progress bars reject invalid dimensions and steps before writing', static function (TestCase $case) { + $stream = new Stream('php://memory'); + $command = new Command(stream: $stream); + $case->expect(fn () => $command->progressBar(-1))->isThrowable(InvalidArgumentException::class)->validate(); + $case->expect(fn () => $command->progressBar(0, 0))->isThrowable(InvalidArgumentException::class)->validate(); + $case->expect(fn () => $command->progressBar(1, -1))->isThrowable(InvalidArgumentException::class)->validate(); + + $bar = $command->progressBar(3); + $case->expect(fn () => $bar->advance(-1))->isThrowable(InvalidArgumentException::class)->validate(); + $case->expect((string)$stream)->isEqualTo('')->validate(); + $bar->finish(); + $case->expect(fn () => $bar->advance(-1))->isThrowable(InvalidArgumentException::class)->validate(); + $case->expect((string)$stream)->isEqualTo("0/3\n")->validate(); +}); + +group('Progress summaries handle short writes and report a stalled stream', static function (TestCase $case) { + $stream = new class ('php://memory') extends Stream { + public ?int $writesBeforeStall = null; + + public function write(string $string): int + { + if ($this->writesBeforeStall !== null) { + if ($this->writesBeforeStall === 0) { + return 0; + } + $this->writesBeforeStall--; + } + return parent::write(substr($string, 0, 2)); + } + }; + $command = new Command(stream: $stream); + $command->progressBar(100)->advance(100); + $case->expect((string)$stream)->isEqualTo("100/100\n")->validate(); + + $bar = $command->progressBar(100); + $bar->advance(5); + $stream->writesBeforeStall = 1; + $case->expect(fn () => $bar->finish())->isThrowable(RuntimeException::class)->validate(); + $case->expect((string)$stream)->isEqualTo("100/100\n5/")->validate(); + $case->expect(fn () => $bar->advance())->isThrowable(RuntimeException::class)->validate(); + $stream->writesBeforeStall = null; + $bar->finish(); + $case->expect((string)$stream)->isEqualTo("100/100\n5/100\n")->validate(); +}); + +$pty = TestConfig::make('A Unix output terminal redraws progress with redirected standard input') + ->withSkip(!in_array(PHP_OS_FAMILY, ['Darwin', 'Linux'], true)); +group($pty, static function (TestCase $case) { + $code = <<<'PHP' + require 'vendor/autoload.php'; + $columns = static function (int $columns): void { + $stty = proc_open(['stty', 'rows', '24', 'cols', (string)$columns], [STDOUT, STDOUT, STDERR], $pipes); + if (!is_resource($stty) || proc_close($stty) !== 0) { + throw new RuntimeException('Could not size the output terminal'); + } + }; + + putenv('TERM=xterm-256color'); + $command = new \MaplePHP\Prompts\Command(); + if ($command->hasTerminalInput() || !$command->hasCursorOutput()) { + throw new RuntimeException('Expected an output terminal and redirected input'); + } + + $columns(80); + $bar = $command->progressBar(4, 4); + $bar->advance(0); + $bar->advance(2); + $bar->advance(PHP_INT_MAX); + $bar->finish(); + $bar->advance(); + $command->progressBar(0, 2); + + $exact = $command->progressBar(22, 22); + $exact->advance(15); + $exact->finish(); + + $large = $command->progressBar(PHP_INT_MAX, 4); + $half = intdiv(PHP_INT_MAX, 2); + $large->advance($half); + $large->advance(PHP_INT_MAX - 1 - $half); + $large->finish(); + $large->finish(); + + $columns(14); + $narrow = $command->progressBar(3, PHP_INT_MAX); + $narrow->advance(); + $narrow->finish(); + + $command->getAnsi()->disableAnsi(true); + $plain = $command->progressBar(3); + $plain->advance(2); + $plain->finish(); + $command->line('Next line'); + PHP; + $process = proc_open([PHP_BINARY, '-r', $code], [['pipe', 'r'], ['pty'], ['pipe', 'w']], $pipes, dirname(__DIR__)); + if (!is_resource($process)) { + throw new RuntimeException('Could not open the Unix output pseudo-terminal'); + } + fclose($pipes[0]); + $stdout = (string)@stream_get_contents($pipes[1]); + $stderr = stream_get_contents($pipes[2]); + fclose($pipes[1]); + fclose($pipes[2]); + $case->expect(proc_close($process) === 0 && $stderr === '')->isTrue()->validate($stderr); + + $redraw = "\r\033[2K"; + $max = PHP_INT_MAX; + $half = intdiv($max, 2); + $almost = $max - 1; + $case->expect(str_replace("\r\n", "\n", $stdout))->isEqualTo( + "[----] 0/4{$redraw}[==--] 2/4{$redraw}[====] 4/4\n[==] 0/0\n" . + "[----------------------] 0/22{$redraw}[===============-------] 15/22\n" . + "[----] 0/$max{$redraw}[=---] $half/$max{$redraw}[===-] $almost/$max\n" . + "[-------] 0/3{$redraw}[==-----] 1/3\n2/3\nNext line\n" + )->validate(); +}); From e142e25d70699d0f03fefac2be6fdafa6ccefc15 Mon Sep 17 00:00:00 2001 From: Daniel Ronkainen Date: Mon, 30 Nov 2026 20:27:15 +0100 Subject: [PATCH 12/15] docs: lead the Prompts guide with runnable recipes --- README.md | 10 +- docs/guide.md | 464 +++++++++++++++++++++++++++++++++---------- docs/migration.md | 6 + examples/command.php | 25 ++- examples/example.php | 3 +- 5 files changed, 391 insertions(+), 117 deletions(-) diff --git a/README.md b/README.md index 1797c3e..d55e7b4 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # MaplePHP Prompts -Build PHP command-line tools with questions, menus, hidden input, validation, and formatted output. Use `Command` to control the interaction step by step or `Prompt` to run a workflow such as an installer. Both use the same terminal and piped-input support. +Build PHP command-line tools with validated questions, searchable menus, hidden input, progress bars, and formatted output. Use `Command` to control the interaction step by step or `Prompt` to run a workflow such as an installer. Both support terminals and piped input. ## Installation @@ -10,7 +10,7 @@ Prompts requires PHP 8.2 or later. Install it in your application with Composer. composer require maplephp/prompts ``` -The quickstarts use the API in this checkout. To try it before it is available in a release, run `composer install` in the package root and use the included demos. +Composer installs a published release. The quickstarts and guide use the API in this checkout. To try them with the current source, run `composer install` in the package root and use the included demos or save the snippets alongside that checkout's `vendor` directory. ## Quickstart with Command @@ -37,7 +37,7 @@ try { } ``` -Enter a report name, then choose the format. The repository demo adds multi-select, confirmation, a table, and progress output. Run it from the package root with `php examples/command.php`. [Command demo](examples/command.php) +Enter a report name, then choose the format. The repository demo validates the report name, confirms the chosen options, and updates a progress bar as it prepares each report section. Run it from the package root with `php examples/command.php`. [Command demo](examples/command.php) ## Quickstart with Prompt @@ -66,9 +66,9 @@ if ($answers === false) { $installer->getCommand()->success('Installation approved for ' . $answers['project'] . '.'); ``` -Enter at least three characters for the project name and answer `yes` to confirm. The repository demo adds a nested workflow, list validation, and hidden input. Run it from the package root with `php examples/example.php`. [Prompt demo](examples/example.php) +Enter at least three characters for the project name and answer `yes` to confirm. The repository demo adds a searchable environment picker, a nested workflow, list validation, and hidden input. Run it from the package root with `php examples/example.php`. [Prompt demo](examples/example.php) ## Documentation -- [Package guide](docs/guide.md) covers direct input, workflow options, stored definitions, and formatted output. +- [Package guide](docs/guide.md) includes recipes for validation, search, work-driven progress, and custom prompts, followed by the Command and workflow references. - [Migrating from Prompts 1.x](docs/migration.md) lists method replacements and behavior to check when upgrading. diff --git a/docs/guide.md b/docs/guide.md index 041fc74..5bdec23 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -1,70 +1,45 @@ # Prompts guide -The [quickstarts](../README.md) show direct calls with `Command` and a workflow with `Prompt`. The PHP examples below are standalone scripts. Save them next to your project's `vendor` directory and run them with `php`. +## Ask a question with Command -## Command input and output - -A `Command` reads from standard input and writes to standard output by default. Pass a PSR-7 output stream or response as `stream` and a separate PSR-7 stream as `input`. When given a response, `Command` writes to its body. To send prompts to stderr while reading stdin, pass a `MaplePHP\Http\Stream` wrapping `STDERR` as `stream`. `withStream()` returns a copy with a different output stream and keeps the same input. Pass the command to `new Prompt($command)` to use those streams for the full workflow, including nested prompts. - -| Method | Result | -| --- | --- | -| `ask($message)` | A `string`, including an empty line as `''`. Leading and trailing whitespace are preserved. | -| `mask($message)` | A `string` read without echoing the answer. Use it for passwords. | -| `list($message)` | An array of trimmed strings split on commas. Blank entries remain as `''`. | -| `select($message, $items)` | The chosen `int` or `string` key from a non-empty array of choices. | -| `multiSelect($message, $items, $defaults = [])` | A list of unique original choice keys in declaration order. Defaults are original keys. | -| `toggle($message)` | Integer `1` for yes or `0` for no. | -| `confirm($message)` | Boolean `true` for yes or `false` for no. | -| `line($message = '', $break = true)` | Writes a line. Pass `false` for `$break` to omit the newline. Returns `void`. | -| `title()`, `success()`, `status()`, `warning()` | Write styled output and return `void`. | -| `error($message, $break = true)` | Writes an error to the configured output and returns `false`. | - -### Terminals, pipes, and end of input - -- Arrow-key menus require terminal stdin, cursor-capable output, and usable Unix `stty`. Use Up and Down to move and Enter to accept. In a multi-select menu, Space toggles the current choice. -- With a pipe, redirected output, plain terminal settings, or Windows, a single choice uses one-based positions. A multi-select accepts comma-separated positions, a blank line to keep the defaults, or `none` to clear them. Invalid positions retry. The selected values are the original keys, including integer `0`. `inputSelect()` and `inputToggle()` explicitly use line input. Both `confirm()` and the line-based toggle expect `yes` or `no`. -- Masked input uses `stty` on a supported Unix stdin terminal and PowerShell on a native Windows stdin console. For injected input, use a recognized stdin terminal or a genuinely non-echoing source such as a pipe or memory stream. The caller controls whether a custom PSR stream echoes input. Recognized terminals that cannot be masked raise `PromptException`. The package's Windows CI job exercises redirected input. -- Direct reads and `promptLine()` throw `InputExhaustedException` if no answer remains. A final non-empty line without a newline still counts as an answer, and a blank line can apply a default. Raw terminal menus and masked reads report a handled Ctrl+C as `InputInterruptedException`. Both exceptions extend `PromptException`. `prompt()` and `runDefinition()` return `false` for either exception. Other input failures, such as failure to configure masked entry, can still throw `PromptException`. -- `getAnsi()->disableAnsi(true)` disables generated ANSI styling and cursor navigation. Passing `false` restores automatic detection. The detection uses `TERM` and the OS. A redirected stream can still receive text styles when `TERM` indicates ANSI support. Check `hasCursorOutput()` before writing cursor controls or set `TERM=dumb` for plain output. - -## Trusted PHP workflows +Save this as `command.php` next to your project's `vendor` directory. Run `TERM=dumb php command.php` in a terminal to try the numbered menu shown below. On Windows, run `php command.php`. The examples use the API in this checkout. See the [installation instructions](../README.md#installation) to try it locally. -`Prompt::set($rows)` replaces the queue, `add($name, $row)` adds or replaces one row, and `promptLine($row)` asks one question directly without consuming the queue. `setTitle()` and `setDescription()` customize the header. `disableHeaderInfo(true)` hides the header and its keyboard hint. - -Call `prompt()` to process queued rows in declaration order and get answers keyed by row name. Successful rows are removed as the run advances. If a confirmation is declined, EOF occurs, or input is interrupted, the run returns `false` and discards its partial results. A subsequent call on the same `Prompt` resumes at the first unfinished row using the available input and returns answers for the remaining rows. If a nested workflow aborts, its `continue` row stays queued and starts over when resumed. Call `set($rows)` again to repeat the full sequence, or use `runDefinition()` for a data-only workflow that starts fresh on every call. +```php + [3, 40], 'isEmail' => []]` or a legacy callable in trusted PHP. | -| `validator` | A trusted PHP callable. Return `true` to accept or `false` to retry. Use either `validator` or `validate` on a row. | -| `error` | A string to print on a failed validation attempt, or a trusted PHP callable taking `($rule, $input, $row)` and returning a string. The rule is `null` for callback validation. | -| `confirm` | A message printed after successful validation. On a `confirm` row it prints only after `yes`. | +use MaplePHP\Prompts\Command; +use MaplePHP\Prompts\Exceptions\PromptException; -| `type` | Value returned in the workflow | -| --- | --- | -| `text` | The typed string or its default. | -| `password`, `mask`, `invisible` | The hidden answer or its default. | -| `list` | An array of trimmed comma-separated strings. | -| `select` | The original choice key. | -| `multiselect` | A list of selected keys in declaration order. A top-level `required` or `isRequired` rule requires at least one selection and accepts a key of `0`. | -| `toggle` | Integer `1` or `0`. | -| `confirm` | Integer `1` for yes. A no aborts the workflow. | -| `continue` | An array of nested answers. A trusted `items` callback can return `false` to skip its nested questions, recording `true` for the row. | -| `message` | Displays text without adding an answer. | +$command = new Command(); +$command->title('Export report'); + +try { + $name = $command->ask('Report name'); + $format = $command->select('Output format', ['text' => 'Plain text', 'json' => 'JSON']); + $command->success("Selected $format for $name."); +} catch (PromptException $exception) { + $command->error($exception->getMessage()); + exit(1); +} +``` -Text `0` and the integer choice key `0` count as answers. For workflows that handle passwords, read the masked field from the result only where it is needed and omit it from summaries. +```text +Export report +Report name: Quarterly sales +Output format (1-2) +1: Plain text +2: JSON +Input your answer: 2 +Selected json for Quarterly sales. +``` -### Nested rows and callbacks +`select()` returns the original array key, so choosing the second row gives you `json`. In a terminal with cursor navigation, use the arrows and Enter instead of entering a number. -A `continue` row reuses the parent command and suppresses the nested header. In trusted PHP, an `items` callable receives the preceding accepted value and the current zero-based row index. A nested decline also aborts the parent workflow. +## Collect installer settings with Prompt -Save this as `database.php`. Answer `yes`, provide a host, and confirm with `yes` to see the nested host in the summary. +Use `Prompt` when an array can describe the questions and control when to proceed. Save this as `installer.php` and run `php installer.php`. Try `ab` to see validation retry, then enter `Maple` and answer `yes` to approve the settings. Answering `no` ends the workflow and returns `false`. ```php set([ - 'remote' => ['type' => 'toggle', 'message' => 'Use a remote database?'], - 'database' => [ - 'type' => 'continue', - 'items' => static fn (int $remote, int $index): array|false => $remote === 1 ? [ - 'host' => [ - 'message' => 'Database host', - 'validator' => static fn (string $host): bool => strlen($host) >= 3, - 'error' => 'Enter at least three characters.', - ], - 'connect' => ['type' => 'confirm', 'message' => 'Use this host?'], - ] : false, +$installer = (new Prompt())->setTitle('Project installer')->set([ + 'project' => [ + 'message' => 'Project name', + 'validate' => ['length' => [3, 40]], + 'error' => 'Enter a name with 3 to 40 characters.', ], + 'install' => ['type' => 'confirm', 'message' => 'Install this project?'], ]); -$answers = $prompt->prompt(); +$answers = $installer->prompt(); if ($answers === false) { exit(1); } -$prompt->getCommand()->line($answers['database']['host'] ?? 'Using the local database.'); +$installer->getCommand()->success('Installation approved for ' . $answers['project'] . '.'); ``` -## Stored workflow definitions +[Validation](#validate-a-direct-answer) · [Search](#search-a-list-of-choices) · [Progress](#track-work-as-it-completes) · [Formatted output](#formatted-output) · [Command reference](#command-input-and-output) · [Workflow rows](#row-options) + +## Validate a direct answer + +Use `askValidated()` to retry a question until it passes. A rule map uses the same [rules and arguments](#stored-rule-reference) as a stored workflow and is checked before the prompt reads input. For an application-specific check, pass a trusted PHP callable that receives the exact string entered. Return `true` to accept or `false` to show the error and ask again. + +Save this as `validate.php` and run `php validate.php`. Try `me` before `avery@example.com` and `Sales 2027` before `sales-2027`. -Use `runDefinition(array $steps)` to replay rows from JSON or another data store. It checks all rows, nested `items`, defaults, and rule arguments before writing a prompt or reading input. On invalid data it throws `InvalidArgumentException`. Each call starts with fresh rows and shares the configured command and header. The trusted queue set with `set()` and `add()` remains independent. +```php +askValidated('Contact email', ['isEmail' => []], 'Enter an email address.'); +$slug = $command->askValidated( + 'Workspace slug', + static fn (string $value): bool => preg_match('/\A[a-z0-9-]+\z/', $value) === 1, + 'Use lowercase letters, digits, or hyphens.' +); +$command->success("Workspace $slug will use $email."); +``` + +## Search a list of choices + +Save this as `search.php` and run `php search.php` in a terminal with cursor navigation. Type `customer` to filter, use Backspace to edit, move with Up or Down, and press Enter to select. The menu shows up to eight matches at a time and scrolls as you move. Search matches a case-insensitive, literal substring of a label and keeps the original keys and order, including choices that share a label. + +```php +selectWithSearch('Choose a dataset', [ + 'sales' => 'Sales totals', + 'customer-activity' => 'Customer activity', + 'customer-totals' => 'Customer totals', +]); +$command->line("Dataset key: $dataset"); +``` + +With piped input, the first line is the filter and the second is a one-based position among the matches. A blank filter shows all choices. If nothing matches, enter a new filter. This pipe selects `customer-totals`. + +```sh +printf 'customer\n2\n' | TERM=dumb php search.php +``` + +```text +Choose a dataset (filter, or leave blank for all): Choose a dataset (1-2) +1: Customer activity +2: Customer totals +Input your answer: Dataset key: customer-totals +``` + +## Stored workflow definitions + +Use a `search` row to offer the same interaction in a workflow loaded from JSON. Save this definition as `setup.json`. It also shows how to combine validation rules and use `continue` for nested questions. ```json { @@ -116,6 +138,15 @@ Save the definition as `setup.json`. }, "error": "Enter an email address or a five-digit PIN." }, + "dataset": { + "type": "search", + "message": "Choose a dataset", + "items": { + "sales": "Sales totals", + "customer-activity": "Customer activity", + "customer-totals": "Customer totals" + } + }, "details": { "type": "continue", "items": { @@ -126,7 +157,7 @@ Save the definition as `setup.json`. } ``` -Save this as `stored.php` beside `setup.json` and run `php stored.php`. Try `12345`, `05/03/2027`, then `yes`. +Save this as `stored.php` beside `setup.json` and run `php stored.php`. Enter `12345`, search for `customer` and select Customer totals, then enter `05/03/2027` and `yes`. For numbered input, supply `customer` and `2` on separate lines. ```php runDefinition($definition); if ($answers === false) { exit(1); } -$prompt->getCommand()->success('Setup approved for ' . $answers['details']['date'] . '.'); +$prompt->getCommand()->success('Setup approved for ' . $answers['dataset'] . ' on ' . $answers['details']['date'] . '.'); ``` -To run that definition again, pass it to `runDefinition()` again with fresh answers available on the input stream. The definition contains workflow configuration. The returned values are available to application code for persistence. +Each `runDefinition()` call checks the full definition before interacting and starts from the first row. Application code can use the answers when the run succeeds. See the [stored definition reference](#stored-definition-reference) for accepted data. -### Validation maps +## Nested rows and callbacks -A validation map keys each rule by name and provides an array of arguments in parameter order. Use `[]` for rules with no arguments. Top-level rules all need to pass. `oneOf` and `allOf` take one nested rule map, so the map must appear inside the argument array, as in `['oneOf' => [['isEmail' => [], 'isUrl' => []]]]`. `oneOf` passes if any nested rule passes and `allOf` passes if every nested rule passes. An empty `oneOf` fails and an empty `allOf` passes. +A `continue` row reuses the parent command and suppresses the nested header. In trusted PHP, an `items` callable receives the preceding accepted value and the current zero-based row index. A nested decline also aborts the parent workflow. -For array answers such as a comma-separated list or multi-select, rules and callable validators run on each item or choice key. The top-level multiselect required rule checks the selection as a whole. Trusted rule maps pass each value as a string to MaplePHP Validate. Stored rule maps check the typed value, so a strict comparison to `0` matches an integer key, while a comparison to `'0'` matches text input. In trusted PHP, a callable in `validate` uses the legacy polarity of `true` for retry and `false` for accept. Both callable forms must return a boolean. +Save this as `database.php`. Answer `yes`, provide a host, and confirm with `yes` to see the nested host in the summary. -### Stored rule reference +```php +`, `=`, `==`, `>`, `>=`, `eq`, `ge`, `gt`, `le`, `lt`, `ne`. The default is `==`. | -| `isEqualTo`, `isNotEqualTo` | `equal`, `notEqual` | `[expected]` as a scalar or `null`, compared strictly. | -| `isMatchingPattern` | `pregMatch` | `[range]`, a character-class contents string such as `'A-Z0-9'`. | -| `oneOf`, `allOf` | | `[ruleMap]`, recursively subject to the same rules and argument checks. | +use MaplePHP\Prompts\Prompt; -For trusted workflows, use `isDate` with an explicit format for dates and date-times, and `isValidVersion` for versions. These canonical methods are available at the package's Validate 2.0.0 floor, including when nested in a trusted `oneOf` or `allOf` rule. +$prompt = new Prompt(); +$prompt->set([ + 'remote' => ['type' => 'toggle', 'message' => 'Use a remote database?'], + 'database' => [ + 'type' => 'continue', + 'items' => static fn (int $remote, int $index): array|false => $remote === 1 ? [ + 'host' => [ + 'message' => 'Database host', + 'validator' => static fn (string $host): bool => strlen($host) >= 3, + 'error' => 'Enter at least three characters.', + ], + 'connect' => ['type' => 'confirm', 'message' => 'Use this host?'], + ] : false, + ], +]); + +$answers = $prompt->prompt(); +if ($answers === false) { + exit(1); +} +$prompt->getCommand()->line($answers['database']['host'] ?? 'Using the local database.'); +``` + +## Track work as it completes + +Save this as `progress.php` and run `php progress.php report.csv`. It creates a new CSV file and advances the bar after each successful write. Choose a fresh output filename for each run. + +```php +progressBar(count($rows), width: 12); +try { + foreach ($rows as $row) { + if (fputcsv($file, $row, escape: '') === false) { + throw new RuntimeException('Could not write the report.'); + } + $bar->advance(); + } +} finally { + fclose($file); + $bar->finish(); +} +``` + +A cursor-capable terminal updates the same line from `0/3` through `[============] 3/3`. Reaching the total finishes the bar automatically. If a write fails after one row, `finish()` ends the line at `1/3`. When output is redirected or cursor controls are unavailable, the bar writes just the final `done/total` line. For example, `php progress.php another-report.csv > progress.log` writes the following to the log. + +```text +3/3 +``` ## Formatted output -`Command::getAnsi()` styles strings, for example `style(['bold', 'blue'], $text)`. `Blocks` writes help text through a `Command`. A section can use a literal description or a callback. Return the builder from a section callback to display its options, list entries, or examples. `addOption()`, `addList()`, and `addExample()` return a new builder, so chain the calls or reassign the result. `addCode()` prints the source with PHP token styles when ANSI and the tokenizer are available. +### Design a prompt with ANSI styles -`table($headers, $rows)` takes a non-empty list of column headings and a list of rows with one cell per heading. Cells are scalars or stringable objects with single-line, printable UTF-8 text. Empty rows print only the headings. ANSI text styles are preserved without taking up columns. Wide characters and combining marks are accounted for, and emoji widths can vary by terminal. +Use styled spans to make the current action and settings easier to scan. Here `reverse()` marks the `EXPORT` label inside a blue background that resumes for `Report settings`. `dim()` de-emphasizes the hint, `underline()` marks the current format, and `strikethrough()` marks the retired format. The words `current` and `retired` carry the same meaning in plain output. + +Save this as `report-prompt.php`. In an ANSI-capable Unix terminal, run `TERM=xterm-256color php report-prompt.php` to see the styles. Run `php report-prompt.php --plain` to see the plain version below. + +```php +getAnsi(); +if (in_array('--plain', $argv, true)) { + $ansi->disableAnsi(true); +} + +$command->line($ansi->blueBg($ansi->reverse('EXPORT') . ' Report settings')); +$command->line($ansi->dim('The report includes the selected sections.')); +$command->line('Format: ' . $ansi->underline('JSON') . ' (current), ' . $ansi->strikethrough('XML') . ' (retired)'); +$name = $command->ask($ansi->bold('Report name')); +$command->success("Ready to export $name."); +``` + +```text +[EXPORT Report settings] +The report includes the selected sections. +Format: JSON (current), XML (retired) +Report name: Quarterly sales +Ready to export Quarterly sales. +``` + +To style an entire string, you can also pass a style name or an ordered list of names to `style()`, for example `style(['bold', 'blue'], $text)`. + +### Write help with Blocks + +Use `Blocks` to build help sections, show examples, and align tables through the same command output. Save this as `help.php` and run `php help.php`. ```php addSection('Usage', static fn (Blocks $section): Blocks => $section ->addExample('report --format=json', 'Export a JSON report')); $blocks->table(['Format', 'Description'], [['text', 'Plain text'], ['json', 'JSON']]); $blocks->addCode('$command->status("Preparing report");'); -$command->progress(3, 12, static fn ($i, $length): int => 20); ``` +A section can use a literal description or a callback. Return the builder from a callback to display its options, list entries, or examples. `addOption()`, `addList()`, and `addExample()` return a new builder, so chain the calls or reassign the result. `addCode()` prints the source with PHP token styles when ANSI and the tokenizer are available. + +`table($headers, $rows)` takes a non-empty list of column headings and a list of rows with one cell per heading. Cells are scalars or stringable objects with single-line, printable UTF-8 text. Empty rows print only the headings. ANSI text styles are preserved without taking up columns. Wide characters and combining marks are accounted for, and emoji widths can vary by terminal. + ### Custom navigation -Use `Navigation::navigate()` when you need to render a menu yourself. Its callback receives the zero-based highlighted index and the ordered list of labels. For cursor navigation, print exactly one terminal row per item. Keep labels short enough to avoid wrapping because the renderer moves up by a relative row count before redrawing. Numbered fallback calls the renderer before displaying the numbered choices and again if the chosen index changes. After acceptance, `getValue()` returns the original choice key and `getItem()` returns its label. Use `setAcceptKey()` to change the terminal acceptance key from Enter. +Use `Navigation::navigate()` to decide how a menu looks. The callback receives the zero-based highlighted index and the ordered labels. Here the highlighted row uses reverse video and starts with `>`, so focus remains visible in plain output. Save this as `menu.php` and run `php menu.php`. ```php setHelperText(Navigation::HELPER_TEXT); $navigation->navigate('Choose a format', ['text' => 'Plain text', 'json' => 'JSON'], static function (int $current, array $labels) use ($command): void { foreach ($labels as $index => $label) { - $marker = $current === $index ? '>' : ' '; - $command->line("$marker $label"); + $command->line($current === $index + ? $command->getAnsi()->reverse("> $label") + : " $label"); } } ); $command->success('Selected ' . $navigation->getItem()); ``` + +Print one terminal row per item and keep labels short enough to avoid wrapping. Cursor navigation moves up by a relative row count before redrawing. Numbered fallback calls the renderer before displaying the numbered choices and again if the chosen index changes. After acceptance, `getValue()` returns the original choice key and `getItem()` returns its label. `setAcceptKey()` changes the terminal acceptance key from Enter. + +## Command input and output + +### Streams and capabilities + +| Method | Behavior | +| --- | --- | +| `new Command($stream = null, $input = null)` | Defaults to stdout for output and stdin for input. A PSR-7 response supplies its body as the output stream. Pass a PSR-7 stream such as `new MaplePHP\Http\Stream(STDERR)` to write prompts to stderr. | +| `withStream($stream)` | Returns a copy with a different PSR-7 output stream and the same input. | +| `getStream()`, `getInput()` | Return the configured PSR-7 output and input streams, respectively. | +| `getAnsi()` | Returns the `Ansi` instance for styling strings and building terminal controls. | +| `hasTerminalInput()` | Checks whether input uses the process's stdin terminal. | +| `hasCursorOutput()` | Checks whether the configured output can receive cursor controls. | +| `supportsNavigation()` | Checks whether input, output, and Unix terminal controls can support cursor-based navigation. | +| `getStty()` | Returns the `SttyWrapper` for low-level Unix terminal settings. | + +Pass your configured command to `new Prompt($command)` to use those streams for the full workflow, including nested prompts. + +### Questions and choices + +| Method | Result | +| --- | --- | +| `ask($message)`, `readline($message)` | Read a string. An empty line returns `''`. Leading and trailing whitespace are preserved. `readline()` also backs `ask()`. | +| `askValidated($message, $validator, $error = 'Please try again.')` | Returns the accepted string after a rule map or trusted boolean callback passes it. | +| `mask($message)` | Reads a string without echoing terminal input. Use it for passwords. | +| `list($message)` | Returns trimmed strings split on commas. Blank entries remain as `''`. | +| `select($message, $items)` | Returns the chosen `int` or `string` key from a non-empty array. | +| `selectWithSearch($message, $items)` | Filters choices by label and returns the original key. Labels must be non-empty, printable, single-line UTF-8 strings. | +| `inputSelect($message, $choices)` | Always reads a numbered choice and returns the original key. | +| `multiSelect($message, $items, $defaults = [])` | Returns unique original choice keys in declaration order. Defaults are original keys. | +| `toggle($message)`, `inputToggle($message)` | Return integer `1` for yes or `0` for no. `inputToggle()` always reads `yes` or `no` as text. | +| `confirm($message)` | Reads `yes` or `no` and returns a boolean. | + +### Messages and progress + +The message methods listed with `$break` write a newline by default. Pass `false` to omit the newline. + +| Method | Behavior | +| --- | --- | +| `line($message = '', $break = true)` | Writes a line and returns `void`. Call with no arguments to print a blank line. | +| `title($message, $break = true)` | Writes a bold heading and returns `void`. | +| `success($message, $break = true)`, `status($message, $break = true)`, `warning($message, $break = true)` | Write a green, blue, or yellow message and return `void`. | +| `error($message, $break = true)` | Writes a red error to the configured output and returns `false`. | +| `progressBar($total, $width = 40)` | Creates a `ProgressBar`. Call `advance($steps = 1)` after work completes and `finish()` to end the display at its current count. | +| `progress($expectedRows, $maxLength = 100, $sleep = null)` | Runs a fixed-length animation and returns `void`. | + +`progressBar()` requires a non-negative total and a positive width. `advance()` rejects negative steps, ignores zero and caps the count at the total. A zero total finishes immediately as `0/0`. Once finished, further advances and repeated `finish()` calls produce no output. + +`progress()` writes `$maxLength` cells and a newline when both dimensions are positive. Either dimension can be zero to write a blank line. Negative dimensions throw `InvalidArgumentException`. The optional delay is in milliseconds. A delay callback runs once per cell and receives `($i, $length)` using the original scale. For scale `min($expectedRows, $maxLength) / max($expectedRows, $maxLength)`, `$i` is the zero-based frame times the scale and `$length` is `($maxLength - 0.5)` times the scale. The callback can return a positive integer delay or `0` to continue immediately. + +### Supported legacy names + +| Method | Behavior | +| --- | --- | +| `message($message, $getLine = false)` | Writes a line and returns `false` by default. With `$getLine` set to `true`, it asks a question and returns a string. Use `line()` and `ask()` in new code. | +| `approve($message, $break = true)` | Writes a success message and returns `false`. Use `success()` in new code. | +| `statusMsg($message, $break = true)` | Writes a status message and returns `false`. Use `status()` in new code. | + +See the [migration notes](migration.md) for additional aliases and upgrade details. + +### Terminals, pipes, and end of input + +- Arrow-key menus require terminal stdin, cursor-capable output, and usable Unix `stty`. Use Up and Down to move and Enter to accept. In a multi-select menu, Space toggles the current choice. Search also uses numbered input when the terminal is too small to display its live menu. +- With a pipe, redirected output, plain terminal settings, or Windows, a single choice uses one-based positions. Search first reads a filter line. A multi-select accepts comma-separated positions, a blank line to keep the defaults, or `none` to clear them. Invalid positions retry. The selected values are the original keys, including integer `0`. +- Masked input uses `stty` on a supported Unix stdin terminal and PowerShell on a native Windows stdin console. For injected input, use a recognized stdin terminal or a genuinely non-echoing source such as a pipe or memory stream. The caller controls whether a custom PSR stream echoes input. Recognized terminals that cannot be masked raise `PromptException`. The package's Windows CI job exercises redirected input. +- Direct reads and `promptLine()` throw `InputExhaustedException` if no answer remains. A final non-empty line without a newline still counts as an answer, and a blank line can apply a default. Raw terminal menus and masked reads report a handled Ctrl+C as `InputInterruptedException`. Both exceptions extend `PromptException`. `prompt()` and `runDefinition()` return `false` for either exception. Other input failures, such as failure to configure masked entry, can still throw `PromptException`. +- `getAnsi()->disableAnsi(true)` disables generated ANSI styling and cursor navigation. Passing `false` restores automatic detection. Detection uses `TERM` and the OS. A redirected stream can still receive text styles when `TERM` indicates ANSI support. Check `hasCursorOutput()` before writing cursor controls or set `TERM=dumb` for plain output. + +## Trusted PHP workflows + +`Prompt::set($rows)` replaces the queue, `add($name, $row)` adds or replaces one row, and `promptLine($row)` asks one question directly without consuming the queue. `getCommand()` returns the workflow command. `setTitle()` and `setDescription()` customize the header. `disableHeaderInfo(true)` hides the header and its keyboard hint. + +Call `prompt()` to process queued rows in declaration order and get answers keyed by row name. Successful rows are removed as the run advances. If a confirmation is declined, EOF occurs, or input is interrupted, the run returns `false` and discards its partial results. A subsequent call on the same `Prompt` resumes at the first unfinished row using the available input and returns answers for the remaining rows. If a nested workflow aborts, its `continue` row stays queued and starts over when resumed. Call `set($rows)` again to repeat the full sequence, or use `runDefinition()` for a data-only workflow that starts fresh on every call. + +### Row options + +| Key | Use | +| --- | --- | +| `type` | One of the types below, with `text` as the default. | +| `message` | The prompt or notice to display. Required except on `continue`. | +| `default` | A replacement for an empty text or masked answer. For `multiselect`, use a list of original choice keys. Defaults on masked input stay hidden. | +| `items` | A choice map for `select`, `search`, or `multiselect`, or nested rows for `continue`. In trusted PHP a `continue` row also accepts a callable. | +| `validate` | A rule map such as `['length' => [3, 40], 'isEmail' => []]` or a legacy callable in trusted PHP. | +| `validator` | A trusted PHP callable. Return `true` to accept or `false` to retry. Use either `validator` or `validate` on a row. | +| `error` | A string to print on a failed validation attempt, or a trusted PHP callable taking `($rule, $input, $row)` and returning a string. The rule is `null` for callback validation. | +| `confirm` | A message printed after successful validation. On a `confirm` row it prints only after `yes`. | + +| `type` | Value returned in the workflow | +| --- | --- | +| `text` | The typed string or its default. | +| `password`, `mask`, `invisible` | The hidden answer or its default. | +| `list` | An array of trimmed comma-separated strings. | +| `select`, `search` | The original choice key. Search filters by label before selection. | +| `multiselect` | A list of selected keys in declaration order. A top-level `required` or `isRequired` rule requires at least one selection and accepts a key of `0`. | +| `toggle` | Integer `1` or `0`. | +| `confirm` | Integer `1` for yes. A no aborts the workflow. | +| `continue` | An array of nested answers. A trusted `items` callback can return `false` to skip its nested questions, recording `true` for the row. | +| `message` | Displays text without adding an answer. | + +Text `0` and the integer choice key `0` count as answers. For workflows that handle passwords, read the masked field from the result only where it is needed and omit it from summaries. + +## Stored definition reference + +`runDefinition(array $steps)` checks all rows, nested `items`, defaults, and rule arguments before writing a prompt or reading input. On invalid data it throws `InvalidArgumentException`. Each call starts with fresh rows and shares the configured command and header. The trusted queue set with `set()` and `add()` remains independent. + +Store an object keyed by row name. Use scalar values, `null`, and arrays or objects that decode to PHP arrays. `items` on `continue` contains more named rows. `items` on selections is a non-empty map of keys to string labels. Search requires non-empty, printable, single-line UTF-8 labels. A text or masked `default` must be scalar or `null`. A multiselect `default` must be a list of existing choice keys with matching types. Use strings for `message`, `error`, and `confirm`. `validate` accepts only rule maps from the allowlist, and `message` rows only display text. PHP callables, arbitrary validation methods, DNS or file rules, and unknown fields are rejected. + +### Validation maps + +A validation map keys each rule by name and provides an array of arguments in parameter order. Use `[]` for rules with no arguments. Top-level rules all need to pass. `oneOf` and `allOf` take one nested rule map, so the map must appear inside the argument array, as in `['oneOf' => [['isEmail' => [], 'isUrl' => []]]]`. `oneOf` passes if any nested rule passes and `allOf` passes if every nested rule passes. An empty `oneOf` fails and an empty `allOf` passes. + +For array answers such as a comma-separated list or multi-select, rules and callable validators run on each item or choice key. The top-level multiselect required rule checks the selection as a whole. Trusted rule maps pass each value as a string to MaplePHP Validate. Stored rule maps check the typed value, so a strict comparison to `0` matches an integer key, while a comparison to `'0'` matches text input. In trusted PHP, a callable in `validate` uses the legacy polarity of `true` for retry and `false` for accept. Both callable forms must return a boolean. + +### Stored rule reference + +The names in either column below are accepted in a stored definition, including inside `oneOf` and `allOf`. + +| Canonical rules | Aliases | Positional arguments | +| --- | --- | --- | +| `isRequired`, `isEmail`, `isNumber`, `isUrl`, `isPhone` | `required`, `email`, `number`, `url`, `phone` | `[]` | +| `isBool`, `isBoolVal`, `isFloat`, `isInt`, `isPositive`, `isNegative` | `bool`, `boolVal`, `float`, `int`, `positive`, `negative` | `[]` | +| `isTrue`, `isFalse`, `isTruthy`, `isFalsy`, `isArray`, `isObject` | | `[]` | +| `isHexColor`, `isString`, `isAlpha`, `isLowerAlpha`, `isUpperAlpha` | `hex`, `string`, `atoZ`, `lowerAtoZ`, `upperAtoZ` | `[]` | +| `length`, `isZip` | `zip` for `isZip` | `[minimum]` or `[minimum, maximum]`. Non-negative integers, with an optional `null` maximum and any numeric maximum at least the minimum. | +| `min`, `max` | | `[limit]` as a finite number. | +| `isAge`, `isLengthEqualTo` | `age`, `equalLength` | `[minimumAge]` or `[length]` respectively, as a non-negative integer. | +| `isLossyPassword`, `isStrictPassword` | `lossyPassword`, `strictPassword` | `[]` or `[length]` as an integer from 0 to 65535. | +| `isDate`, `isDateWithTime` | `date`, `dateTime` | `[]` or `[format]` as a non-empty date format string. The defaults are `Y-m-d` and `Y-m-d H:i:s`. | +| `isValidVersion`, `isDomain` | `validVersion`, `domain` | `[]` or `[strict]` as a boolean. Strict mode is off for versions and on for domains by default. Domain validation checks syntax. | +| `versionCompare` | | `[version]` or `[version, operator]`, both strings. Operators are `!=`, `<`, `<=`, `<>`, `=`, `==`, `>`, `>=`, `eq`, `ge`, `gt`, `le`, `lt`, `ne`. The default is `==`. | +| `isEqualTo`, `isNotEqualTo` | `equal`, `notEqual` | `[expected]` as a scalar or `null`, compared strictly. | +| `isMatchingPattern` | `pregMatch` | `[range]`, a character-class contents string such as `'A-Z0-9'`. | +| `oneOf`, `allOf` | | `[ruleMap]`, recursively subject to the same rules and argument checks. | + +For trusted workflows, use `isDate` with an explicit format for dates and date-times, and `isValidVersion` for versions. These canonical methods are available at the package's Validate 2.0.0 floor, including when nested in a trusted `oneOf` or `allOf` rule. diff --git a/docs/migration.md b/docs/migration.md index 20cc8a6..57c4fbe 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -30,6 +30,12 @@ Check for `false` before using a workflow result. A declined confirmation, handl Selections can now use numbered input when cursor navigation is unavailable. In automated input, supply one-based positions using digits only and keep reading original choice keys from the result. A value such as `1x` retries the question. For a custom `Navigation` renderer, print one terminal row per item so relative cursor movement redraws the right lines. A recognized live terminal that cannot disable echo raises `PromptException` for masked input. +## Direct validation, search, and progress + +- Use `askValidated()` when a direct question should retry on validation failure. Its trusted callback returns `true` to accept, matching the trusted workflow `validator` field. [Validation recipe](guide.md#validate-a-direct-answer) +- Use `selectWithSearch()` or the `search` row type when users need to filter choices. Update piped answers to supply the filter line first, then the numbered choice. The result is still the original key. [Search recipe](guide.md#search-a-list-of-choices) +- Use `progressBar($total)` when work determines the count. Call `advance()` after a completed operation and `finish()` if work stops early. For redirected output, expect a single `done/total` line. The existing `progress()` method still runs its fixed-length animation. [Progress recipe](guide.md#track-work-as-it-completes) + ## Section callbacks `Blocks::addSection()` prints string descriptions literally, including strings that name functions or static methods. If a function name came from trusted PHP, wrap it with `Closure::fromCallable()` to invoke it as a section callback. Save and run this example from a project with the package installed. diff --git a/examples/command.php b/examples/command.php index 5b33952..7a0b488 100644 --- a/examples/command.php +++ b/examples/command.php @@ -12,7 +12,7 @@ $command->title('Export report'); try { - $name = $command->ask('Report name'); + $name = $command->askValidated('Report name', ['length' => [3, 40]], 'Enter a name with 3 to 40 characters.'); $format = $command->select('Output format', ['text' => 'Plain text', 'json' => 'JSON']); $sections = $command->multiSelect('Report sections', ['summary' => 'Summary', 'details' => 'Details'], ['summary']); $command->line(); @@ -32,8 +32,27 @@ $command->line(); $command->status('Preparing report'); - $command->progress(3, 12, 20); - $command->success('Export approved.'); + $totals = ['North' => 12, 'South' => 18]; + $report = []; + $bar = $command->progressBar(count($sections), width: 12); + try { + foreach ($sections as $section) { + $report[$section] = $section === 'summary' ? ['Total' => array_sum($totals)] : $totals; + $bar->advance(); + } + } finally { + $bar->finish(); + } + + if ($format === 'json') { + $command->line(json_encode($report, JSON_THROW_ON_ERROR)); + } else { + foreach ($report as $section => $values) { + $blocks->addText(ucfirst($section)); + $blocks->table(['Region', 'Total'], array_map(null, array_keys($values), $values)); + } + } + $command->success('Report prepared.'); } catch (PromptException $exception) { $command->error($exception->getMessage()); exit(1); diff --git a/examples/example.php b/examples/example.php index 4a79e80..634ee0e 100755 --- a/examples/example.php +++ b/examples/example.php @@ -43,7 +43,7 @@ ], 'notice' => ['type' => 'message', 'message' => 'Choose the settings for your first installation.'], 'environment' => [ - 'type' => 'select', + 'type' => 'search', 'message' => 'Environment', 'items' => ['local' => 'Local', 'staging' => 'Staging', 'production' => 'Production'], ], @@ -77,7 +77,6 @@ exit(1); } - $command->progress(4, 12, 20); $command->success(sprintf( 'Installation approved for %s %s at %s (%s).', $answers['firstName'], From 1a67a2c1dc8cae7d9ed762423e3ee8be9f8daf18 Mon Sep 17 00:00:00 2001 From: Daniel Ronkainen Date: Mon, 30 Nov 2026 20:30:09 +0100 Subject: [PATCH 13/15] test: cover the piped Command workflow --- tests/unitary-compatibility.php | 39 +++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/tests/unitary-compatibility.php b/tests/unitary-compatibility.php index c96d7c7..3fda411 100644 --- a/tests/unitary-compatibility.php +++ b/tests/unitary-compatibility.php @@ -43,6 +43,45 @@ public function readline(string $message): string } }); +group('A piped Command session validates input, selects keyed work and reports completion', static function (TestCase $case) { + $code = <<<'PHP' + require 'vendor/autoload.php'; + putenv('TERM=dumb'); + $command = new \MaplePHP\Prompts\Command(); + $name = $command->askValidated('Report name', ['length' => [3, 10]], 'Use 3 to 10 characters.'); + $preset = $command->selectWithSearch('Preset', [ + 'preview' => 'Daily preview', 'full' => 'Daily archive', 'weekly' => 'Weekly archive', + ]); + $note = $command->ask('Note'); + $sections = ['preview' => ['summary'], 'full' => ['summary', 'details', 'totals'], 'weekly' => ['totals']][$preset]; + $progress = $command->progressBar(count($sections)); + $report = []; + foreach ($sections as $section) { + $report[] = "$name/$section"; + $progress->advance(); + } + $progress->finish(); + $command->line(implode(', ', $report) . " [$note]"); + PHP; + $process = proc_open([PHP_BINARY, '-r', $code], [['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']], $pipes, dirname(__DIR__)); + if (!is_resource($process)) { + throw new RuntimeException('Could not run the piped Command fixture'); + } + fwrite($pipes[0], "x\r\nSales\r\nDAILY\r\n2\r\n keep spaces \r\n"); + fclose($pipes[0]); + $stdout = stream_get_contents($pipes[1]); + $stderr = stream_get_contents($pipes[2]); + fclose($pipes[1]); + fclose($pipes[2]); + + $case->expect(proc_close($process) === 0 && $stderr === '')->isTrue()->validate($stderr); + $case->expect($stdout)->isEqualTo( + "Report name: Use 3 to 10 characters.\nReport name: Preset (filter, or leave blank for all): " . + "Preset (1-2)\n1: Daily preview\n2: Daily archive\nInput your answer: Note: 3/3\n" . + "Sales/summary, Sales/details, Sales/totals [ keep spaces ]\n" + )->validate(); +}); + group('Command preserves named stream and output parameters', static function (TestCase $case) { $original = new Stream('php://memory'); $output = new Stream('php://memory'); From b38f4b4310d3dc0c0a0a0da253f869edd1fec9d8 Mon Sep 17 00:00:00 2001 From: Daniel Ronkainen Date: Mon, 30 Nov 2026 21:23:55 +0100 Subject: [PATCH 14/15] chore: ignore IDE project files --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index c66fb76..9797ea9 100755 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,5 @@ .DS_Store .sass-cache composer.lock -vendor \ No newline at end of file +vendor +.idea/ From 426631b97d535d7a8d0b1c35d61887a5892af0e8 Mon Sep 17 00:00:00 2001 From: Daniel Ronkainen Date: Mon, 30 Nov 2026 22:11:58 +0100 Subject: [PATCH 15/15] docs: rewrite README --- README.md | 304 ++++++++++++++++++++++++++--- docs/guide.md | 479 ---------------------------------------------- docs/migration.md | 58 ------ 3 files changed, 274 insertions(+), 567 deletions(-) delete mode 100644 docs/guide.md delete mode 100644 docs/migration.md diff --git a/README.md b/README.md index d55e7b4..7a68fb9 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,12 @@ # MaplePHP Prompts -Build PHP command-line tools with validated questions, searchable menus, hidden input, progress bars, and formatted output. Use `Command` to control the interaction step by step or `Prompt` to run a workflow such as an installer. Both support terminals and piped input. +Interactive questions, menus, and formatted output for PHP console applications. -## Installation +Use `Command` to ask questions from your own PHP code, or `Prompt` to collect a set of answers from an array of steps. Prompts works independently of the MaplePHP framework. + +[Command](#start-with-command) · [Prompt](#build-an-installer-with-prompt) · [Validation](#validation) · [Choices](#search-and-multiple-choices) · [Progress](#progress) · [ANSI](#ansi-styling) · [Reference](#command-reference) + +## Install Prompts requires PHP 8.2 or later. Install it in your application with Composer. @@ -10,11 +14,9 @@ Prompts requires PHP 8.2 or later. Install it in your application with Composer. composer require maplephp/prompts ``` -Composer installs a published release. The quickstarts and guide use the API in this checkout. To try them with the current source, run `composer install` in the package root and use the included demos or save the snippets alongside that checkout's `vendor` directory. +## Start with Command -## Quickstart with Command - -Use direct method calls when application code decides what to ask and what to print. Save this as `command.php` next to your application's `vendor` directory and run `php command.php`. +Add a question wherever your script needs an answer. Save this as `setup.php` beside your `vendor` directory and run `php setup.php`. ```php title('Export report'); +$cli = new Command(); -try { - $name = $command->ask('Report name'); - $format = $command->select('Output format', ['text' => 'Plain text', 'json' => 'JSON']); - $command->success("Selected $format for $name."); -} catch (PromptException $exception) { - $command->error($exception->getMessage()); - exit(1); -} +$name = $cli->ask('Project name'); +$database = $cli->select('Database', [ + 'sqlite' => 'SQLite', + 'mysql' => 'MySQL', + 'pgsql' => 'PostgreSQL', +]); + +$cli->success("Settings collected for $name ($database)."); ``` -Enter a report name, then choose the format. The repository demo validates the report name, confirms the chosen options, and updates a progress bar as it prepares each report section. Run it from the package root with `php examples/command.php`. [Command demo](examples/command.php) +Use the arrow keys to move and Enter to choose. Selecting **MySQL** returns `'mysql'`, the array key, so your code gets a stable value while the menu can use a readable label. + +Menus automatically offer numbered choices when arrow-key navigation is unavailable. -## Quickstart with Prompt +## Build an installer with Prompt -Define the steps and validation rules for a workflow such as an installer. Save this as `installer.php` next to your application's `vendor` directory and run `php installer.php`. +Define the questions, defaults, and validation rules in an array, then collect the answers with `prompt()`. ```php setTitle('Project installer')->set([ - 'project' => [ +$steps = [ + 'name' => [ 'message' => 'Project name', + 'default' => 'atlas', 'validate' => ['length' => [3, 40]], - 'error' => 'Enter a name with 3 to 40 characters.', + 'error' => 'Use between 3 and 40 characters.', ], - 'install' => ['type' => 'confirm', 'message' => 'Install this project?'], -]); + 'database' => [ + 'type' => 'select', + 'message' => 'Database', + 'items' => ['sqlite' => 'SQLite', 'mysql' => 'MySQL'], + ], + 'approved' => [ + 'type' => 'confirm', + 'message' => 'Create this project?', + ], +]; +$installer = (new Prompt())->setTitle('New project')->set($steps); $answers = $installer->prompt(); + if ($answers === false) { exit(1); } -$installer->getCommand()->success('Installation approved for ' . $answers['project'] . '.'); + +$installer->getCommand()->success( + "Settings approved for {$answers['name']} ({$answers['database']})." +); +``` + +Pressing Enter at the project name uses `atlas`. Choosing SQLite and answering `yes` to the confirmation produces this result. + +```php +['name' => 'atlas', 'database' => 'sqlite', 'approved' => 1] +``` + +The array keys become the keys in your answers. Invalid input repeats the question with your error message. A declined confirmation, exhausted input, or handled interrupt returns `false`. + +### Reuse the same questions + +`prompt()` consumes completed steps. To run the whole installer again, reload them with `set($steps)`. + +For definitions you want to run repeatedly or load from storage, use `runDefinition()`. + +```php +$installer = new Prompt(); +$answers = $installer->runDefinition($steps); +``` + +Each call starts from the first step. You can also load `$steps` with `json_decode($json, true)` from a file or database. Stored definitions support literal text, choices, nested arrays, and supported validation rules. The full definition is checked before any questions are asked. + +PHP callbacks belong in workflows built with `set()`. An `items` callback on a `continue` step receives the previous answer and returns follow-up steps, or `false` to skip them. For example, a MySQL choice can lead to host and password questions while SQLite skips them. Nested answers are grouped under the `continue` step’s key. + +### Question types + +| Type | Answer | +| --- | --- | +| `text` (default) | A string. A blank answer uses `default` when supplied. | +| `password`, `mask`, `invisible` | A hidden string. | +| `select`, `search` | The original key of the chosen item. | +| `multiselect` | The selected keys in definition order. `default` holds initially selected keys. | +| `list` | An array of trimmed, comma-separated strings. | +| `toggle` | `1` for yes or `0` for no. | +| `confirm` | `1` for yes. Answering no stops the workflow. | +| `continue` | Nested answers, or `true` when a callback skips the step. | +| `message` | Prints a notice without adding an answer. | + +## Validation + +The shorter examples below build on the first script, using its `$cli` instance and Composer autoloader. + +`askValidated()` keeps asking until an answer passes your rules. + +```php +$email = $cli->askValidated( + 'Administrator email', + ['isEmail' => []], + 'Please enter a valid email address.' +); +``` + +```text +Administrator email: alex +Please enter a valid email address. +Administrator email: alex@example.com +``` + +Rules come from MaplePHP Validate. Each name takes an array of arguments, so `['length' => [3, 40]]` accepts between 3 and 40 characters. Put several rules in the same map to require them all to pass. Use the same maps under a Prompt step’s `validate` field. + +For application-specific checks, pass a callback that returns `true` to accept the answer. + +```php +$slug = $cli->askValidated( + 'Project slug', + static fn (string $value): bool => preg_match('/\A[a-z0-9-]+\z/', $value) === 1, + 'Use lowercase letters, numbers, and hyphens.' +); +``` + +In a Prompt step, put that callback under `validator`. The older callable `validate` has the opposite convention, with `true` requesting a retry. Use one validation field per step. + +## Search and multiple choices + +`selectWithSearch()` filters a list as the user types. + +```php +$timezone = $cli->selectWithSearch('Timezone', [ + 'Europe/Stockholm' => 'Stockholm', + 'Europe/London' => 'London', + 'America/New_York' => 'New York', + 'America/Los_Angeles' => 'Los Angeles', +]); +``` + +Type `los` to find Los Angeles. Pressing Enter returns `'America/Los_Angeles'`. Search matches a case-insensitive, literal part of the label. Backspace edits the filter, and the arrows move through the results. A Prompt definition uses `'type' => 'search'` with the same `items` map. + +`multiSelect()` lets the user choose several items. + +```php +$features = $cli->multiSelect('Include in this project', [ + 'api' => 'API endpoints', + 'mail' => 'Email notifications', + 'reports' => 'Reports', +], defaults: ['api']); +``` + +Use Space to toggle an item and Enter to accept. The answer contains original keys such as `['api', 'reports']`. An empty selection returns `[]`. + +## Progress + +Create a bar with the amount of work to do, then call `advance()` after each item finishes. This example calculates checksums for the library’s PHP source files. + +```php +$files = glob(__DIR__ . '/vendor/maplephp/prompts/src/*.php') ?: []; +$checksums = []; +$bar = $cli->progressBar(count($files), width: 24); + +try { + foreach ($files as $file) { + $hash = hash_file('sha256', $file); + if ($hash === false) { + throw new RuntimeException("Could not read $file."); + } + $checksums[$file] = $hash; + $bar->advance(); + } +} finally { + $bar->finish(); +} +``` + +A terminal updates one line. For three files, the final line is the following. + +```text +[========================] 3/3 +``` + +Reaching the total finishes automatically. `finish()` also closes a partial bar at its actual count, such as `1/3` if work stopped after the first file. Redirected output gets one plain count line. You can advance by a batch with `advance(10)`. + +## ANSI styling + +Style a heading, highlight a choice, or give your questions a look that fits your tool. ANSI helpers return strings, so you can use them with questions and output alike. + +```php +$ansi = $cli->getAnsi(); + +$cli->line($ansi->blueBg(' ATLAS ')); +$cli->line($ansi->dim('Choose a name for your project.')); +$name = $cli->ask($ansi->cyan('Project ' . $ansi->bold('name') . ' to create')); +``` + +The question is cyan, with `name` in bold. The cyan style resumes after the bold word. You can also apply several styles at once with `$ansi->style(['bold', 'cyan'], $text)`. + +| Style | Methods | +| --- | --- | +| Text | `bold()`, `dim()`, `italic()`, `underline()`, `reverse()`, `strikethrough()` | +| Colors | `black()`, `red()`, `green()`, `yellow()`, `blue()`, `magenta()`, `cyan()`, `white()`, `grey()` | +| Bright colors | `brightBlack()`, `brightRed()`, through to `brightWhite()`. | +| Backgrounds | `redBg()`, `blueBg()`, and the corresponding variant for each base color, including bright variants. | + +`disableAnsi(true)` turns off generated styles. Text stays readable, and background labels use brackets. The example above becomes the following. + +```text +[ ATLAS ] +Choose a name for your project. +Project name to create: atlas ``` -Enter at least three characters for the project name and answer `yes` to confirm. The repository demo adds a searchable environment picker, a nested workflow, list validation, and hidden input. Run it from the package root with `php examples/example.php`. [Prompt demo](examples/example.php) +Passing `false` restores automatic detection. Style detection uses `TERM` and the OS. For cursor movement in a custom renderer, check `$cli->hasCursorOutput()` first. + +## Tables and help text + +`Blocks` writes aligned tables and help sections through your command. + +```php +use MaplePHP\Prompts\Themes\Blocks; + +$blocks = new Blocks($cli); +$blocks->table(['Setting', 'Value'], [ + ['Project', 'atlas'], + ['Database', 'SQLite'], +]); +``` + +```text +Setting Value +Project atlas +Database SQLite +``` + +Colors and multibyte text are accounted for when aligning columns. `addSection()` groups help text, `addOption()` describes a flag, and `addExample()` adds a usage example. Chain `addOption()` and `addExample()` inside a section callback and return the resulting builder. `addCode($php)` prints a PHP snippet with syntax highlighting. + +For a custom menu, use `Navigation::navigate($message, $items, $renderer)`. The renderer receives the focused index and ordered labels. Print one short line per choice so the menu can redraw in place. After selection, `getValue()` returns the original key and `getItem()` returns its label. + +## Terminals, pipes, and input handling + +Arrow-key menus use Unix terminal controls. Windows, piped input, and redirected output use numbered choices. Search reads a filter line followed by a choice number. Multi-select accepts comma-separated numbers, a blank line for defaults, or `none` to clear the selection. + +`Command` reads stdin and writes stdout by default. To send questions to stderr while leaving stdout for your application’s data, configure its output stream. + +```php +use MaplePHP\Http\Stream; + +$cli = new Command(stream: new Stream(STDERR)); +``` + +The constructor also accepts a separate PSR-7 stream as `input`, so tests can supply answers and capture output. Pass your command to `new Prompt($cli)` to use those streams throughout a workflow. + +`ask()` preserves surrounding whitespace and returns `''` for a blank line. `mask()` reads hidden input, using Unix terminal controls or PowerShell on a native Windows console. + +Direct questions throw `InputExhaustedException` at the end of input. Raw menus and masked reads report a handled interrupt as `InputInterruptedException`. Both extend `MaplePHP\Prompts\Exceptions\PromptException`. Catch that exception at your script’s entry point to choose your message and exit status. Workflows return `false` for either outcome. + +## Command reference + +| Method | Result or purpose | +| --- | --- | +| `ask($message)`, `readline($message)` | Read a string, preserving whitespace. | +| `askValidated($message, $validator, $error = 'Please try again.')` | Retry until a rule map or callback accepts the answer. | +| `mask($message)` | Read hidden input. | +| `list($message)` | Return trimmed, comma-separated strings. | +| `select($message, $items)` | Return one original choice key. | +| `selectWithSearch($message, $items)` | Search labels and return one original key. Labels must be nonempty printable single-line UTF-8 strings. | +| `multiSelect($message, $items, $defaults = [])` | Return unique selected keys in definition order. | +| `inputSelect($message, $choices)` | Always use numbered input. | +| `toggle($message)`, `inputToggle($message)` | Return `1` or `0`. `inputToggle()` always reads `yes` or `no`. | +| `confirm($message)` | Read `yes` or `no` and return a boolean. | +| `line($message = '', $break = true)` | Print text or a blank line. Pass `false` to omit the newline. | +| `title()`, `status()`, `success()`, `warning()`, `error()` | Print a heading, status, success, warning, or error. `error()` returns `false`; the others return `void`. | +| `progressBar($total, $width = 40)` | Create a bar controlled by `advance()` and `finish()`. | +| `progress($expectedRows, $maxLength = 100, $sleep = null)` | Play a fixed-length progress animation. | +| `withStream($stream)` | Return a copy with different output and the same input. | +| `getStream()`, `getInput()`, `getAnsi()` | Access output, input, and styling. | +| `hasTerminalInput()`, `hasCursorOutput()`, `supportsNavigation()` | Check terminal capabilities. | +| `getStty()` | Access low-level Unix terminal controls. | + +Existing `message()`, `approve()`, and `statusMsg()` calls remain available. `message($text)` prints and returns `false`; `message($text, true)` asks a question. `approve()` and `statusMsg()` return `false`; their newer counterparts are `success()` and `status()`. + +## Try the examples + +From a checkout with dependencies installed, run `php examples/command.php` for a report export, or `php examples/example.php` for an installer with hidden input, validation, and nested questions. -## Documentation +## License -- [Package guide](docs/guide.md) includes recipes for validation, search, work-driven progress, and custom prompts, followed by the Command and workflow references. -- [Migrating from Prompts 1.x](docs/migration.md) lists method replacements and behavior to check when upgrading. +Apache License 2.0. \ No newline at end of file diff --git a/docs/guide.md b/docs/guide.md deleted file mode 100644 index 5bdec23..0000000 --- a/docs/guide.md +++ /dev/null @@ -1,479 +0,0 @@ -# Prompts guide - -## Ask a question with Command - -Save this as `command.php` next to your project's `vendor` directory. Run `TERM=dumb php command.php` in a terminal to try the numbered menu shown below. On Windows, run `php command.php`. The examples use the API in this checkout. See the [installation instructions](../README.md#installation) to try it locally. - -```php -title('Export report'); - -try { - $name = $command->ask('Report name'); - $format = $command->select('Output format', ['text' => 'Plain text', 'json' => 'JSON']); - $command->success("Selected $format for $name."); -} catch (PromptException $exception) { - $command->error($exception->getMessage()); - exit(1); -} -``` - -```text -Export report -Report name: Quarterly sales -Output format (1-2) -1: Plain text -2: JSON -Input your answer: 2 -Selected json for Quarterly sales. -``` - -`select()` returns the original array key, so choosing the second row gives you `json`. In a terminal with cursor navigation, use the arrows and Enter instead of entering a number. - -## Collect installer settings with Prompt - -Use `Prompt` when an array can describe the questions and control when to proceed. Save this as `installer.php` and run `php installer.php`. Try `ab` to see validation retry, then enter `Maple` and answer `yes` to approve the settings. Answering `no` ends the workflow and returns `false`. - -```php -setTitle('Project installer')->set([ - 'project' => [ - 'message' => 'Project name', - 'validate' => ['length' => [3, 40]], - 'error' => 'Enter a name with 3 to 40 characters.', - ], - 'install' => ['type' => 'confirm', 'message' => 'Install this project?'], -]); - -$answers = $installer->prompt(); -if ($answers === false) { - exit(1); -} -$installer->getCommand()->success('Installation approved for ' . $answers['project'] . '.'); -``` - -[Validation](#validate-a-direct-answer) · [Search](#search-a-list-of-choices) · [Progress](#track-work-as-it-completes) · [Formatted output](#formatted-output) · [Command reference](#command-input-and-output) · [Workflow rows](#row-options) - -## Validate a direct answer - -Use `askValidated()` to retry a question until it passes. A rule map uses the same [rules and arguments](#stored-rule-reference) as a stored workflow and is checked before the prompt reads input. For an application-specific check, pass a trusted PHP callable that receives the exact string entered. Return `true` to accept or `false` to show the error and ask again. - -Save this as `validate.php` and run `php validate.php`. Try `me` before `avery@example.com` and `Sales 2027` before `sales-2027`. - -```php -askValidated('Contact email', ['isEmail' => []], 'Enter an email address.'); -$slug = $command->askValidated( - 'Workspace slug', - static fn (string $value): bool => preg_match('/\A[a-z0-9-]+\z/', $value) === 1, - 'Use lowercase letters, digits, or hyphens.' -); -$command->success("Workspace $slug will use $email."); -``` - -## Search a list of choices - -Save this as `search.php` and run `php search.php` in a terminal with cursor navigation. Type `customer` to filter, use Backspace to edit, move with Up or Down, and press Enter to select. The menu shows up to eight matches at a time and scrolls as you move. Search matches a case-insensitive, literal substring of a label and keeps the original keys and order, including choices that share a label. - -```php -selectWithSearch('Choose a dataset', [ - 'sales' => 'Sales totals', - 'customer-activity' => 'Customer activity', - 'customer-totals' => 'Customer totals', -]); -$command->line("Dataset key: $dataset"); -``` - -With piped input, the first line is the filter and the second is a one-based position among the matches. A blank filter shows all choices. If nothing matches, enter a new filter. This pipe selects `customer-totals`. - -```sh -printf 'customer\n2\n' | TERM=dumb php search.php -``` - -```text -Choose a dataset (filter, or leave blank for all): Choose a dataset (1-2) -1: Customer activity -2: Customer totals -Input your answer: Dataset key: customer-totals -``` - -## Stored workflow definitions - -Use a `search` row to offer the same interaction in a workflow loaded from JSON. Save this definition as `setup.json`. It also shows how to combine validation rules and use `continue` for nested questions. - -```json -{ - "contact": { - "message": "Email address or five-digit PIN", - "validate": { - "oneOf": [{ - "isEmail": [], - "allOf": [{"isMatchingPattern": ["0-9"], "length": [5, 5]}] - }] - }, - "error": "Enter an email address or a five-digit PIN." - }, - "dataset": { - "type": "search", - "message": "Choose a dataset", - "items": { - "sales": "Sales totals", - "customer-activity": "Customer activity", - "customer-totals": "Customer totals" - } - }, - "details": { - "type": "continue", - "items": { - "date": {"message": "Start date", "validate": {"isDate": ["d/m/Y"]}, "error": "Use DD/MM/YYYY."}, - "confirm": {"type": "confirm", "message": "Save these settings?"} - } - } -} -``` - -Save this as `stored.php` beside `setup.json` and run `php stored.php`. Enter `12345`, search for `customer` and select Customer totals, then enter `05/03/2027` and `yes`. For numbered input, supply `customer` and `2` on separate lines. - -```php -setTitle('Setup'); -$answers = $prompt->runDefinition($definition); -if ($answers === false) { - exit(1); -} -$prompt->getCommand()->success('Setup approved for ' . $answers['dataset'] . ' on ' . $answers['details']['date'] . '.'); -``` - -Each `runDefinition()` call checks the full definition before interacting and starts from the first row. Application code can use the answers when the run succeeds. See the [stored definition reference](#stored-definition-reference) for accepted data. - -## Nested rows and callbacks - -A `continue` row reuses the parent command and suppresses the nested header. In trusted PHP, an `items` callable receives the preceding accepted value and the current zero-based row index. A nested decline also aborts the parent workflow. - -Save this as `database.php`. Answer `yes`, provide a host, and confirm with `yes` to see the nested host in the summary. - -```php -set([ - 'remote' => ['type' => 'toggle', 'message' => 'Use a remote database?'], - 'database' => [ - 'type' => 'continue', - 'items' => static fn (int $remote, int $index): array|false => $remote === 1 ? [ - 'host' => [ - 'message' => 'Database host', - 'validator' => static fn (string $host): bool => strlen($host) >= 3, - 'error' => 'Enter at least three characters.', - ], - 'connect' => ['type' => 'confirm', 'message' => 'Use this host?'], - ] : false, - ], -]); - -$answers = $prompt->prompt(); -if ($answers === false) { - exit(1); -} -$prompt->getCommand()->line($answers['database']['host'] ?? 'Using the local database.'); -``` - -## Track work as it completes - -Save this as `progress.php` and run `php progress.php report.csv`. It creates a new CSV file and advances the bar after each successful write. Choose a fresh output filename for each run. - -```php -progressBar(count($rows), width: 12); -try { - foreach ($rows as $row) { - if (fputcsv($file, $row, escape: '') === false) { - throw new RuntimeException('Could not write the report.'); - } - $bar->advance(); - } -} finally { - fclose($file); - $bar->finish(); -} -``` - -A cursor-capable terminal updates the same line from `0/3` through `[============] 3/3`. Reaching the total finishes the bar automatically. If a write fails after one row, `finish()` ends the line at `1/3`. When output is redirected or cursor controls are unavailable, the bar writes just the final `done/total` line. For example, `php progress.php another-report.csv > progress.log` writes the following to the log. - -```text -3/3 -``` - -## Formatted output - -### Design a prompt with ANSI styles - -Use styled spans to make the current action and settings easier to scan. Here `reverse()` marks the `EXPORT` label inside a blue background that resumes for `Report settings`. `dim()` de-emphasizes the hint, `underline()` marks the current format, and `strikethrough()` marks the retired format. The words `current` and `retired` carry the same meaning in plain output. - -Save this as `report-prompt.php`. In an ANSI-capable Unix terminal, run `TERM=xterm-256color php report-prompt.php` to see the styles. Run `php report-prompt.php --plain` to see the plain version below. - -```php -getAnsi(); -if (in_array('--plain', $argv, true)) { - $ansi->disableAnsi(true); -} - -$command->line($ansi->blueBg($ansi->reverse('EXPORT') . ' Report settings')); -$command->line($ansi->dim('The report includes the selected sections.')); -$command->line('Format: ' . $ansi->underline('JSON') . ' (current), ' . $ansi->strikethrough('XML') . ' (retired)'); -$name = $command->ask($ansi->bold('Report name')); -$command->success("Ready to export $name."); -``` - -```text -[EXPORT Report settings] -The report includes the selected sections. -Format: JSON (current), XML (retired) -Report name: Quarterly sales -Ready to export Quarterly sales. -``` - -To style an entire string, you can also pass a style name or an ordered list of names to `style()`, for example `style(['bold', 'blue'], $text)`. - -### Write help with Blocks - -Use `Blocks` to build help sections, show examples, and align tables through the same command output. Save this as `help.php` and run `php help.php`. - -```php -addHeadline('Export help'); -$blocks->addSection('Usage', static fn (Blocks $section): Blocks => $section - ->addOption('--format', 'Choose an output format') - ->addExample('report --format=json', 'Export a JSON report')); -$blocks->table(['Format', 'Description'], [['text', 'Plain text'], ['json', 'JSON']]); -$blocks->addCode('$command->status("Preparing report");'); -``` - -A section can use a literal description or a callback. Return the builder from a callback to display its options, list entries, or examples. `addOption()`, `addList()`, and `addExample()` return a new builder, so chain the calls or reassign the result. `addCode()` prints the source with PHP token styles when ANSI and the tokenizer are available. - -`table($headers, $rows)` takes a non-empty list of column headings and a list of rows with one cell per heading. Cells are scalars or stringable objects with single-line, printable UTF-8 text. Empty rows print only the headings. ANSI text styles are preserved without taking up columns. Wide characters and combining marks are accounted for, and emoji widths can vary by terminal. - -### Custom navigation - -Use `Navigation::navigate()` to decide how a menu looks. The callback receives the zero-based highlighted index and the ordered labels. Here the highlighted row uses reverse video and starts with `>`, so focus remains visible in plain output. Save this as `menu.php` and run `php menu.php`. - -```php -setHelperText(Navigation::HELPER_TEXT); -$navigation->navigate('Choose a format', ['text' => 'Plain text', 'json' => 'JSON'], - static function (int $current, array $labels) use ($command): void { - foreach ($labels as $index => $label) { - $command->line($current === $index - ? $command->getAnsi()->reverse("> $label") - : " $label"); - } - } -); -$command->success('Selected ' . $navigation->getItem()); -``` - -Print one terminal row per item and keep labels short enough to avoid wrapping. Cursor navigation moves up by a relative row count before redrawing. Numbered fallback calls the renderer before displaying the numbered choices and again if the chosen index changes. After acceptance, `getValue()` returns the original choice key and `getItem()` returns its label. `setAcceptKey()` changes the terminal acceptance key from Enter. - -## Command input and output - -### Streams and capabilities - -| Method | Behavior | -| --- | --- | -| `new Command($stream = null, $input = null)` | Defaults to stdout for output and stdin for input. A PSR-7 response supplies its body as the output stream. Pass a PSR-7 stream such as `new MaplePHP\Http\Stream(STDERR)` to write prompts to stderr. | -| `withStream($stream)` | Returns a copy with a different PSR-7 output stream and the same input. | -| `getStream()`, `getInput()` | Return the configured PSR-7 output and input streams, respectively. | -| `getAnsi()` | Returns the `Ansi` instance for styling strings and building terminal controls. | -| `hasTerminalInput()` | Checks whether input uses the process's stdin terminal. | -| `hasCursorOutput()` | Checks whether the configured output can receive cursor controls. | -| `supportsNavigation()` | Checks whether input, output, and Unix terminal controls can support cursor-based navigation. | -| `getStty()` | Returns the `SttyWrapper` for low-level Unix terminal settings. | - -Pass your configured command to `new Prompt($command)` to use those streams for the full workflow, including nested prompts. - -### Questions and choices - -| Method | Result | -| --- | --- | -| `ask($message)`, `readline($message)` | Read a string. An empty line returns `''`. Leading and trailing whitespace are preserved. `readline()` also backs `ask()`. | -| `askValidated($message, $validator, $error = 'Please try again.')` | Returns the accepted string after a rule map or trusted boolean callback passes it. | -| `mask($message)` | Reads a string without echoing terminal input. Use it for passwords. | -| `list($message)` | Returns trimmed strings split on commas. Blank entries remain as `''`. | -| `select($message, $items)` | Returns the chosen `int` or `string` key from a non-empty array. | -| `selectWithSearch($message, $items)` | Filters choices by label and returns the original key. Labels must be non-empty, printable, single-line UTF-8 strings. | -| `inputSelect($message, $choices)` | Always reads a numbered choice and returns the original key. | -| `multiSelect($message, $items, $defaults = [])` | Returns unique original choice keys in declaration order. Defaults are original keys. | -| `toggle($message)`, `inputToggle($message)` | Return integer `1` for yes or `0` for no. `inputToggle()` always reads `yes` or `no` as text. | -| `confirm($message)` | Reads `yes` or `no` and returns a boolean. | - -### Messages and progress - -The message methods listed with `$break` write a newline by default. Pass `false` to omit the newline. - -| Method | Behavior | -| --- | --- | -| `line($message = '', $break = true)` | Writes a line and returns `void`. Call with no arguments to print a blank line. | -| `title($message, $break = true)` | Writes a bold heading and returns `void`. | -| `success($message, $break = true)`, `status($message, $break = true)`, `warning($message, $break = true)` | Write a green, blue, or yellow message and return `void`. | -| `error($message, $break = true)` | Writes a red error to the configured output and returns `false`. | -| `progressBar($total, $width = 40)` | Creates a `ProgressBar`. Call `advance($steps = 1)` after work completes and `finish()` to end the display at its current count. | -| `progress($expectedRows, $maxLength = 100, $sleep = null)` | Runs a fixed-length animation and returns `void`. | - -`progressBar()` requires a non-negative total and a positive width. `advance()` rejects negative steps, ignores zero and caps the count at the total. A zero total finishes immediately as `0/0`. Once finished, further advances and repeated `finish()` calls produce no output. - -`progress()` writes `$maxLength` cells and a newline when both dimensions are positive. Either dimension can be zero to write a blank line. Negative dimensions throw `InvalidArgumentException`. The optional delay is in milliseconds. A delay callback runs once per cell and receives `($i, $length)` using the original scale. For scale `min($expectedRows, $maxLength) / max($expectedRows, $maxLength)`, `$i` is the zero-based frame times the scale and `$length` is `($maxLength - 0.5)` times the scale. The callback can return a positive integer delay or `0` to continue immediately. - -### Supported legacy names - -| Method | Behavior | -| --- | --- | -| `message($message, $getLine = false)` | Writes a line and returns `false` by default. With `$getLine` set to `true`, it asks a question and returns a string. Use `line()` and `ask()` in new code. | -| `approve($message, $break = true)` | Writes a success message and returns `false`. Use `success()` in new code. | -| `statusMsg($message, $break = true)` | Writes a status message and returns `false`. Use `status()` in new code. | - -See the [migration notes](migration.md) for additional aliases and upgrade details. - -### Terminals, pipes, and end of input - -- Arrow-key menus require terminal stdin, cursor-capable output, and usable Unix `stty`. Use Up and Down to move and Enter to accept. In a multi-select menu, Space toggles the current choice. Search also uses numbered input when the terminal is too small to display its live menu. -- With a pipe, redirected output, plain terminal settings, or Windows, a single choice uses one-based positions. Search first reads a filter line. A multi-select accepts comma-separated positions, a blank line to keep the defaults, or `none` to clear them. Invalid positions retry. The selected values are the original keys, including integer `0`. -- Masked input uses `stty` on a supported Unix stdin terminal and PowerShell on a native Windows stdin console. For injected input, use a recognized stdin terminal or a genuinely non-echoing source such as a pipe or memory stream. The caller controls whether a custom PSR stream echoes input. Recognized terminals that cannot be masked raise `PromptException`. The package's Windows CI job exercises redirected input. -- Direct reads and `promptLine()` throw `InputExhaustedException` if no answer remains. A final non-empty line without a newline still counts as an answer, and a blank line can apply a default. Raw terminal menus and masked reads report a handled Ctrl+C as `InputInterruptedException`. Both exceptions extend `PromptException`. `prompt()` and `runDefinition()` return `false` for either exception. Other input failures, such as failure to configure masked entry, can still throw `PromptException`. -- `getAnsi()->disableAnsi(true)` disables generated ANSI styling and cursor navigation. Passing `false` restores automatic detection. Detection uses `TERM` and the OS. A redirected stream can still receive text styles when `TERM` indicates ANSI support. Check `hasCursorOutput()` before writing cursor controls or set `TERM=dumb` for plain output. - -## Trusted PHP workflows - -`Prompt::set($rows)` replaces the queue, `add($name, $row)` adds or replaces one row, and `promptLine($row)` asks one question directly without consuming the queue. `getCommand()` returns the workflow command. `setTitle()` and `setDescription()` customize the header. `disableHeaderInfo(true)` hides the header and its keyboard hint. - -Call `prompt()` to process queued rows in declaration order and get answers keyed by row name. Successful rows are removed as the run advances. If a confirmation is declined, EOF occurs, or input is interrupted, the run returns `false` and discards its partial results. A subsequent call on the same `Prompt` resumes at the first unfinished row using the available input and returns answers for the remaining rows. If a nested workflow aborts, its `continue` row stays queued and starts over when resumed. Call `set($rows)` again to repeat the full sequence, or use `runDefinition()` for a data-only workflow that starts fresh on every call. - -### Row options - -| Key | Use | -| --- | --- | -| `type` | One of the types below, with `text` as the default. | -| `message` | The prompt or notice to display. Required except on `continue`. | -| `default` | A replacement for an empty text or masked answer. For `multiselect`, use a list of original choice keys. Defaults on masked input stay hidden. | -| `items` | A choice map for `select`, `search`, or `multiselect`, or nested rows for `continue`. In trusted PHP a `continue` row also accepts a callable. | -| `validate` | A rule map such as `['length' => [3, 40], 'isEmail' => []]` or a legacy callable in trusted PHP. | -| `validator` | A trusted PHP callable. Return `true` to accept or `false` to retry. Use either `validator` or `validate` on a row. | -| `error` | A string to print on a failed validation attempt, or a trusted PHP callable taking `($rule, $input, $row)` and returning a string. The rule is `null` for callback validation. | -| `confirm` | A message printed after successful validation. On a `confirm` row it prints only after `yes`. | - -| `type` | Value returned in the workflow | -| --- | --- | -| `text` | The typed string or its default. | -| `password`, `mask`, `invisible` | The hidden answer or its default. | -| `list` | An array of trimmed comma-separated strings. | -| `select`, `search` | The original choice key. Search filters by label before selection. | -| `multiselect` | A list of selected keys in declaration order. A top-level `required` or `isRequired` rule requires at least one selection and accepts a key of `0`. | -| `toggle` | Integer `1` or `0`. | -| `confirm` | Integer `1` for yes. A no aborts the workflow. | -| `continue` | An array of nested answers. A trusted `items` callback can return `false` to skip its nested questions, recording `true` for the row. | -| `message` | Displays text without adding an answer. | - -Text `0` and the integer choice key `0` count as answers. For workflows that handle passwords, read the masked field from the result only where it is needed and omit it from summaries. - -## Stored definition reference - -`runDefinition(array $steps)` checks all rows, nested `items`, defaults, and rule arguments before writing a prompt or reading input. On invalid data it throws `InvalidArgumentException`. Each call starts with fresh rows and shares the configured command and header. The trusted queue set with `set()` and `add()` remains independent. - -Store an object keyed by row name. Use scalar values, `null`, and arrays or objects that decode to PHP arrays. `items` on `continue` contains more named rows. `items` on selections is a non-empty map of keys to string labels. Search requires non-empty, printable, single-line UTF-8 labels. A text or masked `default` must be scalar or `null`. A multiselect `default` must be a list of existing choice keys with matching types. Use strings for `message`, `error`, and `confirm`. `validate` accepts only rule maps from the allowlist, and `message` rows only display text. PHP callables, arbitrary validation methods, DNS or file rules, and unknown fields are rejected. - -### Validation maps - -A validation map keys each rule by name and provides an array of arguments in parameter order. Use `[]` for rules with no arguments. Top-level rules all need to pass. `oneOf` and `allOf` take one nested rule map, so the map must appear inside the argument array, as in `['oneOf' => [['isEmail' => [], 'isUrl' => []]]]`. `oneOf` passes if any nested rule passes and `allOf` passes if every nested rule passes. An empty `oneOf` fails and an empty `allOf` passes. - -For array answers such as a comma-separated list or multi-select, rules and callable validators run on each item or choice key. The top-level multiselect required rule checks the selection as a whole. Trusted rule maps pass each value as a string to MaplePHP Validate. Stored rule maps check the typed value, so a strict comparison to `0` matches an integer key, while a comparison to `'0'` matches text input. In trusted PHP, a callable in `validate` uses the legacy polarity of `true` for retry and `false` for accept. Both callable forms must return a boolean. - -### Stored rule reference - -The names in either column below are accepted in a stored definition, including inside `oneOf` and `allOf`. - -| Canonical rules | Aliases | Positional arguments | -| --- | --- | --- | -| `isRequired`, `isEmail`, `isNumber`, `isUrl`, `isPhone` | `required`, `email`, `number`, `url`, `phone` | `[]` | -| `isBool`, `isBoolVal`, `isFloat`, `isInt`, `isPositive`, `isNegative` | `bool`, `boolVal`, `float`, `int`, `positive`, `negative` | `[]` | -| `isTrue`, `isFalse`, `isTruthy`, `isFalsy`, `isArray`, `isObject` | | `[]` | -| `isHexColor`, `isString`, `isAlpha`, `isLowerAlpha`, `isUpperAlpha` | `hex`, `string`, `atoZ`, `lowerAtoZ`, `upperAtoZ` | `[]` | -| `length`, `isZip` | `zip` for `isZip` | `[minimum]` or `[minimum, maximum]`. Non-negative integers, with an optional `null` maximum and any numeric maximum at least the minimum. | -| `min`, `max` | | `[limit]` as a finite number. | -| `isAge`, `isLengthEqualTo` | `age`, `equalLength` | `[minimumAge]` or `[length]` respectively, as a non-negative integer. | -| `isLossyPassword`, `isStrictPassword` | `lossyPassword`, `strictPassword` | `[]` or `[length]` as an integer from 0 to 65535. | -| `isDate`, `isDateWithTime` | `date`, `dateTime` | `[]` or `[format]` as a non-empty date format string. The defaults are `Y-m-d` and `Y-m-d H:i:s`. | -| `isValidVersion`, `isDomain` | `validVersion`, `domain` | `[]` or `[strict]` as a boolean. Strict mode is off for versions and on for domains by default. Domain validation checks syntax. | -| `versionCompare` | | `[version]` or `[version, operator]`, both strings. Operators are `!=`, `<`, `<=`, `<>`, `=`, `==`, `>`, `>=`, `eq`, `ge`, `gt`, `le`, `lt`, `ne`. The default is `==`. | -| `isEqualTo`, `isNotEqualTo` | `equal`, `notEqual` | `[expected]` as a scalar or `null`, compared strictly. | -| `isMatchingPattern` | `pregMatch` | `[range]`, a character-class contents string such as `'A-Z0-9'`. | -| `oneOf`, `allOf` | | `[ruleMap]`, recursively subject to the same rules and argument checks. | - -For trusted workflows, use `isDate` with an explicit format for dates and date-times, and `isValidVersion` for versions. These canonical methods are available at the package's Validate 2.0.0 floor, including when nested in a trusted `oneOf` or `allOf` rule. diff --git a/docs/migration.md b/docs/migration.md deleted file mode 100644 index 57c4fbe..0000000 --- a/docs/migration.md +++ /dev/null @@ -1,58 +0,0 @@ -# Migrating from Prompts 1.x - -The existing `Command` entry points remain available. Replace legacy names when updating a script, and check any code that uses their return values. - -| Legacy call | Current call | Return behavior | -| --- | --- | --- | -| `Command::message($message, true)` | `Command::ask($message)` | Both return a string. `readline()` remains available and backs `ask()`. | -| `Command::message($message)` or `message($message, false)` | `Command::line($message)` | Legacy returns `false`. `line()` returns `void`. | -| `Command::approve($message, $break)` | `Command::success($message, $break)` | Legacy returns `false`. `success()` returns `void`. | -| `Command::statusMsg($message, $break)` | `Command::status($message, $break)` | Legacy returns `false`. `status()` returns `void`. | -| `Navigation::navigation($message, $items, $call)` | `Navigation::navigate($message, $items, $call)` | Both return `void`. Read the selection with `getValue()` or `getItem()`. | -| `Blocks::addExamples($example, $description)` | `Blocks::addExample($example, $description)` | Both return a new `Blocks` builder. Keep the returned builder or chain the call. | -| `Ansi::moveCursorTo($line)` | `Ansi::cursorUp($lines)` | Both return a relative upward cursor sequence as a string. Check `Command::hasCursorOutput()` before writing it. | - -`Command::error()` still returns `false`. Use `warning()` for yellow output. - -## Validators and row definitions - -Keep callable `validate` entries in trusted PHP if they already return `true` to reject an answer. When moving to `validator`, invert that condition to make `true` accept the value. For example, a legacy `validate` callback returning `strlen($value) < 3` becomes a `validator` callback returning `strlen($value) >= 3`. Use one validation field per row. Validation rule maps continue to use `validate`, including `oneOf` and `allOf` with one nested map argument each. An unknown prompt type now throws `InvalidArgumentException`. - -Use `isDate` with an explicit format and `isValidVersion` when calling Validate 2.0.0–2.0.2 directly or from a trusted composite rule. Prompts handles the legacy `date`, `dateTime`, `isDateWithTime`, and `validVersion` forms when used as top-level rules and in stored maps. For example, use `['isDate' => ['Y-m-d H:i']]` for a date and time without seconds, or `['isValidVersion' => [true]]` for strict version validation. - -Use `set()` and `prompt()` for trusted PHP workflows that depend on custom validators, callable errors, or callable nested `items`. Use `runDefinition()` for replayable data from storage, with static nested `continue` rows and the supported rule maps. Convert callback-based rules to allowlisted rules where possible and keep application-specific checks in trusted code. The [package guide](guide.md#stored-workflow-definitions) includes a JSON example and the complete argument reference. - -## Streams and workflow outcomes - -`new Command($stream, $input)` uses `$stream` for output and `$input` for input. `withStream()` changes output on the returned command. Pass that command to `Prompt` to use those endpoints for nested prompts as well. - -Check for `false` before using a workflow result. A declined confirmation, handled interrupt, or EOF returns `false` from `prompt()` or `runDefinition()`. A direct read raises the corresponding input exception. An empty line can still select a default. `prompt()` retains unfinished rows for a later call and returns only that call's answers. Reload the rows with `set()` to repeat the sequence. `runDefinition()` begins at the first row each time. - -Selections can now use numbered input when cursor navigation is unavailable. In automated input, supply one-based positions using digits only and keep reading original choice keys from the result. A value such as `1x` retries the question. For a custom `Navigation` renderer, print one terminal row per item so relative cursor movement redraws the right lines. A recognized live terminal that cannot disable echo raises `PromptException` for masked input. - -## Direct validation, search, and progress - -- Use `askValidated()` when a direct question should retry on validation failure. Its trusted callback returns `true` to accept, matching the trusted workflow `validator` field. [Validation recipe](guide.md#validate-a-direct-answer) -- Use `selectWithSearch()` or the `search` row type when users need to filter choices. Update piped answers to supply the filter line first, then the numbered choice. The result is still the original key. [Search recipe](guide.md#search-a-list-of-choices) -- Use `progressBar($total)` when work determines the count. Call `advance()` after a completed operation and `finish()` if work stops early. For redirected output, expect a single `done/total` line. The existing `progress()` method still runs its fixed-length animation. [Progress recipe](guide.md#track-work-as-it-completes) - -## Section callbacks - -`Blocks::addSection()` prints string descriptions literally, including strings that name functions or static methods. If a function name came from trusted PHP, wrap it with `Closure::fromCallable()` to invoke it as a section callback. Save and run this example from a project with the package installed. - -```php -addExample('report --format=json', 'Write a JSON report'); -} - -$blocks = new Blocks(new Command()); -$blocks->addSection('Examples', Closure::fromCallable('reportHelp')); -```