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/.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/ diff --git a/README.md b/README.md index 2d71574..7a68fb9 100644 --- a/README.md +++ b/README.md @@ -1,505 +1,318 @@ # 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. +Interactive questions, menus, and formatted output for PHP console applications. -![Prompt demo](http://wazabii.se/github-assets/maplephp-prompt-v2.gif) +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. -_Note that the prompt may not look as polished on Windows as on Unix, but it will work just as well._ +[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) -### Table of Contents -- [Installation](#installation) -- [Usage Example](#usage-example) -- [Available Options](#available-options) -- [Available Prompt Types](#available-prompt-types) -- [Command instance](#command-instance) -- [Progress Bar](#progress-bar) -- [Validation](#validation-and-error-handling) +## Install -## Installation +Prompts requires PHP 8.2 or later. Install it in your application with Composer. -To install PHP Prompts, use Composer: - -```bash +```sh composer require maplephp/prompts ``` -## Usage Example +## Start with Command + +Add a question wherever your script needs an answer. Save this as `setup.php` beside your `vendor` directory and run `php setup.php`. + +```php +ask('Project name'); +$database = $cli->select('Database', [ + 'sqlite' => 'SQLite', + 'mysql' => 'MySQL', + 'pgsql' => 'PostgreSQL', +]); -1. **Initialize** +$cli->success("Settings collected for $name ($database)."); +``` + +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. + +## Build an installer with Prompt + +Define the questions, defaults, and validation rules in an array, then collect the answers with `prompt()`. ```php -$prompt = new \MaplePHP\Prompts\Prompt(); + [ + 'message' => 'Project name', + 'default' => 'atlas', + 'validate' => ['length' => [3, 40]], + 'error' => 'Use between 3 and 40 characters.', + ], + '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( + "Settings approved for {$answers['name']} ({$answers['database']})." +); ``` -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"]` - -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; - } - ``` - -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. +Pressing Enter at the project name uses `atlas`. Choosing SQLite and answering `yes` to the confirmation produces this result. ```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"); - -// Print messages -$command->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"); +['name' => 'atlas', 'database' => 'sqlite', 'approved' => 1] ``` -## Progress Bar +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`. -The `progress` method of the `Command` class allows displaying a progress bar with customizable sleep intervals to indicate ongoing operations. +### 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 -$command = new \MaplePHP\Prompts\Command(); -$command->progress(1, 100, function($i, $length) { - return 20; -}); +$installer = new Prompt(); +$answers = $installer->runDefinition($steps); ``` -## Validation and Error Handling +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. -Each prompt can have validation rules and custom error messages. Validation can be defined using built-in rules (e.g., length, email) or custom functions. Errors can be specified as static messages or dynamic functions based on the error type. +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. -### Validation List +### Question types -1. **required** - - **Description**: Checks if the value is not empty (e.g., not `""`, `0`, `NULL`). - - **Usage**: `"required" => []` +| 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. | -2. **length** - - **Description**: Checks if the string length is between a specified start and end length. - - **Usage**: `"length" => [1, 200]` +## Validation -3. **email** - - **Description**: Validates email addresses. - - **Usage**: `"email" => []` +The shorter examples below build on the first script, using its `$cli` instance and Composer autoloader. -4. **number** - - **Description**: Checks if the value is numeric. - - **Usage**: `"number" => []` +`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 +``` -5. **min** - - **Description**: Checks if the value is greater than or equal to a specified minimum. - - **Usage**: `"min" => [10]` +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. -6. **max** - - **Description**: Checks if the value is less than or equal to a specified maximum. - - **Usage**: `"max" => [100]` +For application-specific checks, pass a callback that returns `true` to accept the answer. -7. **url** - - **Description**: Checks if the value is a valid URL (http|https is required). - - **Usage**: `"url" => []` +```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.' +); +``` -8. **phone** - - **Description**: Validates phone numbers. - - **Usage**: `"phone" => []` +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. -9. **date** - - **Description**: Checks if the value is a valid date with the specified format. - - **Usage**: `"date" => ["Y-m-d"]` +## Search and multiple choices -10. **dateTime** - - **Description**: Checks if the value is a valid date and time with the specified format. - - **Usage**: `"dateTime" => ["Y-m-d H:i"]` +`selectWithSearch()` filters a list as the user types. -11. **bool** - - **Description**: Checks if the value is a boolean. - - **Usage**: `"bool" => []` +```php +$timezone = $cli->selectWithSearch('Timezone', [ + 'Europe/Stockholm' => 'Stockholm', + 'Europe/London' => 'London', + 'America/New_York' => 'New York', + 'America/Los_Angeles' => 'Los Angeles', +]); +``` -12. **oneOf** - - **Description**: Validates if one of the provided conditions is met. - - **Usage**: `"oneOf" => [["length", [1, 200]], "email"]` +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. -13. **allOf** - - **Description**: Validates if all of the provided conditions are met. - - **Usage**: `"allOf" => [["length", [1, 200]], "email"]` +`multiSelect()` lets the user choose several items. -14. **float** - - **Description**: Checks if the value is a float. - - **Usage**: `"float" => []` +```php +$features = $cli->multiSelect('Include in this project', [ + 'api' => 'API endpoints', + 'mail' => 'Email notifications', + 'reports' => 'Reports', +], defaults: ['api']); +``` -15. **int** - - **Description**: Checks if the value is an integer. - - **Usage**: `"int" => []` +Use Space to toggle an item and Enter to accept. The answer contains original keys such as `['api', 'reports']`. An empty selection returns `[]`. -16. **positive** - - **Description**: Checks if the value is a positive number. - - **Usage**: `"positive" => []` +## Progress -17. **negative** - - **Description**: Checks if the value is a negative number. - - **Usage**: `"negative" => []` +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. -18. **validVersion** - - **Description**: Checks if the value is a valid version number. - - **Usage**: `"validVersion" => [true]` +```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(); +} +``` -19. **versionCompare** - - **Description**: Validates and compares if a version is equal/more/equalMore/less... e.g., than withVersion. - - **Usage**: `"versionCompare" => ["1.0.0", ">="]` +A terminal updates one line. For three files, the final line is the following. -20. **zip** - - **Description**: Validates ZIP codes within a specified length range. - - **Usage**: `"zip" => [5, 9]` +```text +[========================] 3/3 +``` -21. **hex** - - **Description**: Checks if the value is a valid hex color code. - - **Usage**: `"hex" => []` +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)`. -22. **age** - - **Description**: Checks if the value represents an age equal to or greater than the specified minimum. - - **Usage**: `"age" => [18]` +## ANSI styling -23. **domain** - - **Description**: Checks if the value is a valid domain. - - **Usage**: `"domain" => [true]` +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. -24. **dns** - - **Description**: Checks if the host/domain has a valid DNS record (A, AAAA, MX). - - **Usage**: `"dns" => []` +```php +$ansi = $cli->getAnsi(); -25. **matchDNS** - - **Description**: Matches DNS records by searching for a specific type and value. - - **Usage**: `"matchDNS" => [DNS_A]` +$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')); +``` -26. **equal** - - **Description**: Checks if the value is equal to a specified value. - - **Usage**: `"equal" => ["someValue"]` +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)`. -27. **notEqual** - - **Description**: Checks if the value is not equal to a specified value. - - **Usage**: `"notEqual" => ["someValue"]` +| 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. | -28. **string** - - **Description**: Checks if the value is a string. - - **Usage**: `"string" => []` +`disableAnsi(true)` turns off generated styles. Text stays readable, and background labels use brackets. The example above becomes the following. -29. **equalLength** - - **Description**: Checks if the string length is equal to a specified length. - - **Usage**: `"equalLength" => [10]` +```text +[ ATLAS ] +Choose a name for your project. +Project name to create: atlas +``` -30. **lossyPassword** - - **Description**: Validates password with allowed characters `[a-zA-Z\d$@$!%*?&]` and a minimum length. - - **Usage**: `"lossyPassword" => [8]` +Passing `false` restores automatic detection. Style detection uses `TERM` and the OS. For cursor movement in a custom renderer, check `$cli->hasCursorOutput()` first. -31. **strictPassword** - - **Description**: Validates strict password with specific character requirements and a minimum length. - - **Usage**: `"strictPassword" => [8]` +## Tables and help text -32. **pregMatch** - - **Description**: Validates if the value matches a given regular expression pattern. - - **Usage**: `"pregMatch" => ["a-zA-Z"]` +`Blocks` writes aligned tables and help sections through your command. -33. **atoZ** - - **Description**: Checks if the value consists of characters between `a-z` or `A-Z`. - - **Usage**: `"atoZ" => []` +```php +use MaplePHP\Prompts\Themes\Blocks; -34. **lowerAtoZ** - - **Description**: Checks if the value consists of lowercase characters between `a-z`. - - **Usage**: `"lowerAtoZ" => []` +$blocks = new Blocks($cli); +$blocks->table(['Setting', 'Value'], [ + ['Project', 'atlas'], + ['Database', 'SQLite'], +]); +``` -35. **upperAtoZ** - - **Description**: Checks if the value consists of uppercase characters between `A-Z`. - - **Usage**: `"upperAtoZ" => []` +```text +Setting Value +Project atlas +Database SQLite +``` -36. **isArray** - - **Description**: Checks if the value is an array. - - **Usage**: `"isArray" => []` +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. -37. **isObject** - - **Description**: Checks if the value is an object. - - **Usage**: `"isObject" => []` +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. -38. **boolVal** - - **Description**: Checks if the value is a boolean-like value (e.g., "on", "yes", "1", "true"). - - **Usage**: `"boolVal" => []` +## Terminals, pipes, and input handling -### Usage Example +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. -Here is an example of how to use the validation functions in the prompt library: +`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 -$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" => [] - ] - ], - "age" => [ - "type" => "text", - "message" => "Age", - "validate" => [ - "number" => [], - "min" => [18] - ] - ] -]); +use MaplePHP\Http\Stream; + +$cli = new Command(stream: new Stream(STDERR)); ``` -## Conclusion +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. + +## License -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 +Apache License 2.0. \ No newline at end of file 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/examples/command.php b/examples/command.php new file mode 100644 index 0000000..7a0b488 --- /dev/null +++ b/examples/command.php @@ -0,0 +1,59 @@ +title('Export report'); + +try { + $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(); + + $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'); + $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 13adcc2..634ee0e 100755 --- a/examples/example.php +++ b/examples/example.php @@ -1,131 +1,90 @@ #!/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' => 'search', + '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->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); } - - - - diff --git a/src/Command.php b/src/Command.php index 65d7969..5ea03a9 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; @@ -12,19 +15,25 @@ /** * Class Command * @package MaplePHP\Prompts + * @api */ 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; - 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->inputLookahead = (object)['byte' => '']; $this->stty = new SttyWrapper(); $this->ansi = new Ansi(); @@ -53,6 +62,99 @@ 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')); + } + + /** @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 + { + if ($this->inputLookahead->byte !== '') { + return true; + } + $input = $this->getInput(); + $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') || $resource === null) { + 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. + */ + public function hasTerminalInput(): bool + { + $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); + } + + /** + * 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 = $this->nativeResource($output); + return $resource !== null && 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 * @@ -78,15 +180,63 @@ public function getAnsi(): Ansi * * @param string $message * @return string + * @throws InputExhaustedException */ public function readline(string $message): string { - if (function_exists("readline")) { - return readline("$message: "); + $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->hasUnreadBytes($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); + } + + /** + * 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. + */ + public function line(string $message = '', bool $break = true): void + { + $this->write($message, $break); } /** @@ -99,9 +249,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 +273,8 @@ 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. + * @api */ public function approve(string $message, bool $break = true): string|false { @@ -130,12 +282,24 @@ 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 + { + // Keep dispatching to existing overrides of approve(). + /** @psalm-suppress DeprecatedMethod */ + $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. + * @api */ public function statusMsg(string $message, bool $break = true): string|false { @@ -143,6 +307,24 @@ 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 + { + // Keep dispatching to existing overrides of statusMsg(). + /** @psalm-suppress DeprecatedMethod */ + $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 * @@ -179,17 +361,60 @@ 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); } + /** + * 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. + * + * 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 * @@ -203,20 +428,21 @@ 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 = 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]; + } } - return $this->inputSelect($message, $choices); } /** @@ -228,14 +454,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); } @@ -249,38 +469,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); + } + if (PHP_OS_FAMILY === 'Windows') { + return (new WindowsPasswordReader())->read( + fn () => $this->write("$message (masked input): ", false), + fn () => $this->write('') + ); } - $this->message("Warning: The input will not be masked. The PHP function \"system\" is disabled."); - return (string)$this->message($message, true); + + // 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,45 +513,190 @@ 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))); + 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"; + } - if ($line === "yes") { - return true; - } elseif ($line === "no") { - return false; - } - return $this->confirm($message); + /** + * 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 * + * 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(); + } + + /** @return resource|null */ + private function standardInputResource() + { + /** @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(). + $probe = new Stream(Stream::STDIN, 'rb'); + try { + return stream_isatty($probe->getResource()); + } finally { + $probe->close(); + } + } + + private function isUnverifiedTerminalInput(): bool + { + $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 = $input->getMetadata('uri'); + if ($uri === Stream::STDIN || $uri === 'php://fd/0') { + $stdin = $this->standardInputResource(); + return $stdin !== null && $this->standardInputIsTerminal($stdin); + } + 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; + } + 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 = $this->readInputByte(); + 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..c8bb64e --- /dev/null +++ b/src/Exceptions/InputExhaustedException.php @@ -0,0 +1,12 @@ + PromptDefinition::validateInput($rules, $input); + } +} diff --git a/src/Navigation.php b/src/Navigation.php index 5467029..057ea2b 100755 --- a/src/Navigation.php +++ b/src/Navigation.php @@ -3,18 +3,28 @@ namespace MaplePHP\Prompts; use Exception; +use InvalidArgumentException; +use MaplePHP\Prompts\Exceptions\PromptException; /** * Class Navigation * @package MaplePHP\Prompts + * @api */ 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 const SEARCH_ROWS = 8; + private Command $command; + private NavigationInput $input; private int $index = 0; + /** @var list */ private array $items = []; + /** @var list */ private array $values = []; private string $acceptKey = ""; private ?string $helperText = null; @@ -27,6 +37,7 @@ class Navigation public function __construct(Command $command) { $this->command = $command; + $this->input = new NavigationInput($command); $this->setAcceptKey($this->command->getAnsi()->keyEnter()); } @@ -55,31 +66,155 @@ 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->input->withMode(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::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 + * @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 +224,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,21 +246,129 @@ 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); + } + + /** + * @param array $selected + * @return array + */ + private function selectMultipleInTerminal(string $message, array $selected): array + { + $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 { + 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->input->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->input->readByte(); + $key = in_array($byte, ["\033", "\r", "\n"], true) ? $byte : $key . $byte; + continue 2; + } + } + return $key; } } @@ -140,6 +380,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,12 +426,15 @@ 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)); + $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/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/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/Prompt.php b/src/Prompt.php index 9661265..644ab02 100755 --- a/src/Prompt.php +++ b/src/Prompt.php @@ -3,13 +3,20 @@ namespace MaplePHP\Prompts; use ErrorException; -use Exception; use InvalidArgumentException; +use MaplePHP\Prompts\Exceptions\InputExhaustedException; +use MaplePHP\Prompts\Exceptions\InputInterruptedException; use MaplePHP\Prompts\Exceptions\PromptException; use MaplePHP\Validate\Validator; +/** @api */ class Prompt { + private const TYPES = [ + 'message', 'text', 'invisible', 'mask', 'password', 'list', 'select', 'search', 'multiselect', 'toggle', 'confirm', + 'continue', + ]; + private Command $command; private array $data = []; private ?string $title = null; @@ -19,9 +26,9 @@ class Prompt private mixed $prevVal = null; private bool $disableHeaderInfo = false; - public function __construct() + public function __construct(?Command $command = null) { - $this->command = new Command(); + $this->command = $command ?? new Command(); } /** @@ -101,21 +108,38 @@ 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 (isset($default) && is_string($default) && strlen($default)) { + 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)"; } @@ -123,52 +147,45 @@ 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"); + // 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; } - $inst = new self(); - $inst->disableHeaderInfo(true); - $inst->data = $items; - $input = $inst->prompt(); + } + + $input = $this->readRow($rowType, $message, $choices, $row['default'] ?? [], $stored); + if ($input === false && ($rowType === 'continue' || $rowType === 'confirm')) { + return false; + } + // Search always returns a choice key, which can itself be an empty string. + if ($rowType !== 'search' && $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)) { @@ -176,28 +193,57 @@ 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', '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)) { + 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), + 'search' => $this->command->selectWithSearch($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; } /** @@ -205,9 +251,41 @@ public function promptLine(array $row): mixed * * @return array|false * @throws ErrorException - * @throws PromptException|\MaplePHP\Prompts\PromptException + * @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($stored); + } catch (InputExhaustedException | InputInterruptedException) { + return false; + } + } + + private function run(bool $stored): array|false { $result = []; $this->index = 0; @@ -218,11 +296,12 @@ public function prompt(): 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]); @@ -231,6 +310,15 @@ public function prompt(): 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 * @@ -277,29 +365,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; } @@ -314,6 +409,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..19771da --- /dev/null +++ b/src/PromptDefinition.php @@ -0,0 +1,278 @@ + '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', 'search', '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 ($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."); + } + + $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> */ + public 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 = null): 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/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 9481175..9c2757d 100755 --- a/src/SttyWrapper.php +++ b/src/SttyWrapper.php @@ -2,9 +2,12 @@ namespace MaplePHP\Prompts; +use MaplePHP\Prompts\Exceptions\PromptException; + /** * Class SttyWrapper * @package MaplePHP\Prompts + * @api */ class SttyWrapper { @@ -133,4 +136,78 @@ public function hasSttySupport(): bool } return false; } + + /** + * @internal + * @return array{int, int} Terminal rows and columns. + */ + public function terminalSize(): array + { + try { + return $this->parseSize($this->runStty('size')); + } catch (PromptException) { + return [24, 80]; + } + } + + /** + * @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]; + } + + /** + * 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 + { + $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/Themes/Ansi.php b/src/Themes/Ansi.php index 34e300f..b4c56a7 100755 --- a/src/Themes/Ansi.php +++ b/src/Themes/Ansi.php @@ -8,6 +8,7 @@ /** * Class Ansi * @package MaplePHP\Prompts + * @api */ class Ansi { @@ -48,13 +49,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; } @@ -68,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; } @@ -99,7 +104,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"; } @@ -129,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 * @@ -140,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 * @@ -565,11 +614,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 +629,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 +743,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..c1363c6 100644 --- a/src/Themes/Blocks.php +++ b/src/Themes/Blocks.php @@ -2,10 +2,16 @@ namespace MaplePHP\Prompts\Themes; +use InvalidArgumentException; use MaplePHP\Prompts\Command; +use ParseError; +use Stringable; +/** @api */ class Blocks { + private const SGR = '/\x1b\[[0-9;:]*m/'; + private Command $command; private string $space; private array $options = []; @@ -13,6 +19,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 +91,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 +101,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 +134,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 +144,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 +218,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 +281,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 +297,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 +312,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 +334,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 +353,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 +372,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 +386,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 +406,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/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 new file mode 100644 index 0000000..3fda411 --- /dev/null +++ b/tests/unitary-compatibility.php @@ -0,0 +1,240 @@ +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'); + } +} + +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('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'); + $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 = new Prompt(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 = new Prompt($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 = 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']]; + 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(); +}); diff --git a/tests/unitary-definitions.php b/tests/unitary-definitions.php new file mode 100644 index 0000000..068c60e --- /dev/null +++ b/tests/unitary-definitions.php @@ -0,0 +1,294 @@ +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(); +}); + +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(); +}); diff --git a/tests/unitary-input.php b/tests/unitary-input.php new file mode 100644 index 0000000..4ce948c --- /dev/null +++ b/tests/unitary-input.php @@ -0,0 +1,260 @@ +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('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")); + $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) { + fclose(STDIN); + exit((int)($copy->hasTerminalInput() || $copy->inputIsReady(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(); +}); 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); +}); 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(); +}); 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); +}); diff --git a/tests/unitary-themes.php b/tests/unitary-themes.php new file mode 100644 index 0000000..f513cd2 --- /dev/null +++ b/tests/unitary-themes.php @@ -0,0 +1,394 @@ += 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 { + putenv('TERM=xterm-256color'); + $standalone = new Ansi(); + $stream = new Stream('php://memory'); + $command = new Command(new Response($stream)); + $ansi = $command->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); +});