diff --git a/README.md b/README.md index a21ac55..97b285a 100644 --- a/README.md +++ b/README.md @@ -181,16 +181,13 @@ Non-string cell values are stringified (`[NULL]`, `[TRUE]`, `[FALSE]`, `[ARRAY]` ## Documentation -In-depth, example-driven guides live in [`docs/`](./docs): +In-depth, example-driven guides live in [`docs/`](./docs). Start with [Home](./docs/Home.md): -1. [Getting started](./docs/01-getting-started.md) -2. [Commands](./docs/02-commands.md) -3. [Input: arguments, options & segments](./docs/03-input.md) -4. [Typed input arguments](./docs/04-input-arguments.md) -5. [Output & formatting](./docs/05-output.md) -6. [Interactive questions](./docs/06-questions.md) -7. [Tables](./docs/07-tables.md) -8. [Migrating from `initphp/cli-table`](./docs/08-migrating-from-cli-table.md) +- [Installation](./docs/Installation.md) and [Quick Start](./docs/Quick-Start.md) +- [Commands](./docs/Commands.md), [Input](./docs/Input.md) and [Input Arguments](./docs/Input-Arguments.md) +- [Output](./docs/Output.md), [Questions](./docs/Questions.md) and [Tables](./docs/Tables.md) +- [API Reference](./docs/API-Reference.md) and [Exceptions](./docs/Exceptions.md) +- [Recipes](./docs/Recipes.md), [Migration Guide](./docs/Migration-Guide.md) and [FAQ](./docs/FAQ.md) ## Migrating from `initphp/cli-table` @@ -212,7 +209,7 @@ use InitPHP\CLITable\Table; use InitPHP\Console\Utils\Table; ``` -The alias is a transition aid and may be removed in a future major release. See the [migration guide](./docs/08-migrating-from-cli-table.md) for details. +The alias is a transition aid and may be removed in a future major release. See the [migration guide](./docs/Migration-Guide.md) for details. ## Testing & quality diff --git a/docs/01-getting-started.md b/docs/01-getting-started.md deleted file mode 100644 index c7619b4..0000000 --- a/docs/01-getting-started.md +++ /dev/null @@ -1,91 +0,0 @@ -# Getting started - -`initphp/console` helps you build command-line tools in PHP: it routes a command name to a handler, parses the tokens that follow it, and gives you helpers for coloured output, prompts and tables. - -## Installation - -```bash -composer require initphp/console -``` - -Requires PHP 7.2+. The optional `ext-mbstring` extension improves table alignment for multibyte text. - -## Your first application - -Create an executable entry script, for example `bin/console`: - -```php -#!/usr/bin/env php -register('greet', function (Input $input, Output $output) { - $output->writeln('Hello {name}!', [ - 'name' => $input->getArgument('name', 'World'), - ]); -}, 'Greets someone.'); - -$console->run(); -``` - -Make it runnable and try it: - -```bash -chmod +x bin/console - -php bin/console greet --name=Ada # Hello Ada! -php bin/console greet # Hello World! -php bin/console list # Overview of all commands -``` - -## How dispatch works - -`Application::run()`: - -1. Reads the token list (from the global `$argv`, or from the array you pass to `run()`). -2. Drops the script name (`$argv[0]`) and takes the next token as the **command name**. -3. Wraps the remaining tokens in an [`Input`](03-input.md) object and creates an [`Output`](05-output.md). -4. Dispatches: - - `help` / `list` → renders the command overview. - - a registered command with the `--help` argument → renders that command's usage. - - a registered command → runs its handler. - - anything else → prints `The command was not found.` - -`run()` returns `true` when a command (or help) ran and `false` when no command was supplied or nothing matched. - -## Passing the token list explicitly - -`run()` accepts an optional array, which makes the application trivial to drive from tests or another script: - -```php -$console->run(['bin/console', 'greet', '--name=Ada']); -``` - -When omitted, the global `$argv` is used (just like a normal CLI program). - -## Injecting output - -The constructor accepts an optional `Output` instance. Inject one backed by an in-memory stream to capture everything a command prints: - -```php -use InitPHP\Console\Output; - -$stream = fopen('php://memory', 'r+'); -$console = new Application('Acme CLI', '1.0.0', new Output($stream)); -$console->run(['bin/console', 'greet', '--name=Ada']); - -rewind($stream); -echo stream_get_contents($stream); -``` - -## Next steps - -- [Commands](02-commands.md) — closures vs. class-based commands and grouping. -- [Input](03-input.md) — arguments, options and segments. -- [Typed input arguments](04-input-arguments.md) — validation and defaults. -- [Output](05-output.md), [Questions](06-questions.md), [Tables](07-tables.md). diff --git a/docs/02-commands.md b/docs/02-commands.md deleted file mode 100644 index 614de42..0000000 --- a/docs/02-commands.md +++ /dev/null @@ -1,126 +0,0 @@ -# Commands - -A command is the unit of work the application dispatches to. You can register a command either as a **closure** or as a **class** extending `Command`. - -## Closure commands - -```php -use InitPHP\Console\{Input, Output}; - -$console->register('cache:clear', function (Input $input, Output $output) { - // ... do the work ... - $output->success('Cache cleared.'); -}, 'Clears the application cache.'); -``` - -`register()` signature: - -```php -public function register( - string $command, // command name, e.g. "cache:clear" - ?callable $execute = null, // the handler - string $definition = '' // short description for the listing -): self -``` - -The handler is called with `(Input $input, Output $output)`. The return value is ignored. `register()` returns the application, so calls can be chained. - -## Class-based commands - -For richer commands, extend `InitPHP\Console\Command`: - -```php -use InitPHP\Console\{Command, Input, InputArgument, Output}; - -final class MakeModelCommand extends Command -{ - public $command = 'make:model'; - - public function definition(): string - { - return 'Generates a model class.'; - } - - public function help(): string - { - return 'Creates a new model in app/Models from a name argument.'; - } - - public function arguments(): array - { - return [ - new InputArgument('name', InputArgument::STR, '', false, 'Model class name.'), - new InputArgument('force', InputArgument::BOOL, false, true, 'Overwrite if it exists.'), - ]; - } - - public function execute(Input $input, Output $output) - { - $name = $input->getArgument('name'); - $output->success("Model {$name} created."); - } -} -``` - -Register it by class name — the application instantiates it and reads the metadata from the instance: - -```php -$console->register(MakeModelCommand::class); -``` - -### The `Command` contract - -| Member | Required | Purpose | -|-----------------|----------|-------------------------------------------------------------------------| -| `$command` | ✅ | The name the command is invoked by. Must be set or registration throws. | -| `execute()` | ✅ | Runs the command. Receives `(Input, Output)`. | -| `definition()` | ❌ | One-line description shown in the listing (defaults to `''`). | -| `help()` | ❌ | Long help shown by ` --help`. | -| `arguments()` | ❌ | Array of [`InputArgument`](04-input-arguments.md) declarations. | - -Every entry returned by `arguments()` is validated **before** `execute()` runs. If a required argument is missing or a value fails its type check, the command aborts with an error and `execute()` is never called. - -## Grouping in the listing - -If a command name contains a colon, the prefix becomes a group heading in `php console list`: - -```php -$console->register(MakeModelCommand::class); // group: make -$console->register('make:controller', $fn, '...'); // group: make -$console->register('serve', $fn, 'Start server.'); // ungrouped -``` - -``` -[COMMANDS] - -make - make:model : Generates a model class. - make:controller : ... - -serve : Start server. -``` - -## Per-command help - -Any command supports an automatic usage screen via the `--help` argument: - -```bash -php console make:model --help -``` - -``` -Creates a new model in app/Models from a name argument. - -[PARAMETERS] - --name : Model class name. - --force : Overwrite if it exists. - -[USAGE] - php console make:model --name=(STRING) [--force=(BOOL)] -``` - -Required parameters are shown bare; optional ones are wrapped in `[ ]`. - -## Reserved names - -`help` and `list` are reserved for the built-in overview and cannot be used as command names. diff --git a/docs/03-input.md b/docs/03-input.md deleted file mode 100644 index 5e46800..0000000 --- a/docs/03-input.md +++ /dev/null @@ -1,101 +0,0 @@ -# Input: arguments, options & segments - -`Input` parses the tokens that follow the command name into three buckets and exposes them through a small, symmetric API. - -## The three token shapes - -| Shape | Bucket | Example | -|----------------------|-----------|----------------------------| -| `--name` | argument | `--verbose` | -| `--name=value` | argument | `--name=John` | -| `-x` | option | `-v` | -| `-xyz` (combined) | option | `-abc` → `a`, `b`, `c` | -| `-key=value` | option | `-level=5` | -| bare token | segment | `migrate`, `42` | - -> In this library `--long` tokens are **arguments** and `-short` tokens are **options** — the opposite of some other CLI frameworks. - -A token consisting only of dashes/whitespace (such as a lone `--`) carries no data and is skipped. - -## Automatic type casting - -Every value is normalised with `Helpers::strValueCast()`: - -| Input string | Result | -|--------------------------|---------------| -| `"true"`, `"yes"` | `true` | -| `"false"`, `"no"` | `false` | -| `"null"` | `null` | -| `"42"`, `"-7"`, `"+7"` | `int` | -| `"3.14"`, `"3,14"` | `float` | -| anything else | `string` | - -(Matching is case-insensitive. Both `.` and `,` are accepted as the decimal separator.) - -```php -$input = new Input(['--age=30', '--active=true', '--ratio=1,5', 'deploy']); - -$input->getArgument('age'); // int(30) -$input->getArgument('active'); // bool(true) -$input->getArgument('ratio'); // float(1.5) -$input->getSegment(0); // string("deploy") -``` - -## Arguments API - -```php -$input->hasArgument('name'); // bool -$input->getArgument('name', $default); // value or $default (null when omitted) -$input->allArguments(); // ['name' => 'John', ...] -``` - -A bare `--flag` (no `=value`) is stored as an empty string `''`, so `hasArgument('flag')` is `true` and `getArgument('flag')` is `''`. - -## Options API - -```php -$input->hasOption('v'); // bool -$input->getOption('level', $default); // value or $default -$input->allOptions(); // ['v' => 'v', 'level' => 5, ...] -``` - -Boolean short flags resolve to their own letter as the value: - -```php -$input = new Input(['-abc']); -$input->allOptions(); // ['a' => 'a', 'b' => 'b', 'c' => 'c'] -``` - -## Segments API - -Segments are bare positional tokens, indexed in order: - -```php -$input = new Input(['migrate', 'up', '3']); - -$input->getSegment(0); // string("migrate") -$input->getSegment(1); // string("up") -$input->getSegment(2); // int(3) -$input->allSegment(); // ['migrate', 'up', 3] -``` - -## Importing values - -`importArguments()` merges one or more `name => value` maps into the parsed arguments (later maps win). It is mainly used internally by [`InputArgument`](04-input-arguments.md) to write back resolved defaults, but it is available to you too: - -```php -$input->importArguments(['name' => 'fallback'], ['env' => 'prod']); -``` - -## Programming to the interface - -`Input` implements `InitPHP\Console\InputInterface`. Type-hint the interface in your own helpers when you want to accept any compatible implementation: - -```php -use InitPHP\Console\InputInterface; - -function resolveName(InputInterface $input): string -{ - return (string) $input->getArgument('name', 'World'); -} -``` diff --git a/docs/04-input-arguments.md b/docs/04-input-arguments.md deleted file mode 100644 index 3339927..0000000 --- a/docs/04-input-arguments.md +++ /dev/null @@ -1,95 +0,0 @@ -# Typed input arguments - -`InputArgument` lets a [class-based command](02-commands.md) declare the `--name` arguments it accepts, each with a type, a default value and an optional/required flag. The application validates them before calling `execute()`. - -## Constructing an argument - -```php -use InitPHP\Console\InputArgument; - -new InputArgument( - string $name, // name without dashes, e.g. "name" - string $type, // one of the type constants below - mixed $default, // must satisfy $type - bool $isOptional = true, - string $definition = '' // description for the help screen -); -``` - -The constructor throws `InvalidArgumentException` if the type is unknown, or if the default value does not satisfy the type. - -## Types - -| Constant | Underlying value | Accepts | -|---------------------------|------------------|-------------------------------------------------------------| -| `InputArgument::ANY` | `ANY` | Any value. | -| `InputArgument::INT` | `INT` | Integers. | -| `InputArgument::FLOAT` | `FLOAT` | Floats. | -| `InputArgument::NUMERIC` | `NUMBER` | Any numeric value (int, float or numeric string). | -| `InputArgument::BOOL` | `BOOL` | `true`/`false`, or `1`/`0` (coerced to bool). | -| `InputArgument::STR` | `STRING` | Strings (numeric/bool values are stringified). | - -Because `Input` casts values first (see [Input](03-input.md)), `--age=30` already arrives as `int(30)` and passes the `INT` check; `--age=abc` stays a string and fails it. - -## How resolution works - -For each declared argument, `run()` does the following: - -1. Look the value up as an **argument** (`--name`), then as an **option** (`-name`). -2. **Missing value:** - - optional → the default is stored and the command proceeds. - - required → an error is printed and the command aborts. -3. **Present value:** - - valid → kept (a required argument given an empty `''`/`null` value falls back to its default). - - invalid + optional → replaced with the default. - - invalid + required → an error is printed and the command aborts. - -The resolved value is written back into `Input`, so `execute()` reads it with `$input->getArgument('name')`. - -## Example - -```php -public function arguments(): array -{ - return [ - new InputArgument('name', InputArgument::STR, '', false, 'Required model name.'), - new InputArgument('count', InputArgument::INT, 1, true, 'How many to create.'), - new InputArgument('force', InputArgument::BOOL, false, true, 'Overwrite existing files.'), - ]; -} - -public function execute(Input $input, Output $output) -{ - $name = $input->getArgument('name'); // guaranteed present (required) - $count = $input->getArgument('count'); // int, defaults to 1 - $force = $input->getArgument('force'); // bool, defaults to false - // ... -} -``` - -```bash -php console make:model --name=User --count=3 --force=true -php console make:model # error: The --name parameter is undefined. -php console make:model --name=User # count=1, force=false -``` - -## Zero and `false` are real values - -A required argument explicitly set to `0` keeps `0` (it is not mistaken for "missing" and replaced by the default): - -```php -new InputArgument('retries', InputArgument::INT, 5, false); -// php console run --retries=0 → getArgument('retries') === 0 -``` - -## Reading the metadata - -```php -$arg = new InputArgument('age', InputArgument::INT, 18, false, 'The age.'); - -$arg->getName(); // "--age" -$arg->getType(); // "INT" -$arg->getDefault(); // "18" (string form, or null when no default) -$arg->getDefinition(); // "The age." -$arg->isOptional(); // false -``` diff --git a/docs/05-output.md b/docs/05-output.md deleted file mode 100644 index 4bcb03f..0000000 --- a/docs/05-output.md +++ /dev/null @@ -1,105 +0,0 @@ -# Output & formatting - -`Output` writes coloured/styled text to an output stream and reads interactive answers from an input stream. Both streams default to `STDOUT`/`STDIN` but can be injected for testing. - -## Writing text - -```php -$output->write('No trailing newline'); -$output->writeln('With a trailing newline'); -``` - -### Placeholder interpolation - -The second argument is a context map; `{key}` tokens in the string are replaced. Array values and objects without `__toString()` are left untouched. - -```php -$output->writeln('Deployed {app} to {env}', [ - 'app' => 'api', - 'env' => 'production', -]); -// Deployed api to production -``` - -### Styling - -The third argument (for `writeln`) / fourth (for `write`) is a list of SGR codes applied to the whole string: - -```php -$output->writeln('Important', [], [Output::COLOR_RED, Output::BOLD]); -$output->writeln('On blue', [], [Output::COLOR_WHITE, Output::BACKGROUND_BLUE]); -``` - -Available constants: - -- **Foreground:** `COLOR_DEFAULT`, `COLOR_BLACK`, `COLOR_RED`, `COLOR_GREEN`, `COLOR_YELLOW`, `COLOR_BLUE`, `COLOR_MAGENTA`, `COLOR_CYAN`, `COLOR_LIGHT_GRAY`, `COLOR_DARK_GRAY`, `COLOR_LIGHT_RED`, `COLOR_LIGHT_GREEN`, `COLOR_LIGHT_YELLOW`, `COLOR_LIGHT_BLUE`, `COLOR_LIGHT_MAGENTA`, `COLOR_LIGHT_CYAN`, `COLOR_WHITE` -- **Background:** `BACKGROUND_BLACK`, `BACKGROUND_RED`, `BACKGROUND_GREEN`, `BACKGROUND_YELLOW`, `BACKGROUND_BLUE`, `BACKGROUND_MAGENTA`, `BACKGROUND_CYAN` -- **Styles:** `BOLD`, `ITALIC`, `UNDERLINE`, `STRIKETHROUGH` - -## Message helpers - -Pre-styled, prefixed one-liners: - -```php -$output->error('Disk full'); // [ERROR] white on red, bold -$output->success('Done'); // [SUCCESS] white on green, bold -$output->warning('Low memory'); // [WARNING] white on yellow, bold -$output->info('Cache warmed'); // [INFO] cyan -``` - -Each accepts a context map too: - -```php -$output->error('User {id} not found', ['id' => 42]); -``` - -## Key/value lists - -```php -$output->list([ - 'Host' => 'localhost', - 'Port' => 8080, - 'TLS' => 'enabled', -]); -``` - -``` -Host : localhost -Port : 8080 -TLS : enabled -``` - -The optional second argument indents the whole block by N tab stops — used by the built-in help screen to indent grouped commands. - -## Progress bar - -`progressBar($done, $total)` renders a single, in-place updating line. `$total` must be greater than zero (a `0` total throws `InvalidArgumentException`). - -```php -$total = 50; -for ($i = 0; $i <= $total; $i++) { - $output->progressBar($i, $total); - usleep(20_000); -} -$output->writeln(''); // move off the progress line when finished -``` - -## Injecting streams (testing) - -Pass a stream resource to capture output or feed answers: - -```php -$buffer = fopen('php://memory', 'r+'); -$output = new Output($buffer); - -$output->writeln('hello'); - -rewind($buffer); -echo stream_get_contents($buffer); // "\e[39mhello\e[0m\n" -``` - -The second constructor argument overrides the input stream used by [`ask()`/`question()`](06-questions.md). - -## Programming to the interface - -`Output` implements `InitPHP\Console\OutputInterface`; type-hint that interface where you only need the public surface. diff --git a/docs/06-questions.md b/docs/06-questions.md deleted file mode 100644 index b230ba9..0000000 --- a/docs/06-questions.md +++ /dev/null @@ -1,87 +0,0 @@ -# Interactive questions - -`Output` offers two ways to read input from the user: free-form `ask()` and the option-constrained `question()` built around the `Question` value object. - -## `ask()` — free-form input - -```php -$name = $output->ask('What is your name?'); -``` - -- The prompt is printed, then a line is read from the input stream. -- The answer is run through the same [type casting](03-input.md#automatic-type-casting) as command input, so `"42"` comes back as `int(42)`, `"yes"` as `true`, etc. -- Passing `false` as the second argument rejects an empty answer and keeps asking: - -```php -$value = $output->ask('This cannot be empty:', false); -``` - -- Typing `exit` or `quit` terminates the application. - -## `question()` — constrained input - -`Question` describes the prompt, the set of acceptable answers, whether it is optional and a default. Configure it fluently: - -```php -use InitPHP\Console\Question; - -$question = (new Question()) - ->setQuestion('Pick an environment:') - ->setOptions(['dev', 'staging', 'prod']) - ->optional() - ->setDefault('dev'); - -$env = $output->question($question); -``` - -Behaviour when an answer is submitted: - -1. If it matches one of the options → the (cast) answer is returned. -2. If it is `exit`/`quit` → the application terminates. -3. If the question is **optional** → the default is returned (or the raw answer when no default is set). -4. If the question is **required** and nothing matched → the user is asked again. - -### Acceptable-answer matching - -`hasOption()` matches both the verbatim answer and its cast form, so string input lines up with boolean/numeric options: - -```php -$q = new Question(); // default options: [true, false] -$q->hasOption('true'); // true ("true" casts to bool true) -$q->hasOption('yes'); // true -$q->hasOption('maybe'); // false -``` - -For yes/no prompts you can therefore rely on the defaults, or set explicit string options: - -```php -(new Question())->setQuestion('Continue?')->setOptions(['yes', 'no']); -``` - -## The `Question` API - -| Method | Purpose | -|--------------------------------|----------------------------------------------------------------| -| `setQuestion(string)` / `getQuestion()` | The prompt text. | -| `setOptions(array)` / `getOptions()` | Replace / read the acceptable answers. | -| `addOption(string)` | Append a single acceptable answer. | -| `hasOption(string)` | Whether an answer is acceptable (verbatim or cast). | -| `optional()` / `notOptional()` / `isOptional()` | Toggle / read the optional flag. | -| `setDefault(mixed)` / `getDefault()` | Set / read the default answer. | -| `hasDefault()` | Whether a default was set. | -| `Question::NO_DEFAULT` | Sentinel returned by `getDefault()` when no default is set. | - -> **`addOption()` compatibility note:** the method also accepts a legacy two-argument form `addOption($label, $value)`, where the second argument is the value that gets registered and the first is just a label. Prefer the single-argument form for new code. - -## Testing prompts - -Inject an input stream pre-seeded with the answers: - -```php -$stdin = fopen('php://memory', 'r+'); -fwrite($stdin, "Ada\n"); -rewind($stdin); - -$output = new Output(STDOUT, $stdin); -$output->ask('Name?'); // "Ada" -``` diff --git a/docs/07-tables.md b/docs/07-tables.md deleted file mode 100644 index 54c1a44..0000000 --- a/docs/07-tables.md +++ /dev/null @@ -1,79 +0,0 @@ -# Tables - -`InitPHP\Console\Utils\Table` renders styleable ASCII/ANSI tables. Rows are associative arrays; the union of their keys forms the header, columns are auto-sized, and styles are emitted as SGR escape sequences. - -## Basic usage - -```php -use InitPHP\Console\Utils\Table; - -$table = Table::create(); - -$table->row(['id' => 1, 'name' => 'Matthew S.', 'email' => 'matthew@example.com']) - ->row(['id' => 2, 'name' => 'Millie J.', 'email' => 'millie@example.com']); - -echo $table; // uses __toString() -// or -echo $table->getContent(); -``` - -``` -╔══════╤══════════════╤══════════════════════════╗ -║ id │ name │ email ║ -╟──────┼──────────────┼──────────────────────────╢ -║ 1 │ Matthew S. │ matthew@example.com ║ -║ 2 │ Millie J. │ millie@example.com ║ -╚══════╧══════════════╧══════════════════════════╝ -``` - -`Table::create()` is a convenience factory equivalent to `new Table()`; both return a fresh instance and every mutator returns `$this` for chaining. - -## Styling - -All four style setters take one or more SGR codes (the same constants as [`Output`](05-output.md), also exposed on `Table`): - -```php -$table = Table::create() - ->setHeaderStyle(Table::COLOR_RED, Table::BOLD) // header row - ->setCellStyle(Table::COLOR_GREEN) // every body cell - ->setBorderStyle(Table::COLOR_BLUE) // the frame - ->setColumnCellStyle('status', Table::COLOR_YELLOW); // one column's body cells -``` - -- `setHeaderStyle()` — defaults to `[BOLD]`. -- `setCellStyle()` — applied to all body cells. -- `setBorderStyle()` — applied to the box-drawing characters. -- `setColumnCellStyle($column, ...)` — overrides body styling for a single column. - -## How values are rendered - -Non-string cell values are converted to a printable form: - -| Value type | Rendered as | -|------------------------------------|----------------------| -| `null` | `[NULL]` | -| `true` / `false` | `[TRUE]` / `[FALSE]` | -| array | `[ARRAY]` | -| array that is callable | `[CALLABLE]` | -| other callable | `[CALLABLE]` | -| resource | `[RESOURCE]` | -| object | its class name | -| int / float | string cast | - -Rows with different key sets are allowed: any cell missing from a row is rendered as `[NULL]`. - -```php -Table::create() - ->row(['id' => 1, 'name' => 'Ada', 'active' => true]) - ->row(['id' => 2, 'name' => null, 'meta' => ['x' => 1]]) - ->getContent(); -// missing/extra columns are filled with [NULL]; null → [NULL]; array → [ARRAY] -``` - -## Multibyte text - -Column widths are measured with `mb_strlen()` when the `mbstring` extension is available, so UTF-8 values such as `İstanbul` or `Mühammet` align correctly. Without `mbstring` the renderer falls back to `strlen()`. - -## Legacy alias - -This class was previously shipped as `initphp/cli-table`. The old fully-qualified name `\InitPHP\CLITable\Table` still resolves to it via a `class_alias`, so existing code keeps working. See [Migrating from `initphp/cli-table`](08-migrating-from-cli-table.md). diff --git a/docs/08-migrating-from-cli-table.md b/docs/08-migrating-from-cli-table.md deleted file mode 100644 index 2b2b475..0000000 --- a/docs/08-migrating-from-cli-table.md +++ /dev/null @@ -1,59 +0,0 @@ -# Migrating from `initphp/cli-table` - -The standalone [`initphp/cli-table`](https://github.com/InitPHP/CLITable) package was merged into `initphp/console` as of **2.1** and is now deprecated. The table renderer now lives at `InitPHP\Console\Utils\Table`. - -## What you need to do - -### 1. Switch the dependency - -```diff - "require": { -- "initphp/cli-table": "^1.0", -+ "initphp/console": "^2.1" - } -``` - -```bash -composer update initphp/console -``` - -`initphp/console` declares a Composer `replace` for `initphp/cli-table`, so Composer will never install both packages side by side — even if a transitive dependency still asks for the old one. - -### 2. (Optional) update your imports - -**No code change is strictly required.** This package registers a `class_alias` so the legacy fully-qualified name keeps working: - -```php -use InitPHP\CLITable\Table; // still resolves — backed by the alias -``` - -When you next touch the code, prefer the canonical namespace: - -```php -// Before -use InitPHP\CLITable\Table; - -// After -use InitPHP\Console\Utils\Table; -``` - -The public API (`create()`, `row()`, `setHeaderStyle()`, `setCellStyle()`, `setBorderStyle()`, `setColumnCellStyle()`, `getContent()`, `__toString()`) is unchanged — see [Tables](07-tables.md). - -## How the alias works - -`src/aliases.php` (loaded automatically via Composer's `files` autoloading) runs: - -```php -if (!class_exists(\InitPHP\CLITable\Table::class, false)) { - class_alias( - \InitPHP\Console\Utils\Table::class, - 'InitPHP\\CLITable\\Table' - ); -} -``` - -The `class_exists(..., false)` check (autoload disabled) is a safety net: if the legacy class were somehow already loaded, the alias is skipped to avoid a "cannot redeclare class" fatal. In normal use the `replace` directive guarantees the legacy class is absent, so the alias is always created. - -## Deprecation timeline - -The alias is a **transition aid**. Treat the legacy `InitPHP\CLITable\Table` name as deprecated and migrate to `InitPHP\Console\Utils\Table` at your convenience; the alias may be removed in a future major release. diff --git a/docs/API-Reference.md b/docs/API-Reference.md new file mode 100644 index 0000000..39c23c9 --- /dev/null +++ b/docs/API-Reference.md @@ -0,0 +1,387 @@ +# API Reference + +The full public surface of `initphp/console`. Behavioural deep-dives are +linked into the [Building Commands](Commands.md) and +[Output & Interaction](Output.md) sections. + +> Signatures are shown as they appear in the source. The library requires +> **PHP 8.2+**. Where a signature below carries a `// mixed` comment, the source +> has no native type and documents it with PHPDoc; `?Type` nullable hints and +> scalar parameter/return types are native. + +**Classes & interfaces** + +- [`Application`](#application) +- [`Command`](#command) +- [`Input`](#input) / [`InputInterface`](#inputinterface) +- [`InputArgument`](#inputargument) +- [`Output`](#output) / [`OutputInterface`](#outputinterface) +- [`Question`](#question) +- [`Helpers`](#helpers) +- [`Utils\Table`](#utilstable) + +--- + +## `Application` + +`InitPHP\Console\Application` — the command registry and dispatcher. + +```php +public const VERSION = '2.1.0'; +``` + +### Constructor + +```php +public function __construct( + string $application = 'InitPHP Console Application', + string $version = self::VERSION, + ?Output $output = null +); +``` + +Stores the application name and version shown in help output. When `$output` +is `null` a default [`Output`](#output) is created lazily during `run()`. Inject +one (e.g. backed by a memory stream) to capture output in tests. + +### `register` + +```php +public function register(string $command, ?callable $execute = null, string $definition = ''): self; +``` + +Registers a command. Two modes: + +- **Closure mode** (`$execute` is a callable): `$command` is the command name, + `$definition` is the short listing description. +- **Class mode** (`$execute` is `null`): `$command` is the fully-qualified name + of a [`Command`](#command) subclass. It is instantiated; its `$command`, + `definition()` and `help()` are read from the instance. + +Returns `$this`. Throws: + +- `\InvalidArgumentException` — class mode: the class does not exist or is not + a `Command`. +- `\LogicException` — class mode: a `Command` class does not set its `$command` + name. +- `\TypeError` — closure mode: `$execute` is not callable. The `?callable` + parameter type rejects it before the method body runs. + +See [Exceptions](Exceptions.md). + +### `run` + +```php +public function run(?array $argv = null): bool; +``` + +Parses the token list and dispatches. When `$argv` is `null` the global +`$argv` is used. The first element is treated as the script name and dropped; +the next token is the command name. + +Returns: + +- `false` — no command was supplied (only the script name, or an empty list). +- `true` — `help`/`list` ran, a command ran, or the command was not found + (handled gracefully with an error message). + +`false` is also returned when a command's declared argument validation fails, +when the handler is not executable, or when the handler throws (the `Throwable` +is caught and its message printed via `Output::error()`). + +Reserved command names `help` and `list` render the overview screen; the +`--help` argument on any registered command renders its per-command usage. + +--- + +## `Command` + +`InitPHP\Console\Command` — abstract base class for class-based commands. + +```php +public $command; // the invocation name (set in a subclass) + +abstract public function execute(Input $input, Output $output); + +public function help(): string; // default: 'No explanation for this command is specified.' +public function definition(): string; // default: '' +public function arguments(): array; // default: [] — array +``` + +`$command` must be set by the subclass. `arguments()` returns the typed +[`InputArgument`](#inputargument) declarations validated before `execute()`. +See [Commands](Commands.md). + +--- + +## `InputInterface` + +`InitPHP\Console\InputInterface` — read access to parsed tokens. + +```php +public function hasArgument(string $name): bool; +public function getArgument(string $name, $default = null); // mixed +public function allArguments(): array; // array + +public function hasSegment(int $index): bool; +public function getSegment(int $index, $default = null); // mixed +public function allSegment(): array; // array + +public function hasOption(string $name): bool; +public function getOption(string $name, $default = null); // mixed +public function allOptions(): array; // array + +public function importArguments(array ...$arguments): void; // merge maps (later wins) +``` + +Implemented by [`Input`](#input). Depend on the interface in helpers that only +read input. + +--- + +## `Input` + +`InitPHP\Console\Input implements InputInterface` — parses the tokens that +follow the command name. + +### Constructor + +```php +public function __construct(array $argv); +``` + +`$argv` is the token list **after** the command name. Parsing rules: + +- `--name=value` / `--name` → **argument** (bare form stored as `''`). +- `-key=value` → **option**; `-abc` (no `=`) → combined boolean flags + (`a`, `b`, `c`), each stored as its own letter. +- bare token → **segment**. +- a token of only dashes/whitespace (e.g. `--`) is skipped. + +All values are cast with [`Helpers::strValueCast()`](#helpers). + +### Methods + +Identical to [`InputInterface`](#inputinterface). See [Input](Input.md) for +worked examples. + +--- + +## `InputArgument` + +`InitPHP\Console\InputArgument` (final) — a typed `--name` argument. + +### Constants + +```php +public const ANY = 'ANY'; +public const INT = 'INT'; +public const FLOAT = 'FLOAT'; +public const NUMERIC = 'NUMBER'; +public const BOOL = 'BOOL'; +public const STR = 'STRING'; +``` + +### Constructor + +```php +public function __construct( + string $name, + $type, // one of the constants above + $default, // must satisfy $type + bool $isOptional = true, + string $definition = '' +); +``` + +Throws `\InvalidArgumentException` if `$type` is unsupported or `$default` +does not satisfy it. + +### Methods + +```php +public function isOptional(): bool; +public function getType(): string; // the type constant value, e.g. "INT" +public function getName(): string; // the name prefixed with "--" +public function getDefinition(): string; +public function getDefault(): ?string; // default as a string, or null +public function run(Input $input, Output $output): bool; +``` + +`run()` resolves the value (argument first, then option), validates it, +applies the default where appropriate, and writes the result back into +`$input`. Returns `false` when a required argument is missing or invalid. See +[Input Arguments](Input-Arguments.md). + +--- + +## `OutputInterface` + +`InitPHP\Console\OutputInterface` — the writing/prompting contract. + +```php +public function write(string $str, array $context = [], bool $newLine = false, array $format = []): void; +public function writeln(string $str, array $context = [], array $format = []): void; +public function list(array $rows, int $leftSpace = 0): void; +public function progressBar($done, $total): void; +public function ask(string $question, bool $empty = true); // mixed +public function question(Question $question); // mixed +public function error(string $msg, array $context = []): void; +public function success(string $msg, array $context = []): void; +public function warning(string $msg, array $context = []): void; +public function info(string $msg, array $context = []): void; +``` + +Implemented by [`Output`](#output). + +> The concrete `Output` uses `[Output::COLOR_DEFAULT]` as the default +> `$format` for `write()`/`writeln()` (the interface declares `[]` since it +> cannot reference the implementation's constants). Both render uncoloured +> text by default. + +--- + +## `Output` + +`InitPHP\Console\Output implements OutputInterface`. + +### Style constants + +**Foreground:** `COLOR_DEFAULT` (39), `COLOR_BLACK` (30), `COLOR_RED` (31), +`COLOR_GREEN` (32), `COLOR_YELLOW` (33), `COLOR_BLUE` (34), `COLOR_MAGENTA` +(35), `COLOR_CYAN` (36), `COLOR_LIGHT_GRAY` (37), `COLOR_DARK_GRAY` (90), +`COLOR_LIGHT_RED` (91), `COLOR_LIGHT_GREEN` (92), `COLOR_LIGHT_YELLOW` (93), +`COLOR_LIGHT_BLUE` (94), `COLOR_LIGHT_MAGENTA` (95), `COLOR_LIGHT_CYAN` (96), +`COLOR_WHITE` (97). + +**Background:** `BACKGROUND_BLACK` (40), `BACKGROUND_RED` (41), +`BACKGROUND_GREEN` (42), `BACKGROUND_YELLOW` (43), `BACKGROUND_BLUE` (44), +`BACKGROUND_MAGENTA` (45), `BACKGROUND_CYAN` (46). + +**Styles:** `ITALIC` (3), `BOLD` (1), `UNDERLINE` (4), `STRIKETHROUGH` (9). + +### Constructor + +```php +public function __construct($stdout = null, $stdin = null); +``` + +`$stdout`/`$stdin` are stream resources, defaulting to `STDOUT`/`STDIN`. Inject +`php://memory` handles to capture output / feed answers in tests. + +### Methods + +```php +public function write(string $str, array $context = [], bool $newLine = false, array $format = [self::COLOR_DEFAULT]): void; +public function writeln(string $str, array $context = [], array $format = [self::COLOR_DEFAULT]): void; +public function list(array $rows, int $leftSpace = 0): void; +public function progressBar($done, $total): void; // throws \InvalidArgumentException +public function ask(string $question, bool $empty = true); +public function question(Question $question); +public function error(string $msg, array $context = []): void; +public function success(string $msg, array $context = []): void; +public function warning(string $msg, array $context = []): void; +public function info(string $msg, array $context = []): void; +``` + +`progressBar()` throws `\InvalidArgumentException` when `$done`/`$total` are +not numeric or when `$total <= 0`. `ask()`/`question()` terminate the process +when the user enters `exit` or `quit`. + +### Protected hook + +```php +protected function terminate(int $code = 0): void; // default: exit($code) +``` + +Override in a subclass (e.g. to throw) so the `exit`/`quit` prompt path can be +exercised in tests without killing the runner. See +[Testing Commands](Recipe-Testing-Commands.md). + +--- + +## `Question` + +`InitPHP\Console\Question` — value object for an interactive question. + +```php +public const NO_DEFAULT = '__Qu€sti0nN0D€f@ultV@lue__'; // sentinel; prefer hasDefault() + +public function isOptional(): bool; +public function optional(): self; +public function notOptional(): self; + +public function hasOption(string $option): bool; // matches verbatim or cast +public function setOptions(array $options): self; +public function getOptions(): array; +public function addOption(string $option, $value = self::NO_DEFAULT): self; + +public function setQuestion(string $question): self; +public function getQuestion(): string; // '' when unset + +public function setDefault($default): self; +public function hasDefault(): bool; +public function getDefault(); // mixed, or NO_DEFAULT when unset +``` + +Default options are `[true, false]`. See [Questions](Questions.md). + +--- + +## `Helpers` + +`InitPHP\Console\Helpers` (final). + +```php +public static function strValueCast(string $value); // mixed +``` + +Casts a raw command-line token to the most appropriate scalar: +`""`→`""`, `"null"`→`null`, `"true"`/`"yes"`→`true`, `"false"`/`"no"`→`false`, +integer-like→`int`, decimal-like (`.` or `,`)→`float`, otherwise the string +unchanged. Keyword matching is case-insensitive. See +[Input → casting](Input.md#automatic-type-casting). + +--- + +## `Utils\Table` + +`InitPHP\Console\Utils\Table` — ASCII/ANSI table renderer. + +### Style constants + +The same `COLOR_*`, `BACKGROUND_*`, `ITALIC`/`BOLD`/`UNDERLINE`/`STRIKETHROUGH` +constants (and values) as [`Output`](#output). + +### Methods + +```php +public static function create(): Table; +public function __toString(): string; // === getContent() + +public function setHeaderStyle(int ...$format): self; // default [BOLD] +public function setCellStyle(int ...$format): self; +public function setBorderStyle(int ...$format): self; +public function setColumnCellStyle(string $column, int ...$format): self; + +public function row(array $assoc): self; // append a row +public function getContent(): string; // render +``` + +`row()` keys form the header (union across rows). Non-string values are +stringified (`[NULL]`, `[TRUE]`, `[FALSE]`, `[ARRAY]`, `[CALLABLE]`, +`[RESOURCE]`, or the class name for objects). Missing cells render as `[NULL]`. +Widths use `mb_strlen()` when available. See [Tables](Tables.md). + +--- + +## Backwards-compatibility alias + +`src/aliases.php` (loaded via Composer `files` autoloading) registers: + +```php +class_alias(\InitPHP\Console\Utils\Table::class, 'InitPHP\\CLITable\\Table'); +``` + +so code written against the old `initphp/cli-table` package keeps working. See +[Migration Guide](Migration-Guide.md). diff --git a/docs/Commands.md b/docs/Commands.md new file mode 100644 index 0000000..c273a6a --- /dev/null +++ b/docs/Commands.md @@ -0,0 +1,179 @@ +# Commands + +A command is the unit of work the [`Application`](API-Reference.md#application) +dispatches to. There are two ways to register one: as a **closure** or as a +**class** extending [`Command`](API-Reference.md#command). + +## Closure commands + +```php +use InitPHP\Console\{Input, Output}; + +$console->register('cache:clear', function (Input $input, Output $output) { + // ... do the work ... + $output->success('Cache cleared.'); +}, 'Clears the application cache.'); +``` + +`register()` has the signature: + +```php +public function register( + string $command, // the name the command is invoked by + ?callable $execute = null, // the handler + string $definition = '' // short description for the listing +): self; +``` + +The handler is invoked with `(Input $input, Output $output)`. Its return value +is ignored. `register()` returns the application, so calls chain: + +```php +$console + ->register('up', $up, 'Run migrations.') + ->register('down', $down, 'Roll back the last batch.'); +``` + +Any PHP callable works — a closure, an invokable object, `'Class::method'`, or +`[$object, 'method']`. + +## Class-based commands + +For richer commands extend `InitPHP\Console\Command`: + +```php +use InitPHP\Console\{Command, Input, InputArgument, Output}; + +final class MakeModelCommand extends Command +{ + public $command = 'make:model'; + + public function definition(): string + { + return 'Generates a model class.'; + } + + public function help(): string + { + return 'Creates a new model in app/Models from the given name.'; + } + + public function arguments(): array + { + return [ + new InputArgument('name', InputArgument::STR, '', false, 'Model class name.'), + ]; + } + + public function execute(Input $input, Output $output) + { + $name = $input->getArgument('name'); + $output->success("Model {$name} created."); + } +} +``` + +Register it **by class name** — the application instantiates it and reads the +metadata from the instance: + +```php +$console->register(MakeModelCommand::class); +``` + +> When the second argument to `register()` is `null`, the first argument is +> treated as a class name. The class must exist and extend `Command`, and its +> `$command` property must be set — otherwise registration throws. See +> [Exceptions](Exceptions.md). + +### The `Command` contract + +| Member | Required | Default | Purpose | +| --- | --- | --- | --- | +| `public $command` | ✅ | — | The name the command is invoked by. Must be set. | +| `execute(Input, Output)` | ✅ | — | Runs the command. | +| `definition(): string` | ❌ | `''` | One-line description for the listing. | +| `help(): string` | ❌ | `'No explanation for this command is specified.'` | Long help for ` --help`. | +| `arguments(): array` | ❌ | `[]` | Array of [`InputArgument`](Input-Arguments.md) declarations. | + +Every entry returned by `arguments()` is validated **before** `execute()` +runs. If a required argument is missing, or a value fails its type check, the +command aborts with an error and `execute()` is never called. See +[Input Arguments](Input-Arguments.md) for the full resolution rules. + +## Grouping in the listing + +If a command name contains a colon, the part before it becomes a group heading +in `php console list`: + +```php +$console->register(MakeModelCommand::class); // group: make +$console->register('make:controller', $fn, 'Make ...'); // group: make +$console->register('serve', $fn, 'Start the server.'); // ungrouped +``` + +``` +[COMMANDS] + +make + make:model : Generates a model class. + make:controller : Make ... + +serve : Start the server. +``` + +The colon is purely a naming convention for display grouping; it has no other +behaviour. + +## Per-command help + +Every command supports an automatic usage screen via the `--help` argument. +For a class-based command it lists the declared parameters and renders a usage +line: + +```bash +php console.php make:model --help +``` + +``` +Creates a new model in app/Models from the given name. + +[PARAMETERS] + --name : Model class name. + +[USAGE] + php console.php make:model --name=(STRING) +``` + +Required parameters are shown bare; optional ones are wrapped in `[ ]`. The +long text comes from `help()` (falling back to `definition()`). + +## Reserved names and lookup + +- `help` and `list` are reserved for the built-in overview and cannot be used + as command names. +- An unknown command prints `The command was not found.` and `run()` returns + `true` (the application handled the invocation gracefully). +- Running with no command at all makes `run()` return `false`. + +## Error handling inside a command + +`execute()` runs inside a `try/catch` in the dispatcher. Any `Throwable` it +raises is caught, its message is printed via `Output::error()`, and `run()` +returns `false`: + +```php +$console->register('risky', function (Input $input, Output $output) { + throw new \RuntimeException('boom'); +}); + +// php console.php risky → [ERROR] boom (run() returns false) +``` + +This means you can `throw` from a command to abort with a message, rather than +calling `exit()` yourself. + +## Where to go next + +- [Input](Input.md) — read arguments, options and segments. +- [Input Arguments](Input-Arguments.md) — declare typed, validated arguments. +- [Output](Output.md) — format the command's output. diff --git a/docs/Exceptions.md b/docs/Exceptions.md new file mode 100644 index 0000000..62435a0 --- /dev/null +++ b/docs/Exceptions.md @@ -0,0 +1,128 @@ +# Exceptions + +`initphp/console` throws only standard SPL exceptions — there are no +package-specific exception classes. This keeps integration simple: catch the +SPL types you already handle. + +``` +\LogicException +└── (thrown by Application::register for a misconfigured Command class) + +\InvalidArgumentException +└── (thrown by Application::register and InputArgument::__construct) +``` + +## When they are raised + +| Trigger | Type | Where | +| --- | --- | --- | +| `register()` given a class name that does not exist | `\InvalidArgumentException` | `Application::register()` | +| `register()` given a class that is not a `Command` | `\InvalidArgumentException` | `Application::register()` | +| A `Command` class whose `$command` is not set | `\LogicException` | `Application::register()` | +| `InputArgument` constructed with an unsupported type | `\InvalidArgumentException` | `InputArgument::__construct()` | +| `InputArgument` default value does not satisfy the type | `\InvalidArgumentException` | `InputArgument::__construct()` | +| `progressBar()` with non-numeric input or `$total <= 0` | `\InvalidArgumentException` | `Output::progressBar()` | + +### Registration errors + +```php +$console->register('App\\Missing\\CommandClass'); +// InvalidArgumentException: The specified executable does not meet the requirements. + +$console->register(\stdClass::class); +// InvalidArgumentException: The specified executable does not meet the requirements. + +final class BadCommand extends \InitPHP\Console\Command { + public function execute($i, $o) {} // forgot: public $command = '...'; +} +$console->register(BadCommand::class); +// LogicException: The command name of the command class is undefined. +``` + +These are programming errors — surface them during development; they should +never reach a released binary. + +### Argument declaration errors + +```php +use InitPHP\Console\InputArgument; + +new InputArgument('age', 'WRONG', 0); +// InvalidArgumentException: The type defined for the --age parameter is not supported. + +new InputArgument('age', InputArgument::INT, 'not-an-int'); +// InvalidArgumentException: The default value for the --age parameter +// must be a type accepted for the parameter. +``` + +### Progress bar errors + +```php +$output->progressBar(1, 0); +// InvalidArgumentException: $total must be greater than zero. + +$output->progressBar('a', 'b'); +// InvalidArgumentException: $done and $total must be integer or float. +``` + +## Errors that surface as output, not exceptions + +Several conditions are handled gracefully at runtime rather than thrown. +During dispatch the `Application` writes a styled `[ERROR]` message via +`Output::error()` and returns `false` from `run()`: + +| Situation | What happens | +| --- | --- | +| Unknown command | `[ERROR] The command was not found.` — `run()` returns `true`. | +| Required argument missing / value invalid | `[ERROR] The -- parameter is …` — `run()` returns `false`, `execute()` is skipped. | +| `arguments()` contains a non-`InputArgument` entry | `[ERROR] One or more arguments are wrong! …` — `run()` returns `false`. | +| Handler is registered but not executable | `[ERROR] The command is not executable; …` — `run()` returns `false`. | + +## Exceptions thrown inside a command + +Any `Throwable` raised inside a command handler (closure or `execute()`) is +caught by the dispatcher, its message is printed via `Output::error()`, and +`run()` returns `false`: + +```php +$console->register('deploy', function ($input, $output) { + if (!is_writable('/var/www')) { + throw new \RuntimeException('Target directory is not writable.'); + } + // ... +}); + +// php console.php deploy +// [ERROR] Target directory is not writable. (run() returns false) +``` + +This lets you abort a command with a clear message by throwing, instead of +calling `exit()` yourself. If you need a specific process exit code, inspect +the boolean return of `run()` in your entry script: + +```php +exit($console->run() ? 0 : 1); +``` + +## Catching registration errors at boot + +Because registration errors are programming mistakes, the usual approach is to +let them bubble during development. If you build commands dynamically (e.g. +from a directory scan) and want a friendlier boot failure, wrap registration: + +```php +try { + foreach ($discoveredCommandClasses as $class) { + $console->register($class); + } +} catch (\LogicException | \InvalidArgumentException $e) { + fwrite(STDERR, 'Command registration failed: ' . $e->getMessage() . PHP_EOL); + exit(1); +} +``` + +## See also + +- [Commands](Commands.md) — registration and the `Command` contract. +- [Input Arguments](Input-Arguments.md) — argument validation behaviour. +- [API Reference](API-Reference.md) — where each exception is documented per method. diff --git a/docs/FAQ.md b/docs/FAQ.md new file mode 100644 index 0000000..473ace3 --- /dev/null +++ b/docs/FAQ.md @@ -0,0 +1,171 @@ +# FAQ + +Quick answers to questions that come up when using the package. If yours is +not here, please [open an issue](https://github.com/InitPHP/Console/issues/new) +— documentation fixes are reviewed eagerly. + +## General + +### What is `initphp/console` for? + +Writing small-to-medium command-line tools in PHP: routing a command name to a +handler, parsing its arguments, printing coloured output, asking questions, +and rendering tables. It is dependency-free and deliberately minimal. + +### What is it NOT for? + +- Deep sub-command trees, shell auto-completion, or a rich argument grammar + (variadics, negatable flags, `--` passthrough). The parser is flat — see + [Input](Input.md). +- A built-in DI/service layer. Compose dependencies yourself; the package only + routes the invocation. +- Output verbosity levels / structured logging out of the box. Build them on + top of [`Output`](Output.md). + +### Does it have any runtime dependencies? + +No. Dev tools (PHPUnit, PHPStan, PHP-CS-Fixer) live under `require-dev`. The +runtime requires PHP only; `ext-mbstring` is an optional enhancement for table +alignment. + +## Terminology + +### Why is `--name` an "argument" but `-v` an "option"? + +That is this library's convention: `--long` tokens are **arguments**, `-short` +tokens are **options**, and bare tokens are **segments**. It is the opposite of +some other frameworks, so double-check when porting code. See +[Input](Input.md#the-three-token-shapes). + +## Usage + +### How do I read a value that may be `--name` or `-name`? + +Declare an [`InputArgument`](Input-Arguments.md): its `run()` looks the value up +as an argument first, then as an option, under the same name. For ad-hoc +reads, check both with `getArgument()` / `getOption()`. + +### Why did `--age=30` come back as an `int`, not a string? + +All tokens are cast by [`Helpers::strValueCast()`](Input.md#automatic-type-casting): +integer-like → `int`, decimal-like → `float`, `true`/`false`/`yes`/`no` → +`bool`, `null` → `null`. Pass it through `(string)` if you need the text form, +or declare the argument as `InputArgument::STR` to have it stringified. + +### How do I give a command a default for a missing argument? + +Two ways: read with a default — `$input->getArgument('name', 'World')` — or +declare an optional [`InputArgument`](Input-Arguments.md) with a default value, +which the framework writes back before `execute()` runs. + +### How do I abort a command with an error message? + +`throw` from the handler. The dispatcher catches any `Throwable`, prints +`[ERROR] `, and `run()` returns `false`. You do not need to call +`exit()` yourself. See [Exceptions](Exceptions.md#exceptions-thrown-inside-a-command). + +### How do I set the process exit code? + +`run()` returns a bool. Map it in your entry script: + +```php +exit($console->run() ? 0 : 1); +``` + +### Why does typing `exit` at a prompt kill my program? + +`ask()` and `question()` treat `exit` and `quit` as a request to terminate — +they call the protected `Output::terminate()`, which `exit`s by default. To +intercept it (cleanup, or testing), subclass `Output` and override +`terminate()`. See [Testing Commands](Recipe-Testing-Commands.md). + +### My yes/no question rejects "yes". Why? + +`question()` accepts an answer only if it is in the question's options. The +default options are `[true, false]`, and `hasOption()` matches the +[cast](Input.md#automatic-type-casting) form — so `"yes"`/`"no"`/`"true"`/`"false"` +all work against the defaults. If you set custom string options +(`setOptions(['y', 'n'])`), the answer must match one of those. See +[Questions](Questions.md#acceptable-answer-matching). + +### Can I register a command as an object method or invokable? + +Yes. The handler is any PHP callable: a closure, `'Class::method'`, +`[$object, 'method']`, or an invokable object. Class-based commands use the +[`Command`](Commands.md) base class and are registered by class name. + +## Output & tables + +### How do I capture output for a test? + +Inject a `php://memory` stream: `new Output($stream)`, then read the stream +after running. See [Output → injecting streams](Output.md#injecting-streams) and +[Testing Commands](Recipe-Testing-Commands.md). + +### Why do my table booleans show as `[TRUE]`/`[FALSE]`? + +That is how non-string values are stringified. Convert to `'yes'`/`'no'` (or +any string) before calling `row()` if you want different text. See +[Tables → how values are rendered](Tables.md#how-values-are-rendered). + +### My UTF-8 table columns are misaligned. + +Install `ext-mbstring`. Widths are measured with `mb_strlen()` when available; +without it the renderer falls back to byte length. See +[Tables → multibyte](Tables.md#multibyte-text). + +## PHP / tooling + +### Which PHP versions are supported? + +PHP **8.2 and up**. CI runs the QA matrix on 8.2, 8.3, 8.4 and 8.5. + +### Why does the code use PHPDoc types instead of native types in places? + +Several signatures (for example `getArgument()`, `ask()` and `question()`) +carry no native type and are documented with PHPDoc. Adding native types to +them would change the contract that subclasses and `InputInterface` / +`OutputInterface` implementations rely on. See the note atop the +[API Reference](API-Reference.md). + +### What is the PHPStan level? + +Level 6, and the source is clean at that level. The coding standard is PER-CS, +checked with PHP-CS-Fixer (`composer cs-check`). + +### Where are the tests? + +Under `tests/` in the source repository. They cover input parsing, argument +validation, output formatting, the question flow, the dispatcher, and the +table renderer — using injected in-memory streams (see +[Testing Commands](Recipe-Testing-Commands.md)). + +## Versioning + +### Is the table renderer the same as `initphp/cli-table`? + +Yes — it was merged in as of 2.1 and the old class name still resolves via a +`class_alias`. See the [Migration Guide](Migration-Guide.md). + +### Will 2.x see breaking changes? + +Not within the 2.x releases. The one pending breaking change, the PHP `^8.2` +requirement, is recorded in the +[changelog](https://github.com/InitPHP/Console/blob/main/CHANGELOG.md) under +"Unreleased". Anything that breaks the public contract (classes, +interfaces, the `Command` hooks, exception behaviour) would require a major +bump. New optional parameters and new methods are added compatibly. + +## Other + +### Where do I report a security issue? + +See [`SECURITY.md`](https://github.com/InitPHP/.github/blob/main/SECURITY.md) +in the InitPHP org profile. Please do not file public issues for +vulnerabilities. + +### Where do I open feature requests or discussions? + +[InitPHP Discussions](https://github.com/orgs/InitPHP/discussions) is the place +for open-ended threads; concrete bug reports and proposals belong in +[the issue tracker](https://github.com/InitPHP/Console/issues). diff --git a/docs/Home.md b/docs/Home.md new file mode 100644 index 0000000..ea9e4a3 --- /dev/null +++ b/docs/Home.md @@ -0,0 +1,87 @@ +# InitPHP Console — Wiki + +Welcome to the official documentation for **`initphp/console`** — a small, +dependency-free toolkit for writing command-line applications in PHP: command +routing, typed arguments, coloured output, interactive prompts, and a +styleable ANSI table renderer. + +```bash +composer require initphp/console +``` + +```php +#!/usr/bin/env php +register('greet', function (Input $input, Output $output) { + $output->writeln('Hello {name}!', ['name' => $input->getArgument('name', 'World')]); +}, 'Greets someone.'); + +$console->run(); +``` + +```bash +php console.php greet --name=Ada # Hello Ada! +php console.php list # Overview of all commands +``` + +## The building blocks + +| Type | Purpose | +| --- | --- | +| [`Application`](API-Reference.md#application) | The command registry and dispatcher. | +| [`Command`](API-Reference.md#command) | Base class for class-based commands. | +| [`Input`](API-Reference.md#input) / [`InputInterface`](API-Reference.md#inputinterface) | Parsed access to arguments, options and segments. | +| [`InputArgument`](API-Reference.md#inputargument) | A typed, validated `--name` argument declaration. | +| [`Output`](API-Reference.md#output) / [`OutputInterface`](API-Reference.md#outputinterface) | Coloured writing, lists, progress bar and prompts. | +| [`Question`](API-Reference.md#question) | A value object describing an interactive question. | +| [`Helpers`](API-Reference.md#helpers) | Scalar value casting shared across the components. | +| [`Utils\Table`](API-Reference.md#utilstable) | A styleable, multibyte-aware ASCII/ANSI table renderer. | + +## Start here + +- **New to the package?** Read [Installation](Installation.md), then [Quick Start](Quick-Start.md). +- **Building commands?** See [Commands](Commands.md), then [Input](Input.md) and [Input Arguments](Input-Arguments.md). +- **Formatting output?** Read [Output](Output.md); for prompts see [Questions](Questions.md). +- **Rendering tables?** See [Tables](Tables.md). +- **Coming from `initphp/cli-table`?** Read the [Migration Guide](Migration-Guide.md). +- **Looking for a specific method?** The full [API Reference](API-Reference.md) lists every class member. + +## A note on terminology + +This library splits the tokens after the command name into three buckets: + +| Token | Shape | Accessor | +| --- | --- | --- | +| **Argument** | `--name`, `--name=value` | `getArgument()` | +| **Option** | `-v`, `-abc`, `-key=value` | `getOption()` | +| **Segment** | bare value, e.g. `migrate` | `getSegment()` | + +> Here `--long` tokens are called **arguments** and `-short` tokens are called +> **options** — the opposite of some other CLI frameworks. Keep it in mind when +> porting code. See [Input](Input.md) for the full grammar. + +## Package metadata + +- **License**: MIT +- **Minimum PHP**: 8.2 (CI matrix runs 8.2 – 8.5) +- **Runtime dependencies**: none +- **Optional extension**: `ext-mbstring` (improves table alignment for UTF-8 values) +- **Packagist**: [`initphp/console`](https://packagist.org/packages/initphp/console) +- **Source**: [github.com/InitPHP/Console](https://github.com/InitPHP/Console) +- **Issues**: [github.com/InitPHP/Console/issues](https://github.com/InitPHP/Console/issues) +- **Discussions**: [github.com/orgs/InitPHP/discussions](https://github.com/orgs/InitPHP/discussions) +- **Security**: [`SECURITY.md`](https://github.com/InitPHP/.github/blob/main/SECURITY.md) + +> Since **2.1** this package also ships the table renderer formerly distributed +> as `initphp/cli-table` (now deprecated). The old class name keeps working via +> a `class_alias` — see [Migration Guide](Migration-Guide.md). + +If something in this wiki is unclear, ambiguous, or wrong, please +[open an issue](https://github.com/InitPHP/Console/issues/new) — +documentation fixes are reviewed eagerly. diff --git a/docs/Input-Arguments.md b/docs/Input-Arguments.md new file mode 100644 index 0000000..944a954 --- /dev/null +++ b/docs/Input-Arguments.md @@ -0,0 +1,149 @@ +# Input Arguments + +[`InputArgument`](API-Reference.md#inputargument) lets a +[class-based command](Commands.md#class-based-commands) declare the `--name` +arguments it accepts, each with a type, a default value and an +optional/required flag. The [`Application`](API-Reference.md#application) +validates them before calling `execute()`. + +## Constructing an argument + +```php +use InitPHP\Console\InputArgument; + +new InputArgument( + string $name, // name without dashes, e.g. "name" + string $type, // one of the type constants below + mixed $default, // must satisfy $type + bool $isOptional = true, + string $definition = '' // description shown in the help screen +); +``` + +The constructor throws `\InvalidArgumentException` when the type is unknown, +or when the default value does not satisfy the declared type: + +```php +new InputArgument('age', InputArgument::INT, 'not-an-int'); +// InvalidArgumentException: The default value for the --age parameter +// must be a type accepted for the parameter. +``` + +## Types + +| Constant | Internal value | Accepts | +| --- | --- | --- | +| `InputArgument::ANY` | `ANY` | Any value. | +| `InputArgument::INT` | `INT` | Integers. | +| `InputArgument::FLOAT` | `FLOAT` | Floats. | +| `InputArgument::NUMERIC` | `NUMBER` | Any numeric value (int, float or numeric string). | +| `InputArgument::BOOL` | `BOOL` | `true`/`false`, or `1`/`0` (coerced to `bool`). | +| `InputArgument::STR` | `STRING` | Strings (numeric/bool values are stringified). | + +Because [`Input`](Input.md#automatic-type-casting) casts values first, `--age=30` +already arrives as `int(30)` and passes the `INT` check, while `--age=abc` +stays a string and fails it. + +> The `NUMERIC` constant's internal value is the string `"NUMBER"` — use the +> `InputArgument::NUMERIC` constant rather than the literal so you never have to +> remember that. + +## How resolution works + +For each declared argument the application calls `run()`, which: + +1. Looks the value up as an **argument** (`--name`) first, then as an + **option** (`-name`). +2. **Missing value:** + - optional → the default is stored, the command proceeds. + - required → an error is printed and the command aborts (`run()` returns `false`). +3. **Present value:** + - valid → kept. A required argument given an empty `''`/`null` value falls + back to its default. + - invalid + optional → replaced with the default. + - invalid + required → an error is printed and the command aborts. + +The resolved value is written back into [`Input`](Input.md), so `execute()` reads +it with `$input->getArgument('name')`. + +## A complete example + +```php +use InitPHP\Console\{Command, Input, InputArgument, Output}; + +final class CreateUserCommand extends Command +{ + public $command = 'user:create'; + + public function arguments(): array + { + return [ + new InputArgument('email', InputArgument::STR, '', false, 'Required e-mail.'), + new InputArgument('age', InputArgument::INT, 18, true, 'Age in years.'), + new InputArgument('admin', InputArgument::BOOL, false, true, 'Grant admin rights.'), + ]; + } + + public function execute(Input $input, Output $output) + { + $email = $input->getArgument('email'); // guaranteed present (required) + $age = $input->getArgument('age'); // int, defaults to 18 + $admin = $input->getArgument('admin'); // bool, defaults to false + + $output->success("Created {$email} (age {$age}, admin: " . ($admin ? 'yes' : 'no') . ')'); + } +} +``` + +```bash +php console.php user:create --email=ada@example.com --age=36 --admin=true +php console.php user:create # [ERROR] The --email parameter is undefined. +php console.php user:create --email=ada@example.com # age=18, admin=false +``` + +## Zero and `false` are real values + +A required argument explicitly set to `0` keeps `0` — it is **not** mistaken +for "missing" and replaced by the default: + +```php +new InputArgument('retries', InputArgument::INT, 5, false); + +// php console.php run --retries=0 → getArgument('retries') === 0 +``` + +(The same applies to `false` and `'0'`. This is a deliberate behaviour of the +resolver.) + +## Boolean coercion + +`BOOL` accepts a real boolean, or the integers `1`/`0`, which are coerced to +`true`/`false`: + +```php +new InputArgument('force', InputArgument::BOOL, false); + +// --force=true → true (Input casts "true" → bool true) +// --force=1 → true (1 coerced to bool) +// --force=0 → false +``` + +## Reading the metadata + +The help renderer (and your own code) can introspect an argument: + +```php +$arg = new InputArgument('age', InputArgument::INT, 18, false, 'The age.'); + +$arg->getName(); // "--age" (note the leading dashes) +$arg->getType(); // "INT" +$arg->getDefault(); // "18" (string form, or null when no default) +$arg->getDefinition(); // "The age." +$arg->isOptional(); // false +``` + +## Where to go next + +- [Commands](Commands.md) — how `arguments()` plugs into a command. +- [Input](Input.md) — the parsing and casting that feeds these arguments. +- [API Reference](API-Reference.md#inputargument) — every method and constant. diff --git a/docs/Input.md b/docs/Input.md new file mode 100644 index 0000000..6885eea --- /dev/null +++ b/docs/Input.md @@ -0,0 +1,151 @@ +# Input + +[`Input`](API-Reference.md#input) parses the tokens that follow the command name +into three buckets and exposes them through a small, symmetric API. It +implements [`InputInterface`](API-Reference.md#inputinterface), so you can +type-hint the interface in your own helpers. + +## The three token shapes + +| Shape | Bucket | Example | +| --- | --- | --- | +| `--name` | argument | `--verbose` | +| `--name=value` | argument | `--name=John` | +| `-x` | option | `-v` | +| `-xyz` (combined) | option | `-abc` → `a`, `b`, `c` | +| `-key=value` | option | `-level=5` | +| bare token | segment | `migrate`, `42` | + +> In this library `--long` tokens are **arguments** and `-short` tokens are +> **options** — the opposite of some other CLI frameworks. + +A token consisting only of dashes and/or whitespace (such as a lone `--`) +carries no data and is skipped entirely. + +## Automatic type casting + +Every argument value, option value and segment is normalised with +[`Helpers::strValueCast()`](API-Reference.md#helpers): + +| Input string | Result | +| --- | --- | +| `"true"`, `"yes"` | `true` | +| `"false"`, `"no"` | `false` | +| `"null"` | `null` | +| `"42"`, `"-7"`, `"+7"` | `int` | +| `"3.14"`, `"3,14"` | `float` | +| `""` (empty) | `""` (empty string) | +| anything else | `string` | + +Matching of the keyword literals is case-insensitive (`TRUE` == `true`). Both +`.` and `,` are accepted as the decimal separator (the comma form is +normalised to a dot before casting). + +```php +use InitPHP\Console\Input; + +$input = new Input(['--age=30', '--active=true', '--ratio=1,5', 'deploy']); + +$input->getArgument('age'); // int(30) +$input->getArgument('active'); // bool(true) +$input->getArgument('ratio'); // float(1.5) +$input->getSegment(0); // string("deploy") +``` + +## Arguments — `--long` + +```php +$input->hasArgument('name'); // bool +$input->getArgument('name', $default); // value, or $default (default null) +$input->allArguments(); // ['name' => 'John', ...] +``` + +A bare `--flag` (no `=value`) is stored as an empty string `''`, so +`hasArgument('flag')` is `true` and `getArgument('flag')` is `''`: + +```php +$input = new Input(['--verbose', '--name=John']); + +$input->hasArgument('verbose'); // true +$input->getArgument('verbose'); // '' +$input->getArgument('name'); // 'John' +``` + +## Options — `-short` + +```php +$input->hasOption('v'); // bool +$input->getOption('level', $def); // value, or $def (default null) +$input->allOptions(); // ['v' => 'v', 'level' => 5, ...] +``` + +A single short flag resolves to its own letter as the value, and combined +flags expand to one entry per letter: + +```php +$input = new Input(['-v', '-abc', '-level=5']); + +$input->getOption('v'); // 'v' +$input->allOptions(); // ['v' => 'v', 'a' => 'a', 'b' => 'b', 'c' => 'c', 'level' => 5] +``` + +> Combined short flags (`-abc`) only expand when there is no `=`. A token like +> `-level=5` is treated as a single named option, not as the flags `l e v ...`. + +## Segments — bare positional tokens + +Segments are bare tokens (no leading dash), indexed in the order they appear: + +```php +$input = new Input(['migrate', 'up', '3']); + +$input->hasSegment(0); // true +$input->getSegment(0); // 'migrate' +$input->getSegment(1); // 'up' +$input->getSegment(2); // int(3) +$input->getSegment(9, 'fallback'); // 'fallback' +$input->allSegment(); // ['migrate', 'up', 3] +``` + +## Importing values + +`importArguments()` merges one or more `name => value` maps into the parsed +arguments (later maps win). It is used internally by +[`InputArgument`](Input-Arguments.md) to write resolved defaults back, and is +available to you too: + +```php +$input->importArguments(['name' => 'fallback'], ['env' => 'prod']); +``` + +## Programming to the interface + +```php +use InitPHP\Console\InputInterface; + +function resolveName(InputInterface $input): string +{ + return (string) $input->getArgument('name', 'World'); +} +``` + +`InputInterface` declares every public reader plus `allOptions()` and +`importArguments()` — see the [API Reference](API-Reference.md#inputinterface). + +## A worked example + +```php +// php console.php deploy app1 --env=prod --force -v +$input = new Input(['app1', '--env=prod', '--force', '-v']); + +$input->getSegment(0); // 'app1' +$input->getArgument('env'); // 'prod' +$input->hasArgument('force'); // true (value is '') +$input->hasOption('v'); // true +``` + +## Where to go next + +- [Input Arguments](Input-Arguments.md) — turn raw input into typed, validated values. +- [Commands](Commands.md) — where `Input` is handed to your handler. +- [API Reference](API-Reference.md#input) — every method, with signatures. diff --git a/docs/Installation.md b/docs/Installation.md new file mode 100644 index 0000000..9e7d149 --- /dev/null +++ b/docs/Installation.md @@ -0,0 +1,90 @@ +# Installation + +## Requirements + +| | | +| --- | --- | +| PHP | `^8.2` (CI runs 8.2, 8.3, 8.4 and 8.5) | +| Extensions | None required; `ext-mbstring` recommended | +| Runtime dependencies | None | + +The package has zero runtime dependencies. Development dependencies +(PHPUnit, PHPStan, PHP-CS-Fixer) live under `require-dev` and are not +installed when you depend on `initphp/console` from another project. + +`ext-mbstring` is optional: the [table renderer](Tables.md) uses `mb_strlen()` +when it is available so multibyte (UTF-8) columns align correctly, and falls +back to `strlen()` otherwise. + +## Install via Composer + +```bash +composer require initphp/console +``` + +The classes are autoloaded under the `InitPHP\Console` namespace via PSR-4, +and a small backwards-compatibility shim is loaded via Composer's `files` +autoloading: + +```json +{ + "autoload": { + "psr-4": { + "InitPHP\\Console\\": "src/" + }, + "files": [ + "src/aliases.php" + ] + } +} +``` + +The `files` entry registers the `\InitPHP\CLITable\Table` alias used by the +[migration path](Migration-Guide.md) from the old `initphp/cli-table` package. + +## Verifying the install + +Create `console.php`: + +```php +#!/usr/bin/env php +register('ping', function (Input $input, Output $output) { + $output->success('pong'); +}, 'Health check.'); + +$console->run(); +``` + +Run it: + +```bash +php console.php ping # [SUCCESS] pong +php console.php list # banner + command listing +``` + +If the autoloader cannot locate the classes, double-check that you ran +`composer install` (or `composer dump-autoload`) and that your script requires +`vendor/autoload.php` before using the application. + +## Supported PHP versions in CI + +Every pull request runs the QA matrix (coding standards, static analysis, +unit tests) against: + +- PHP 8.2, 8.3, 8.4, 8.5 + +If you discover a regression on a supported version, please +[file an issue](https://github.com/InitPHP/Console/issues/new) and include the +PHP version reported by `php -v`. + +## Next steps + +- Take the five-minute tour in [Quick Start](Quick-Start.md). +- Learn the two ways to declare commands in [Commands](Commands.md). +- Upgrading from `initphp/cli-table`? Read the [Migration Guide](Migration-Guide.md). diff --git a/docs/Migration-Guide.md b/docs/Migration-Guide.md new file mode 100644 index 0000000..dd53407 --- /dev/null +++ b/docs/Migration-Guide.md @@ -0,0 +1,128 @@ +# Migration Guide + +This page covers two things: + +1. Moving from the standalone **`initphp/cli-table`** package to the table + renderer now bundled here (the main reason this guide exists). +2. Notes on the **2.x line** of `initphp/console` itself. + +--- + +## From `initphp/cli-table` + +The standalone [`initphp/cli-table`](https://github.com/InitPHP/CLITable) +package was merged into `initphp/console` as of **2.1** and is now deprecated. +The renderer now lives at `InitPHP\Console\Utils\Table`. + +### 1. Switch the dependency + +```diff + "require": { +- "initphp/cli-table": "^1.0", ++ "initphp/console": "^2.1" + } +``` + +```bash +composer update initphp/console +``` + +`initphp/console` declares a Composer `replace` for `initphp/cli-table`, so the +two are never installed side by side — even if a transitive dependency still +asks for the old one. + +### 2. (Optional) update your imports + +**No code change is strictly required.** The package registers a `class_alias` +so the legacy fully-qualified name keeps resolving: + +```php +use InitPHP\CLITable\Table; // still works — backed by the alias +``` + +When you next touch the code, prefer the canonical namespace: + +```php +// Before +use InitPHP\CLITable\Table; + +// After +use InitPHP\Console\Utils\Table; +``` + +The public API is unchanged — `create()`, `row()`, `setHeaderStyle()`, +`setCellStyle()`, `setBorderStyle()`, `setColumnCellStyle()`, `getContent()` +and `__toString()` all behave exactly as before. See [Tables](Tables.md). + +### How the alias works + +`src/aliases.php` (loaded via Composer's `files` autoloading) runs: + +```php +if (!class_exists(\InitPHP\CLITable\Table::class, false)) { + class_alias( + \InitPHP\Console\Utils\Table::class, + 'InitPHP\\CLITable\\Table' + ); +} +``` + +The `class_exists(..., false)` check (autoload disabled) is a safety net: if +the legacy class were somehow already loaded, the alias is skipped to avoid a +"cannot redeclare class" fatal. In normal use the `replace` directive +guarantees the legacy class is absent, so the alias is always created. + +### Deprecation timeline + +Treat `InitPHP\CLITable\Table` as deprecated. The alias is a transition aid and +may be removed in a future major release — migrate to +`InitPHP\Console\Utils\Table` at your convenience. + +--- + +## Within the 2.x line + +`2.x` is backwards compatible across its minor releases. Highlights relevant to +upgraders: + +- **Bundled table renderer (2.1).** As above — `initphp/cli-table` is now part + of this package. +- **Interfaces.** [`Input`](Input.md) implements + [`InputInterface`](API-Reference.md#inputinterface) and [`Output`](Output.md) + implements [`OutputInterface`](API-Reference.md#outputinterface). Existing code + that type-hints the concrete classes is unaffected; new code can depend on + the interfaces. +- **Injectable I/O.** `Output` now accepts optional stream resources + (`new Output($stdout, $stdin)`) and `Application` accepts an optional + `Output` (3rd constructor argument). `Application::run()` accepts an optional + `$argv`. All are additive — calling them with no arguments behaves as before. + See [Testing Commands](Recipe-Testing-Commands.md). + +### Behavioural fixes to be aware of + +These correct clear bugs; in the rare case you relied on the old behaviour, +adjust as noted. + +| Area | Old behaviour | Now | +| --- | --- | --- | +| Combined short flags `-abc` | also stored a spurious `abc` option key | stores only `a`, `b`, `c` ([Input](Input.md#options---short)) | +| `Question::hasOption()` | loose comparison accepted *any* non-empty answer against the default `[true, false]` | strict match, plus a [cast](Input.md#automatic-type-casting) fallback ([Questions](Questions.md#acceptable-answer-matching)) | +| Required `InputArgument` given `0`/`false`/`''` | treated as "empty" and replaced by the default | a real `0`/`false` is kept ([Input Arguments](Input-Arguments.md#zero-and-false-are-real-values)) | +| `Output::progressBar()` with `$total = 0` | division-by-zero error | throws `\InvalidArgumentException` ([Output](Output.md#progress-bar)) | +| Value casting of tokens like `\|123` | mis-parsed as numeric | returned unchanged as a string ([Input](Input.md#automatic-type-casting)) | + +If any of these surprise you, the linked pages document the current behaviour +precisely. + +## PHP requirement in the next release + +The unreleased changes require PHP `^8.2` (the 2.x releases supported +`>=7.2`) and are listed as breaking in the +[changelog](https://github.com/InitPHP/Console/blob/main/CHANGELOG.md). +Stay on a 2.x release if you still run PHP 7.2 through 8.1. + +## See also + +- [Tables](Tables.md) — the renderer you are migrating to. +- [FAQ](FAQ.md) — common questions. +- [API Reference](API-Reference.md) — the full surface. diff --git a/docs/Output.md b/docs/Output.md new file mode 100644 index 0000000..4fcaae7 --- /dev/null +++ b/docs/Output.md @@ -0,0 +1,161 @@ +# Output + +[`Output`](API-Reference.md#output) writes coloured/styled text to an output +stream and reads interactive answers from an input stream. Both streams +default to `STDOUT`/`STDIN` but can be injected — see +[Testing Commands](Recipe-Testing-Commands.md). It implements +[`OutputInterface`](API-Reference.md#outputinterface). + +## Writing text + +```php +$output->write('No trailing newline'); +$output->writeln('With a trailing newline'); +``` + +`writeln()` is `write()` with the newline flag set. + +### Placeholder interpolation + +The `$context` map replaces `{key}` tokens in the string. Array values and +objects without `__toString()` are left untouched (so a stray `{` in your text +is safe): + +```php +$output->writeln('Deployed {app} to {env}', [ + 'app' => 'api', + 'env' => 'production', +]); +// Deployed api to production +``` + +### Styling with SGR codes + +The last argument is a list of SGR codes applied to the whole string. For +`writeln()` it is the third argument; for `write()` the fourth: + +```php +$output->writeln('Important', [], [Output::COLOR_RED, Output::BOLD]); +$output->writeln('On blue', [], [Output::COLOR_WHITE, Output::BACKGROUND_BLUE]); +$output->write('inline', [], false, [Output::COLOR_GREEN]); +``` + +Available constants: + +**Foreground colours** + +`COLOR_DEFAULT`, `COLOR_BLACK`, `COLOR_RED`, `COLOR_GREEN`, `COLOR_YELLOW`, +`COLOR_BLUE`, `COLOR_MAGENTA`, `COLOR_CYAN`, `COLOR_LIGHT_GRAY`, +`COLOR_DARK_GRAY`, `COLOR_LIGHT_RED`, `COLOR_LIGHT_GREEN`, +`COLOR_LIGHT_YELLOW`, `COLOR_LIGHT_BLUE`, `COLOR_LIGHT_MAGENTA`, +`COLOR_LIGHT_CYAN`, `COLOR_WHITE` + +**Backgrounds** + +`BACKGROUND_BLACK`, `BACKGROUND_RED`, `BACKGROUND_GREEN`, `BACKGROUND_YELLOW`, +`BACKGROUND_BLUE`, `BACKGROUND_MAGENTA`, `BACKGROUND_CYAN` + +**Text styles** + +`BOLD`, `ITALIC`, `UNDERLINE`, `STRIKETHROUGH` + +> The same constants exist on [`Utils\Table`](Tables.md), so a palette you pick +> for messages also drives table styling. + +## Message helpers + +Pre-styled, prefixed one-liners. Each accepts an optional `$context` map: + +```php +$output->error('Disk full'); // [ERROR] white on red, bold +$output->success('Done'); // [SUCCESS] white on green, bold +$output->warning('Low memory'); // [WARNING] white on yellow, bold +$output->info('Cache warmed'); // [INFO] cyan +$output->error('User {id} not found', ['id' => 42]); +``` + +## Key/value lists + +```php +$output->list([ + 'Host' => 'localhost', + 'Port' => 8080, + 'TLS' => 'enabled', +]); +``` + +``` +Host : localhost +Port : 8080 +TLS : enabled +``` + +The optional second argument indents the whole block by N tab stops — this is +how the built-in help screen indents grouped commands: + +```php +$output->list(['make:model' => 'Generates a model.'], 1); +``` + +## Progress bar + +`progressBar($done, $total)` renders a single, in-place updating line. `$done` +and `$total` must be numeric and `$total` must be greater than zero, otherwise +it throws `\InvalidArgumentException`: + +```php +$total = 50; +for ($i = 0; $i <= $total; $i++) { + $output->progressBar($i, $total); + usleep(20_000); +} +$output->writeln(''); // move off the progress line when finished +``` + +``` +[==============================> ] - 60% 30/50 +``` + +## Interactive prompts + +`ask()` and `question()` read a line from the input stream. See +[Questions](Questions.md) for the full treatment. + +```php +$name = $output->ask('What is your name?'); // free-form, type-cast answer +$ok = $output->ask('Cannot be empty:', false); // re-asks on empty input +``` + +Typing `exit` or `quit` at any prompt terminates the application. + +## Injecting streams + +Pass stream resources to capture output or feed answers — invaluable for +tests: + +```php +$buffer = fopen('php://memory', 'r+'); +$output = new Output($buffer); // first arg: output stream + +$output->writeln('hello'); + +rewind($buffer); +echo stream_get_contents($buffer); // "\e[39mhello\e[0m\n" +``` + +The second constructor argument overrides the input stream used by +`ask()`/`question()`. See [Testing Commands](Recipe-Testing-Commands.md). + +## Programming to the interface + +`Output` implements `OutputInterface`; type-hint that interface where you only +need the public surface. (Note: [`Command::execute()`](Commands.md) and +[`InputArgument::run()`](Input-Arguments.md) are typed against the concrete +`Output` for backwards compatibility — see the +[API Reference](API-Reference.md#outputinterface).) + +## Where to go next + +- [Questions](Questions.md) — structured, option-constrained prompts. +- [Tables](Tables.md) — render tabular data with the same colour palette. +- [API Reference](API-Reference.md#output) — every method and constant. diff --git a/docs/Questions.md b/docs/Questions.md new file mode 100644 index 0000000..05ab5dd --- /dev/null +++ b/docs/Questions.md @@ -0,0 +1,156 @@ +# Questions + +[`Output`](Output.md) offers two ways to read input from the user: free-form +`ask()` and the option-constrained `question()` built around the +[`Question`](API-Reference.md#question) value object. + +## `ask()` — free-form input + +```php +$name = $output->ask('What is your name?'); +``` + +- The prompt is printed, then a line is read from the input stream. +- The answer is run through the same + [type casting](Input.md#automatic-type-casting) as command input, so `"42"` + comes back as `int(42)`, `"yes"` as `true`, and so on. +- Passing `false` as the second argument rejects an empty answer and keeps + asking until something is entered: + +```php +$value = $output->ask('This cannot be empty:', false); +``` + +- Typing `exit` or `quit` terminates the application. + +## `question()` — constrained input + +`Question` describes the prompt, the set of acceptable answers, whether it is +optional, and a default. Configure it fluently, then hand it to +`Output::question()`: + +```php +use InitPHP\Console\Question; + +$question = (new Question()) + ->setQuestion('Pick an environment:') + ->setOptions(['dev', 'staging', 'prod']) + ->optional() + ->setDefault('dev'); + +$env = $output->question($question); +``` + +Behaviour when an answer is submitted: + +1. If it matches one of the options → the (cast) answer is returned. +2. If it is `exit` / `quit` → the application terminates. +3. If the question is **optional** → the default is returned (or the raw + answer when no default is set). +4. If the question is **required** and nothing matched → the user is asked + again. + +## Acceptable-answer matching + +`hasOption()` matches both the verbatim answer and its +[cast](Input.md#automatic-type-casting) form, so string input lines up with +boolean or numeric options: + +```php +$q = new Question(); // default options: [true, false] + +$q->hasOption('true'); // true ("true" casts to bool true) +$q->hasOption('yes'); // true ("yes" casts to bool true) +$q->hasOption('false'); // true +$q->hasOption('maybe'); // false +``` + +For a yes/no prompt you can therefore rely on the defaults, or set explicit +string options: + +```php +(new Question()) + ->setQuestion('Continue?') + ->setOptions(['yes', 'no']); +``` + +## Defaults + +A default is distinct from "no default": `Question` tracks whether one was set +rather than inferring it from the value, so `null` is a perfectly valid +default. + +```php +$q = new Question(); + +$q->hasDefault(); // false +$q->getDefault(); // Question::NO_DEFAULT (sentinel) + +$q->setDefault('home'); +$q->hasDefault(); // true +$q->getDefault(); // 'home' + +(new Question())->setDefault(null)->hasDefault(); // true +``` + +`Question::NO_DEFAULT` is a public sentinel constant; prefer `hasDefault()` +over comparing against it. + +## The `Question` API at a glance + +| Method | Purpose | +| --- | --- | +| `setQuestion(string)` / `getQuestion()` | The prompt text (empty string when unset). | +| `setOptions(array)` / `getOptions()` | Replace / read the acceptable answers. | +| `addOption(string)` | Append a single acceptable answer. | +| `hasOption(string)` | Whether an answer is acceptable (verbatim or cast). | +| `optional()` / `notOptional()` / `isOptional()` | Toggle / read the optional flag. | +| `setDefault(mixed)` / `getDefault()` / `hasDefault()` | Manage the default answer. | + +> **`addOption()` compatibility note.** A legacy two-argument form +> `addOption($label, $value)` is still honoured: when a second argument is +> given it is the value that gets registered and the first acts only as a +> label. Prefer the single-argument form `addOption($value)` in new code. + +## A worked example + +```php +use InitPHP\Console\Question; + +$confirm = (new Question()) + ->setQuestion('Delete all records? [yes/no]') + ->setOptions(['yes', 'no']) + ->notOptional(); + +if ($output->question($confirm) === 'yes') { + // ... destructive action ... + $output->success('Done.'); +} else { + $output->info('Cancelled.'); +} +``` + +## Testing prompts + +Inject an input stream pre-seeded with the answers: + +```php +use InitPHP\Console\Output; + +$stdin = fopen('php://memory', 'r+'); +fwrite($stdin, "Ada\n"); +rewind($stdin); + +$output = new Output(STDOUT, $stdin); +$output->ask('Name?'); // 'Ada' +``` + +See [Testing Commands](Recipe-Testing-Commands.md) for a complete strategy, +including how to exercise the `exit`/`quit` path without killing the test +runner. + +## Where to go next + +- [Output](Output.md) — the writer that prints the prompts. +- [Recipe: Interactive Installer](Recipe-Interactive-Installer.md) — questions + progress in a real flow. +- [API Reference](API-Reference.md#question) — every method and the sentinel. diff --git a/docs/Quick-Start.md b/docs/Quick-Start.md new file mode 100644 index 0000000..d186817 --- /dev/null +++ b/docs/Quick-Start.md @@ -0,0 +1,206 @@ +# Quick Start + +A five-minute tour of the public API. Every snippet runs as-is. + +## 1. The entry script + +A console application is one `Application` instance that you register commands +on and then `run()`: + +```php +#!/usr/bin/env php +run(); +``` + +`run()` reads the global `$argv` by default. You can also pass an explicit +token list — handy for tests: + +```php +$console->run(['console.php', 'greet', '--name=Ada']); +``` + +## 2. A closure command + +```php +$console->register('greet', function (Input $input, Output $output) { + $output->writeln('Hello {name}!', [ + 'name' => $input->getArgument('name', 'World'), + ]); +}, 'Greets someone.'); +``` + +```bash +php console.php greet --name=Ada # Hello Ada! +php console.php greet # Hello World! +``` + +The third argument to `register()` is a short description shown in the +command listing. + +## 3. Reading input + +Tokens after the command name fall into three buckets — **arguments** +(`--long`), **options** (`-short`) and **segments** (bare values) — and scalar +values are cast automatically: + +```php +$console->register('show', function (Input $input, Output $output) { + $input->getArgument('age'); // --age=30 → int(30) + $input->getArgument('active'); // --active=true → bool(true) + $input->getOption('v'); // -v → 'v' + $input->getSegment(0); // first bare token +}, 'Demonstrates input.'); +``` + +See [Input](Input.md) for the full grammar. + +## 4. A class-based command + +For anything beyond a one-liner, extend `Command` and declare typed arguments: + +```php +use InitPHP\Console\{Command, Input, InputArgument, Output}; + +final class MakeModelCommand extends Command +{ + public $command = 'make:model'; + + public function definition(): string + { + return 'Generates a model class.'; + } + + public function arguments(): array + { + return [ + new InputArgument('name', InputArgument::STR, '', false, 'Model class name.'), + new InputArgument('force', InputArgument::BOOL, false, true, 'Overwrite if it exists.'), + ]; + } + + public function execute(Input $input, Output $output) + { + $output->success('Model ' . $input->getArgument('name') . ' created.'); + } +} + +$console->register(MakeModelCommand::class); +``` + +Declared arguments are validated **before** `execute()` runs: + +```bash +php console.php make:model --name=User --force=true +php console.php make:model # [ERROR] The --name parameter is undefined. +php console.php make:model --help # generated usage + parameter list +``` + +See [Commands](Commands.md) and [Input Arguments](Input-Arguments.md). + +## 5. Coloured output and messages + +```php +$output->writeln('Plain line'); +$output->writeln('Coloured', [], [Output::COLOR_GREEN, Output::BOLD]); + +$output->error('Something failed'); +$output->success('All good'); +$output->warning('Heads up'); +$output->info('FYI'); + +$output->list(['Host' => 'localhost', 'Port' => 8080]); +``` + +See [Output](Output.md). + +## 6. Asking questions + +```php +use InitPHP\Console\Question; + +$name = $output->ask('What is your name?'); + +$question = (new Question()) + ->setQuestion('Continue? (yes/no)') + ->setOptions(['yes', 'no']) + ->optional() + ->setDefault('no'); + +$answer = $output->question($question); +``` + +See [Questions](Questions.md). + +## 7. Rendering a table + +```php +use InitPHP\Console\Utils\Table; + +echo Table::create() + ->setHeaderStyle(Table::COLOR_CYAN, Table::BOLD) + ->row(['id' => 1, 'name' => 'Ada', 'admin' => true]) + ->row(['id' => 2, 'name' => 'Linus', 'admin' => false]); +``` + +See [Tables](Tables.md). + +## The built-in `help` / `list` command + +`help` and `list` are reserved. Running either prints the banner, the +application name/version and every registered command, grouped by the prefix +before a `:` in the command name: + +```bash +php console.php list +``` + +## How dispatch works + +`Application::run()`: + +1. Reads the token list, from the global `$argv` or from the array you pass. +2. Drops the script name (`$argv[0]`) and takes the next token as the + **command name**. With no command token, `run()` returns `false`. +3. Wraps the remaining tokens in an [`Input`](Input.md) object and creates an + [`Output`](Output.md) unless one was injected. +4. Dispatches: + - `help` / `list` renders the command overview. + - an unknown name prints `The command was not found.`; `run()` returns `true`. + - a registered command with the `--help` argument renders that command's + usage. + - any other registered command runs its handler. For a class-based command + the declared arguments are validated first. + +## Injecting output + +The constructor accepts an optional `Output` as its third argument. Back it +with an in-memory stream to capture everything a command prints: + +```php +use InitPHP\Console\Output; + +$stream = fopen('php://memory', 'r+'); +$console = new Application('Acme CLI', '1.0.0', new Output($stream)); +$console->run(['bin/console', 'greet', '--name=Ada']); + +rewind($stream); +echo stream_get_contents($stream); +``` + +See [Testing Commands](Recipe-Testing-Commands.md) for a full test harness. + +## Where to go next + +- [Commands](Commands.md) — closures vs. classes, grouping, per-command help. +- [Input](Input.md) — arguments, options, segments and casting. +- [Input Arguments](Input-Arguments.md) — typed validation and defaults. +- [API Reference](API-Reference.md) — exhaustive method list. diff --git a/docs/Recipe-Git-Like-CLI.md b/docs/Recipe-Git-Like-CLI.md new file mode 100644 index 0000000..f6da4be --- /dev/null +++ b/docs/Recipe-Git-Like-CLI.md @@ -0,0 +1,173 @@ +# Recipe: A Git-like CLI + +Build a small multi-command binary — grouped, class-based commands with typed +arguments and a clean help screen. The shape generalises to any tool with a +handful of sub-commands (`make:*`, `db:*`, `cache:*`, …). + +## The entry script + +```php +#!/usr/bin/env php +register(InitCommand::class); +$app->register(AddCommand::class); +$app->register(CommitCommand::class); +$app->register(LogCommand::class); + +exit($app->run() ? 0 : 1); +``` + +## A leaf command + +```php +namespace App\Command; + +use InitPHP\Console\{Command, Input, Output}; + +final class InitCommand extends Command +{ + public $command = 'init'; + + public function definition(): string + { + return 'Create an empty repository.'; + } + + public function execute(Input $input, Output $output) + { + // ... create the .vcs directory ... + $output->success('Initialised empty VCS repository.'); + } +} +``` + +## A command with a required argument + +```php +namespace App\Command; + +use InitPHP\Console\{Command, Input, InputArgument, Output}; + +final class CommitCommand extends Command +{ + public $command = 'commit'; + + public function definition(): string + { + return 'Record changes to the repository.'; + } + + public function help(): string + { + return 'Creates a new commit containing the staged changes.'; + } + + public function arguments(): array + { + return [ + new InputArgument('message', InputArgument::STR, '', false, 'Commit message.'), + new InputArgument('amend', InputArgument::BOOL, false, true, 'Amend the previous commit.'), + ]; + } + + public function execute(Input $input, Output $output) + { + $message = $input->getArgument('message'); // required → guaranteed present + $amend = $input->getArgument('amend'); // bool, defaults to false + + if ($amend) { + $output->info('Amending the previous commit…'); + } + + // ... write the commit ... + $output->success('Created commit: ' . $message); + } +} +``` + +```bash +php bin/vcs commit --message="Initial import" +php bin/vcs commit --message="Fix typo" --amend=true +php bin/vcs commit # [ERROR] The --message parameter is undefined. +php bin/vcs commit --help # generated usage + parameters +``` + +## Grouping sub-commands + +Name commands `group:action` so the listing clusters them: + +```php +final class RemoteAddCommand extends Command +{ + public $command = 'remote:add'; + public function definition(): string { return 'Add a remote.'; } + // ... +} + +final class RemoteRemoveCommand extends Command +{ + public $command = 'remote:remove'; + public function definition(): string { return 'Remove a remote.'; } + // ... +} +``` + +```bash +php bin/vcs list +``` + +``` +[COMMANDS] + +remote + remote:add : Add a remote. + remote:remove : Remove a remote. + +init : Create an empty repository. +commit : Record changes to the repository. +``` + +## Positional sub-arguments via segments + +If you prefer `vcs log 10` over `vcs log --limit=10`, read a +[segment](Input.md#segments--bare-positional-tokens) instead of declaring an +argument: + +```php +final class LogCommand extends Command +{ + public $command = 'log'; + + public function execute(Input $input, Output $output) + { + $limit = $input->getSegment(0, 20); // `vcs log 10` → 10; default 20 + // ... print the last $limit commits ... + } +} +``` + +> Segments are not validated by the framework (only declared +> [`InputArgument`](Input-Arguments.md)s are). Validate them yourself inside +> `execute()` if they must be, say, a positive integer. + +## Mapping results to exit codes + +`run()` returns `false` when a command fails (missing argument, thrown +exception, …). Forward that to the shell so scripts and CI can react: + +```php +exit($app->run() ? 0 : 1); +``` + +## See also + +- [Commands](Commands.md) · [Input Arguments](Input-Arguments.md) · [Input](Input.md) +- [Recipe: Testing Commands](Recipe-Testing-Commands.md) — test the binary above. diff --git a/docs/Recipe-Interactive-Installer.md b/docs/Recipe-Interactive-Installer.md new file mode 100644 index 0000000..354eeb8 --- /dev/null +++ b/docs/Recipe-Interactive-Installer.md @@ -0,0 +1,129 @@ +# Recipe: Interactive Installer + +A guided "setup wizard" command that asks a few questions, applies sensible +defaults, shows progress while it works, and reports the result. It combines +[`ask()`](Questions.md#ask--free-form-input), +[`Question`](Questions.md#question--constrained-input), +[`progressBar()`](Output.md#progress-bar) and the +[message helpers](Output.md#message-helpers). + +## The command + +```php +namespace App\Command; + +use InitPHP\Console\{Command, Input, Output, Question}; + +final class InstallCommand extends Command +{ + public $command = 'app:install'; + + public function definition(): string + { + return 'Interactive project setup.'; + } + + public function execute(Input $input, Output $output) + { + $output->writeln('Welcome! Let’s set up your project.', [], [Output::COLOR_CYAN, Output::BOLD]); + + // 1. Free-form question with a default applied manually. + $name = $output->ask('Project name [my-app]:'); + if ($name === '') { + $name = 'my-app'; + } + + // 2. Constrained, optional question with a default. + $driver = $output->question( + (new Question()) + ->setQuestion('Database driver? [mysql/pgsql/sqlite]') + ->setOptions(['mysql', 'pgsql', 'sqlite']) + ->optional() + ->setDefault('sqlite') + ); + + // 3. A yes/no confirmation (relies on the default [true, false] options). + $seed = $output->question( + (new Question()) + ->setQuestion('Seed demo data? [yes/no]') + ->optional() + ->setDefault(false) + ); + + $output->writeln(''); + $output->list([ + 'Project' => $name, + 'Driver' => $driver, + 'Seed' => $seed ? 'yes' : 'no', + ]); + $output->writeln(''); + + // 4. Do the work with a progress bar. + $steps = ['Writing config', 'Creating directories', 'Installing assets', 'Finalising']; + $total = count($steps); + foreach ($steps as $i => $label) { + // ... perform $label ... + $output->progressBar($i + 1, $total); + } + $output->writeln(''); // leave the progress line + + $output->success("Project “{$name}” is ready."); + } +} +``` + +```bash +php console.php app:install +``` + +``` +Welcome! Let’s set up your project. +Project name [my-app]: +Database driver? [mysql/pgsql/sqlite] +Seed demo data? [yes/no] + +Project : my-app +Driver : sqlite +Seed : no + +[========================================>] - 100% 4/4 +[SUCCESS] Project “my-app” is ready. +``` + +## Notes on the question flow + +- **`ask()` returns a cast value.** An empty line comes back as `''`; the + example treats that as "use the default". To *force* a non-empty answer, + use `ask('…', false)` which re-prompts until something is entered. +- **`question()` with `optional()` + `setDefault()`** returns the default when + the answer is not one of the options. Without `optional()` it re-asks until a + listed option is entered. See + [Questions → constrained input](Questions.md#question--constrained-input). +- **Yes/no** works against the default `[true, false]` options because + `hasOption()` matches the [cast](Input.md#automatic-type-casting) form + (`"yes"`/`"no"`/`"true"`/`"false"` → `bool`). +- **`exit` / `quit`** typed at any prompt terminates the process. If you need + to intercept that (for cleanup, or in tests), override + [`Output::terminate()`](API-Reference.md#output) — see + [Testing Commands](Recipe-Testing-Commands.md). + +## Gating destructive steps + +Pair a required confirmation with an early return: + +```php +$confirm = (new Question()) + ->setQuestion('This will overwrite existing files. Continue? [yes/no]') + ->setOptions(['yes', 'no']) + ->notOptional(); + +if ($output->question($confirm) !== 'yes') { + $output->info('Aborted.'); + return; +} +``` + +## See also + +- [Questions](Questions.md) · [Output](Output.md) +- [Recipe: Testing Commands](Recipe-Testing-Commands.md) — drive this wizard from a test by feeding stdin. diff --git a/docs/Recipe-Report-Table.md b/docs/Recipe-Report-Table.md new file mode 100644 index 0000000..e6d238d --- /dev/null +++ b/docs/Recipe-Report-Table.md @@ -0,0 +1,113 @@ +# Recipe: Styled Report Table + +Render query results (or any row set) as a coloured, aligned table inside a +command, using [`Utils\Table`](Tables.md). + +## A reporting command + +```php +namespace App\Command; + +use InitPHP\Console\{Command, Input, Output}; +use InitPHP\Console\Utils\Table; + +final class UserReportCommand extends Command +{ + public $command = 'report:users'; + + public function definition(): string + { + return 'Print a table of users.'; + } + + public function execute(Input $input, Output $output) + { + $users = [ + ['id' => 1, 'name' => 'Ada Lovelace', 'role' => 'admin', 'active' => true], + ['id' => 2, 'name' => 'Linus Torvalds', 'role' => 'editor', 'active' => true], + ['id' => 3, 'name' => 'Margaret Hamilton','role' => 'admin', 'active' => false], + ]; + + $table = Table::create() + ->setHeaderStyle(Table::COLOR_CYAN, Table::BOLD) + ->setBorderStyle(Table::COLOR_DARK_GRAY) + ->setColumnCellStyle('role', Table::COLOR_YELLOW); + + foreach ($users as $user) { + $table->row($user); + } + + $output->writeln((string) $table); + $output->info(count($users) . ' user(s).'); + } +} +``` + +```bash +php console.php report:users +``` + +``` +╔══════╤═════════════════════╤══════════╤══════════╗ +║ id │ name │ role │ active ║ +╟──────┼─────────────────────┼──────────┼──────────╢ +║ 1 │ Ada Lovelace │ admin │ [TRUE] ║ +║ 2 │ Linus Torvalds │ editor │ [TRUE] ║ +║ 3 │ Margaret Hamilton │ admin │ [FALSE] ║ +╚══════╧═════════════════════╧══════════╧══════════╝ +[INFO] 3 user(s). +``` + +## Friendlier booleans + +The renderer stringifies `true`/`false` as `[TRUE]`/`[FALSE]`. If you want +`yes`/`no` (or `✓`/`✗`), convert before adding the row: + +```php +$table->row([ + 'id' => $user['id'], + 'name' => $user['name'], + 'role' => $user['role'], + 'active' => $user['active'] ? 'yes' : 'no', +]); +``` + +See the full [value rendering table](Tables.md#how-values-are-rendered) for how +every type is displayed. + +## Ragged data is fine + +Rows need not share the same keys — the header is the union, and missing cells +render as `[NULL]`: + +```php +$table = Table::create(); +$table->row(['id' => 1, 'name' => 'Ada', 'email' => 'ada@example.com']); +$table->row(['id' => 2, 'name' => 'Linus']); // no email → [NULL] in that cell +echo $table; +``` + +## Building rows from a PDO query + +```php +$table = Table::create()->setHeaderStyle(Table::COLOR_GREEN, Table::BOLD); + +$stmt = $pdo->query('SELECT id, name, role FROM users ORDER BY id'); +foreach ($stmt as $row) { + $table->row($row); // associative row from PDO::FETCH_ASSOC +} + +echo $table; +``` + +## Multibyte alignment + +With `ext-mbstring` installed, UTF-8 names align correctly because widths are +measured with `mb_strlen()`. Without it, columns containing multibyte +characters may be a little off — see [Tables → multibyte](Tables.md#multibyte-text). + +## See also + +- [Tables](Tables.md) — full renderer reference. +- [Output](Output.md) — the colour constants reused here. +- [Migration Guide](Migration-Guide.md) — if you came from `initphp/cli-table`. diff --git a/docs/Recipe-Testing-Commands.md b/docs/Recipe-Testing-Commands.md new file mode 100644 index 0000000..a8b2830 --- /dev/null +++ b/docs/Recipe-Testing-Commands.md @@ -0,0 +1,186 @@ +# Recipe: Testing Commands + +Because [`Application`](API-Reference.md#application) accepts an injected +[`Output`](Output.md) and `run()` accepts an explicit `$argv`, commands can be +unit-tested without touching `STDOUT`/`STDIN` or the global `$argv`. This is +exactly how the package tests itself. + +## A capturing Output + +Back an `Output` with `php://memory` streams: the first stream captures +everything written, the second feeds answers to prompts. Overriding the +protected [`terminate()`](API-Reference.md#output) hook turns the `exit`/`quit` +prompt path into a catchable exception instead of killing the test runner. + +```php +namespace Tests\Support; + +use InitPHP\Console\Output; + +final class MemoryOutput extends Output +{ + /** @var resource */ + private $buffer; + + public function __construct(string $stdinContent = '') + { + $buffer = fopen('php://memory', 'r+'); + $stdin = fopen('php://memory', 'r+'); + fwrite($stdin, $stdinContent); + rewind($stdin); + + $this->buffer = $buffer; + parent::__construct($buffer, $stdin); + } + + public function captured(): string + { + rewind($this->buffer); + return (string) stream_get_contents($this->buffer); + } + + /** Captured output with SGR colour codes stripped. */ + public function plain(): string + { + return (string) preg_replace('/\e\x5B[0-9;]*m/', '', $this->captured()); + } + + protected function terminate(int $code = 0): void + { + throw new TerminateException('terminated', $code); + } +} + +final class TerminateException extends \RuntimeException {} +``` + +## Testing a closure command + +```php +use PHPUnit\Framework\TestCase; +use InitPHP\Console\{Application, Input, Output}; +use Tests\Support\MemoryOutput; + +final class GreetTest extends TestCase +{ + public function testGreetUsesTheNameArgument(): void + { + $out = new MemoryOutput(); + $app = new Application('Test', '1.0.0', $out); + + $app->register('greet', function (Input $input, Output $output) { + $output->writeln('Hello {n}', ['n' => $input->getArgument('name', 'World')]); + }); + + self::assertTrue($app->run(['console.php', 'greet', '--name=Ada'])); + self::assertStringContainsString('Hello Ada', $out->plain()); + } +} +``` + +The key moves: + +- Inject `MemoryOutput` as the third constructor argument. +- Pass an explicit token list to `run()` — the first element stands in for the + script name. +- Assert against `plain()` (colour codes stripped) so assertions stay readable. + +## Testing a class-based command and its validation + +```php +public function testRequiredArgumentAbortsBeforeExecute(): void +{ + $out = new MemoryOutput(); + $app = new Application('Test', '1.0.0', $out); + $app->register(\App\Command\CommitCommand::class); + + // Missing the required --message: + self::assertFalse($app->run(['console.php', 'commit'])); + self::assertStringContainsString('--message', $out->plain()); +} + +public function testCommitRuns(): void +{ + $out = new MemoryOutput(); + $app = new Application('Test', '1.0.0', $out); + $app->register(\App\Command\CommitCommand::class); + + self::assertTrue($app->run(['console.php', 'commit', '--message=Initial'])); + self::assertStringContainsString('Initial', $out->plain()); +} +``` + +## Testing prompts + +Seed the answers in the constructor; each `fgets()` consumes one line: + +```php +public function testInstallerAcceptsDefaults(): void +{ + // Two prompts: blank project name (→ default), then "sqlite". + $out = new MemoryOutput("\nsqlite\n"); + $app = new Application('Test', '1.0.0', $out); + $app->register(\App\Command\InstallCommand::class); + + self::assertTrue($app->run(['console.php', 'app:install'])); + self::assertStringContainsString('ready', $out->plain()); +} +``` + +Test the `exit`/`quit` path via the overridden `terminate()`: + +```php +public function testQuitTerminates(): void +{ + $out = new MemoryOutput("quit\n"); + + $this->expectException(\Tests\Support\TerminateException::class); + $out->ask('Anything?'); +} +``` + +## Testing Output directly + +You do not need an `Application` to test formatting: + +```php +public function testProgressBarGuardsZeroTotal(): void +{ + $this->expectException(\InvalidArgumentException::class); + (new MemoryOutput())->progressBar(1, 0); +} + +public function testListRendersPairs(): void +{ + $out = new MemoryOutput(); + $out->list(['Host' => 'localhost', 'Port' => 8080]); + + self::assertStringContainsString(': localhost', $out->plain()); +} +``` + +## Testing the table renderer + +`Utils\Table` returns a string, so assert on its content directly — no streams +needed: + +```php +use InitPHP\Console\Utils\Table; + +public function testTableRendersHeadersAndPlaceholders(): void +{ + $content = Table::create() + ->row(['id' => 1, 'name' => 'Ada']) + ->row(['id' => 2]) // missing name → [NULL] + ->getContent(); + + self::assertStringContainsString('name', $content); + self::assertStringContainsString('[NULL]', $content); +} +``` + +## See also + +- [Output → injecting streams](Output.md#injecting-streams) +- [Questions → testing prompts](Questions.md#testing-prompts) +- [API Reference → Output::terminate](API-Reference.md#output) diff --git a/docs/Recipes.md b/docs/Recipes.md new file mode 100644 index 0000000..21e24f3 --- /dev/null +++ b/docs/Recipes.md @@ -0,0 +1,57 @@ +# Recipes + +Practical, copy-pasteable patterns built on top of the public API. Each recipe +is self-contained and links back into the reference material for the +components it uses. + +| Recipe | Solves | +| --- | --- | +| [Git-like CLI](Recipe-Git-Like-CLI.md) | A multi-command binary with grouped, class-based commands and typed arguments. | +| [Interactive Installer](Recipe-Interactive-Installer.md) | A guided flow using questions, defaults and a progress bar. | +| [Styled Report Table](Recipe-Report-Table.md) | Rendering query results as a coloured, aligned table. | +| [Testing Commands](Recipe-Testing-Commands.md) | Unit-testing commands with injected in-memory streams. | + +If you have built something on top of the package that other users might +benefit from, please +[open an issue](https://github.com/InitPHP/Console/issues/new) with a sketch — +recipe contributions are welcomed. + +## General shape of a console app + +Most applications follow the same skeleton: + +```php +#!/usr/bin/env php +run() ? 0 : 1); // map dispatch result to a process exit code +``` + +- Group related commands with a `name:subname` convention so they cluster in + `php tool list` — see [Commands → Grouping](Commands.md#grouping-in-the-listing). +- Declare typed [`InputArgument`](Input-Arguments.md)s on class commands so the + framework validates input for you before `execute()` runs. +- Throw from a command to abort with a message — the dispatcher catches it and + prints `[ERROR] …`. See [Exceptions](Exceptions.md). + +## When NOT to use this package + +`initphp/console` is intentionally small. Reach for a heavier framework when +you need: + +- **Sub-command trees beyond one level**, auto-completion, or a sophisticated + argument grammar (variadics, negatable flags, `--` passthrough). The parser + here is deliberately flat — see [Input](Input.md). +- **A full DI/service layer wired into commands.** Compose your own container + and instantiate command dependencies yourself; this package only routes the + invocation. +- **Structured logging / output verbosity levels** out of the box. Build them + on top of [`Output`](Output.md) (e.g. wrap it and gate `info()` on a `-v` + option). diff --git a/docs/Tables.md b/docs/Tables.md new file mode 100644 index 0000000..8913886 --- /dev/null +++ b/docs/Tables.md @@ -0,0 +1,145 @@ +# Tables + +[`InitPHP\Console\Utils\Table`](API-Reference.md#utilstable) renders styleable +ASCII/ANSI tables. Rows are associative arrays; the union of their keys forms +the header, columns are auto-sized, and styles are emitted as SGR escape +sequences. + +> This is the renderer formerly published as `initphp/cli-table`. The old +> class name `\InitPHP\CLITable\Table` still resolves to it via a +> `class_alias` — see [Migration Guide](Migration-Guide.md). + +## Basic usage + +```php +use InitPHP\Console\Utils\Table; + +$table = Table::create(); + +$table->row(['id' => 1, 'name' => 'Matthew S.', 'email' => 'matthew@example.com']) + ->row(['id' => 2, 'name' => 'Millie J.', 'email' => 'millie@example.com']); + +echo $table; // uses __toString() +// or +echo $table->getContent(); +``` + +``` +╔══════╤══════════════╤══════════════════════════╗ +║ id │ name │ email ║ +╟──────┼──────────────┼──────────────────────────╢ +║ 1 │ Matthew S. │ matthew@example.com ║ +║ 2 │ Millie J. │ millie@example.com ║ +╚══════╧══════════════╧══════════════════════════╝ +``` + +`Table::create()` is a convenience factory equivalent to `new Table()`. Both +return a fresh instance, and every mutator returns `$this`, so construction +chains naturally. + +## Styling + +All four style setters are variadic and take one or more SGR codes — the same +constants as [`Output`](Output.md#styling-with-sgr-codes), also exposed directly +on `Table`: + +```php +$table = Table::create() + ->setHeaderStyle(Table::COLOR_RED, Table::BOLD) // header row + ->setCellStyle(Table::COLOR_GREEN) // every body cell + ->setBorderStyle(Table::COLOR_BLUE) // the frame + ->setColumnCellStyle('status', Table::COLOR_YELLOW); // one column's body cells +``` + +| Setter | Applies to | Default | +| --- | --- | --- | +| `setHeaderStyle(int ...$sgr)` | the header row | `[BOLD]` | +| `setCellStyle(int ...$sgr)` | all body cells | none | +| `setBorderStyle(int ...$sgr)` | box-drawing characters | none | +| `setColumnCellStyle(string $col, int ...$sgr)` | body cells of one column | none | + +Per-column styling overrides the global cell style for that column only, and +applies to body cells, not the header. + +## How values are rendered + +Cell values are coerced to a printable string. Strings pass through verbatim +(trimmed); everything else is mapped as follows: + +| Value | Rendered as | +| --- | --- | +| `null` | `[NULL]` | +| `true` / `false` | `[TRUE]` / `[FALSE]` | +| array | `[ARRAY]` | +| array that is callable (`[$obj, 'method']`) | `[CALLABLE]` | +| other callable | `[CALLABLE]` | +| resource | `[RESOURCE]` | +| object | its class name (e.g. `App\User`) | +| int / float | string cast | + +## Ragged rows + +Rows may have different key sets. The header is the union of all keys, and any +cell missing from a row is rendered as `[NULL]`: + +```php +Table::create() + ->row(['id' => 1, 'name' => 'Ada', 'active' => true]) + ->row(['id' => 2, 'name' => null, 'role' => 'admin']) + ->getContent(); +// Columns: id | name | active | role +// Row 1 has no "role" → [NULL]; Row 2 has no "active" → [NULL]; name=null → [NULL] +``` + +## Multibyte text + +Column widths are measured with `mb_strlen()` when the `mbstring` extension is +available, so UTF-8 values such as `İstanbul` or `Mühammet` align correctly. +Without `mbstring` the renderer falls back to `strlen()` (byte length), which +may misalign multibyte cells. + +## A styled example + +```php +use InitPHP\Console\Utils\Table; + +echo Table::create() + ->setHeaderStyle(Table::COLOR_CYAN, Table::BOLD) + ->setBorderStyle(Table::COLOR_DARK_GRAY) + ->setColumnCellStyle('admin', Table::COLOR_YELLOW) + ->row(['id' => 1, 'name' => 'Ada Lovelace', 'admin' => true]) + ->row(['id' => 2, 'name' => 'Linus Torvalds', 'admin' => false]) + ->row(['id' => 3, 'name' => 'Margaret Hamilton', 'admin' => true]); +``` + +## Combining with the application + +The table is just a string, so print it from a command like any other output: + +```php +use InitPHP\Console\{Command, Input, Output}; +use InitPHP\Console\Utils\Table; + +final class UsersCommand extends Command +{ + public $command = 'user:list'; + + public function execute(Input $input, Output $output) + { + $table = Table::create()->setHeaderStyle(Table::COLOR_GREEN, Table::BOLD); + foreach (User::all() as $user) { + $table->row(['id' => $user->id, 'name' => $user->name, 'admin' => $user->isAdmin]); + } + $output->writeln((string) $table); + } +} +``` + +See the [Styled Report Table recipe](Recipe-Report-Table.md) for a fuller +example. + +## Where to go next + +- [Recipe: Styled Report Table](Recipe-Report-Table.md) — a complete reporting command. +- [Migration Guide](Migration-Guide.md) — moving from `initphp/cli-table`. +- [API Reference](API-Reference.md#utilstable) — every method and constant. diff --git a/docs/_Footer.md b/docs/_Footer.md new file mode 100644 index 0000000..f97cd1d --- /dev/null +++ b/docs/_Footer.md @@ -0,0 +1,8 @@ +**`initphp/console`** · MIT License · part of the [InitPHP](https://github.com/InitPHP) family + +[Source](https://github.com/InitPHP/Console) · +[Issues](https://github.com/InitPHP/Console/issues) · +[Discussions](https://github.com/orgs/InitPHP/discussions) · +[Packagist](https://packagist.org/packages/initphp/console) · +[Contributing](https://github.com/InitPHP/.github/blob/main/CONTRIBUTING.md) · +[Security Policy](https://github.com/InitPHP/.github/blob/main/SECURITY.md) diff --git a/docs/_Sidebar.md b/docs/_Sidebar.md new file mode 100644 index 0000000..85d697c --- /dev/null +++ b/docs/_Sidebar.md @@ -0,0 +1,30 @@ +### [Home](Home.md) + +**Getting Started** +- [Installation](Installation.md) +- [Quick Start](Quick-Start.md) + +**Building Commands** +- [Commands](Commands.md) +- [Input](Input.md) +- [Input Arguments](Input-Arguments.md) + +**Output & Interaction** +- [Output](Output.md) +- [Questions](Questions.md) +- [Tables](Tables.md) + +**Reference** +- [API Reference](API-Reference.md) +- [Exceptions](Exceptions.md) + +**Practical Guides** +- [Recipes](Recipes.md) +- [— Git-like CLI](Recipe-Git-Like-CLI.md) +- [— Interactive Installer](Recipe-Interactive-Installer.md) +- [— Styled Report Table](Recipe-Report-Table.md) +- [— Testing Commands](Recipe-Testing-Commands.md) + +**Migration & Help** +- [Migration Guide](Migration-Guide.md) +- [FAQ](FAQ.md)