Download the PHP package silassare/kli without Composer
On this page you can find all versions of the php package silassare/kli. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download silassare/kli
More information about silassare/kli
Files in silassare/kli
Package kli
Short Description Kli helps you add an interactive command-line interface to your php project.
License MIT
Homepage https://github.com/silassare/kli#readme
Informations about the package kli
Kli
PHP >=8.5 fluent-builder CLI framework. Add a typed, interactive command-line interface to any PHP application in minutes.
Table of Contents
- Requirements
- Installation
- Quick Start
- Architecture
- Commands and Actions
- Options and Types
- String
- Number
- Bool
- Path
- Handlers
- Parsed Arguments — KliArgs
- Positional (Offset) Arguments
- Interactive Prompts
- Interactive REPL Mode
- ANSI Styling — KliStyle
- Table Rendering — KliTable
- Output Helpers
- Exception Handling
- Naming Rules
- Extending Kli
- Testing
- Developer Workflows
Requirements
- PHP >= 8.3
Installation
Quick Start
Architecture
The hierarchy from outermost to innermost is:
Each layer uses a fluent builder API. Every mutator returns static so the
chain works correctly in subclasses.
Commands and Actions
Built-in flags handled automatically by Kli::execute():
| Token | Effect |
|---|---|
--help / -? |
Show help (top-level, command, action) |
--version / -v |
Show version string |
-- |
Stop option parsing; rest is anonymous |
Options and Types
KliAction::option() adds an option and returns the KliOption object.
Call a type setter on it; the setter returns the type object (not the
option), so type-specific constraints are chained on the type:
String type
| Method | Description |
|---|---|
->min(int $n, ?string $msg = null) |
Minimum character count (multibyte) |
->max(int $n, ?string $msg = null) |
Maximum character count (multibyte) |
->pattern(string $regex, ?string $msg = null) |
Regex the value must match |
->validator(callable $fn, ?string $msg = null) |
Custom callable; return false to fail |
->def(string $value) |
Default value |
Number type
| Method | Description |
|---|---|
->min(float $n, ?string $msg) |
Minimum value (inclusive) |
->max(float $n, ?string $msg) |
Maximum value (inclusive) |
->integer(?string $msg = null) |
Require a whole number (no decimal) |
->def(int | float $value) |
Default value |
Returns int when no decimal part, float otherwise.
Bool type
Non-strict mode accepts: true, false, 1, 0, '1', '0', 'true',
'false', 'yes', 'no', 'y', 'n'.
Strict mode accepts only: true, false, 'y', 'n', 'yes', 'no'.
Always resolves to a native PHP bool.
A bool option passed without a value (e.g. --verbose) is treated as true.
Path type
| Method | Description |
|---|---|
->file(?string $msg = null) |
Accept only existing files |
->dir(?string $msg = null) |
Accept only existing directories |
->writable(?string $msg = null) |
Accept only writable paths |
->multiple() |
Return string[] instead of string |
->min(int $n, ?string $msg = null) |
Minimum number of resolved paths |
->max(int $n, ?string $msg = null) |
Maximum number of resolved paths |
->pattern(string $regex, ?string $msg = null) |
Filter resolved paths by regex |
->def(string $value) |
Default value |
Paths are resolved via realpath() — they must exist on the filesystem.
Handlers
Every action must have a handler before execution:
If neither handler is set, Kli::execute() throws KliRuntimeException at
dispatch time.
Parsed Arguments — KliArgs
The KliArgs object is delivered to every handler. Retrieve values by option
name, alias, or single-char flag:
Positional (Offset) Arguments
Map positional (anonymous) tokens directly to an option with offsets():
Offset ranges cannot overlap across options; a duplicate triggers
KliRuntimeException at configuration time.
Interactive Prompts
Mark an option as required and enable prompting so the user is asked when the value is not supplied on the command line:
If the user enters an invalid value the prompt is shown again with the validation error until a valid value is provided. An empty answer selects the option default, which is used as is. At the end of input (Ctrl-D or a closed pipe) with no default, the prompt stops and the action fails as described below.
The user is only prompted when STDIN is a terminal or the tool runs in
interactive mode (see Kli::canPrompt()). Otherwise (pipes, cron, CI) the
option falls back to its default, or the action fails with
"<action>" require option: --<name>.
Interactive REPL Mode
Pass allow_interactive_mode: true to Kli::new(). When the tool is invoked with
no arguments it enters an interactive loop where the user can type commands:
The loop also stops at the end of input (Ctrl-D or a closed pipe).
Override readLine(), canPrompt() and isEndOfInput() in a subclass to customise input (useful in tests — see
ScriptedKli in tests/ScriptedKli.php). Override welcome() to print a
custom banner.
ANSI Styling — KliStyle
Chain color and style methods, then call apply() to wrap a string:
Foreground colors (method names):
black(), darkGray(), blue(), lightBlue(), green(), lightGreen(),
cyan(), lightCyan(), red(), lightRed(), magenta(), lightMagenta(),
yellow(), lightGray(), white(), normal()
Background colors: backgroundBlack(), backgroundRed(),
backgroundGreen(), backgroundYellow(), backgroundBlue(),
backgroundMagenta(), backgroundCyan(), backgroundLightGray()
Styles: bold(), dim(), underline(), blink(), invert(), hidden()
ANSI codes are emitted only when STDOUT is a TTY. Override with static flags:
Table Rendering — KliTable
Built-in formatters (KliTableFormatter static factories):
| Factory | Renders as |
|---|---|
::bool(?KliStyle $style = null) |
true -> "Yes", false -> "No" |
::number(int $decimals, string $dp, string $ts, ?KliStyle $style) |
number_format() output |
::date(string $format = 'Y-m-d H:i:s', ?KliStyle $style) |
Unix timestamp formatted by date() |
Custom formatter: implement KliTableCellFormatterInterface:
Styling borders:
Default border character set: ╔═╤╗║│╟─┼╢╚═╧╝.
Output Helpers
All helpers return static for chaining. $wrap = true runs the message
through wordwrap() at 80 characters.
Exit codes on output methods
error(), warn(), and success() accept an optional ?int $exit parameter
that terminates the process after printing:
| Method | Default $exit |
Behaviour when $exit is non-null |
|---|---|---|
error() |
1 |
Terminates with the given code by default; pass null to skip. |
warn() |
null |
Does not terminate by default; pass a code to stop after printing. |
success() |
null |
Does not terminate by default; pass 0 to stop cleanly. |
In interactive REPL mode a non-null $exit throws KliAbortException
instead of calling exit(), so the REPL loop continues rather than dying.
To terminate unconditionally regardless of mode, call terminate() directly:
Version string — override getVersion() in your subclass to return the
real semantic version:
Exception Handling
KliInputException is thrown by all KliType::validate() implementations and
by KliParser. It is caught inside execute() and shown via error().
KliRuntimeException is thrown at configuration time (bad names, duplicate
flags, conflicting offsets, missing handler). It always propagates.
KliAbortException is an internal signal thrown by error(), warn(), and
success() when $exit is non-null and the CLI is in interactive mode.
execute() catches it so the REPL loop continues. Application code should
never need to catch it directly.
Naming Rules
| Element | Pattern | Notes |
|---|---|---|
| Command name | [a-zA-Z0-9][a-zA-Z0-9-_]+ |
2+ chars, no colons |
| Action name | [a-zA-Z0-9]([a-zA-Z0-9-_:]+) |
colons allowed, e.g. create:user |
| Option name | [a-zA-Z0-9][a-zA-Z0-9-_]* |
1+ chars |
| Option alias | [a-zA-Z0-9][a-zA-Z0-9-_]+ |
2+ chars |
| Option flag | [a-zA-Z0-9] |
exactly 1 char |
Auto-promotion rules applied inside KliOption::__construct():
- A 1-char option name is automatically promoted to a flag (e.g.
option('v')sets flagv). - A multi-char option name is automatically added as an alias.
Extending Kli
Subclass Kli to override behaviour:
Testing
Tests live in tests/ and use snapshot files in tests/snapshots/.
Snapshot pattern (TestUtils::ensureSnapshotFile()): on first run the
snapshot is written; subsequent runs assert against it with
assertStringEqualsFile(). Delete a snapshot file to regenerate it.
Two snapshot variants are produced for output that includes ANSI codes:
| Suffix | How produced |
|---|---|
| (none) | KliStyle::disableAnsi(true) |
.tty.txt |
KliStyle::forceAnsi(true) |
ScriptedKli (tests/ScriptedKli.php) — test helper for interactive
prompts and REPL mode. Subclasses Kli, overrides readLine() with a
pre-scripted queue of responses (end of input once exhausted), and records every prompt shown. Pass
can_prompt: false to act as if STDIN is not a terminal:
Developer Workflows
- PHPUnit config:
phpunit.xml.dist—failOnWarningandfailOnRiskyaretrue - Psalm config:
psalm.xml— error level 4, analyzessrc/only - CS rules:
oliup/oliup-cs-php(seephpcs.xml.dist)
All versions of kli with dependencies
ext-readline Version *