parasoled / getopt
A POSIX command-line parser with typed values, validation and generated help.
Requires
- php: >=8.3
Requires (Dev)
- deptrac/deptrac: ^4.7
- friendsofphp/php-cs-fixer: ^3.95
- phpunit/phpunit: ^12.5
- psalm/plugin-phpunit: ^0.19
- vimeo/psalm: ^6.20
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is not auto-updated.
Last update: 2026-11-21 23:16:36 UTC
README
parasoled/getopt is a POSIX-style command-line parser for PHP. You
declare the options and commands of a program with typed constructors. The
library splits the arguments into options and operands, converts each value
to a typed PHP value, resolves it against environment variables and
defaults, and validates it against your rules. It also generates the help
page and renders user errors with "did you mean" suggestions.
$ greet --loud
error: unknown option --loud
Try 'greet -h' for more information.
A POSIX tool has no long options, so --loud is unknown. Under
ParseMode::Permissive the same typo, --lod, gets a "did you mean
--loud?" suggestion.
Out of scope: command dispatch, configuration files and interactive prompts.
Requirements
PHP 8.3 or later. The library needs no PHP extension, and require in its
composer.json holds php and nothing else.
Installation
composer require parasoled/getopt
A program loads the library through Composer's autoloader, with
require __DIR__ . '/vendor/autoload.php'; at its top. The examples in
this README and in docs/api.md leave that line out.
Example
A tool built with Cli::build(name: 'greet', ...) reads its command line
by the POSIX Utility Syntax Guidelines (see The POSIX
guidelines): an option is a dash and one letter,
and options end at the first operand. Long options, abbreviations and
options after operands are extensions you opt into by passing
mode: ParseMode::Permissive (see Parse modes).
<?php
use Getopt\Cli;
use Getopt\Definition\Option;
enum GreetOption: string
{
case Name = 'n';
case Loud = 'l';
public function description(): string
{
return match ($this) {
self::Name => 'The name to greet',
self::Loud => 'Print in capital letters',
};
}
}
$cli = Cli::build(
name: 'greet',
description: 'Print a greeting.',
help: 'h',
options: [
Option::string(short: GreetOption::Name->value, description: GreetOption::Name->description(), default: 'world', env: 'GREET_NAME'),
Option::flag(short: GreetOption::Loud->value, description: GreetOption::Loud->description()),
],
);
$result = $cli->runOrExit();
$name = $result->string(GreetOption::Name->value);
$loud = $result->bool(GreetOption::Loud->value);
$greeting = "Hello, {$name}!";
echo $loud ? strtoupper($greeting) : $greeting, PHP_EOL;
The option names live in an enum, so the program declares each name once
and reads it back by the same case. Each case carries its description too,
so a name and the words the help page shows for it sit side by side.
Your editor and static analysis catch
a mistyped case. A mistyped string is found only when its line runs, as a
LogicException.
$ greet
Hello, world!
$ greet -n Ada -l
HELLO, ADA!
$ GREET_NAME=Bo greet
Hello, Bo!
$ greet -h
Usage:
greet [-lh] [-n <value>] [operand...]
Description:
Print a greeting.
Options:
-n <value> The name to greet (env: GREET_NAME) (default: world)
-l Print in capital letters
-h Show this help text and exit
greet declares nothing about its operands, so it accepts any number of
them, and its usage line says so with [operand...]. A program that takes
none declares operands: Operands::none(). Its usage line then shows no
operand, and greet x is refused.
Lifecycle
A program uses the library in four steps.
- Define. Each option comes from a typed constructor, such as
Option::int(short: 'p', description: 'The port', min: 1), and each command fromCommand::define(). A definition is afinal readonlyvalue, and making one checks nothing beyond PHP's types. - Build.
Cli::build(name: 'name', ...)takes the whole definition as named arguments, validates it, and returns an immutableCli. It throws aDefinitionErrorfor an invalid definition, such as a duplicate name, a long name under the POSIX mode, or adefault:of the wrong type. Treat aDefinitionErroras a programming error.Cli::fromClass()does the same from a readonly class whose constructor parameters carry option attributes. - Parse.
runOrExit()orrun()parses the arguments, which are the program's own when you pass none. The two differ in who handles help, the version and errors (see run() and runOrExit()). - Read. The
ParseResulthas a typed accessor for each kind of value:bool(),int(),float(),string()andlist(), such as$result->int('p'). The name may be written in any spelling the user could type, so'v','-v','verbose'and'--verbose'name the same option. An unset flag isfalse, an unset count0and an unset list[]. Any other option nothing set isnull. A name no option has, or an accessor that does not suit the option's kind, throws aLogicException, because both are mistakes in the program.$result->option('p')returns the value with the source it came from.
Under the POSIX mode no letter is reserved for you. POSIX defines no help
or version option, so a POSIX tool has one only when you name its letter:
help: 'h' and version: new Version(text: '1.0.0', short: 'V'). A tool
that names neither has neither, and an error ends without a hint. Under
ParseMode::Permissive the library adds -h/--help and --version
whether or not you name anything, and a letter you name becomes the short
name beside the long one. help: new Help() gives --help alone, so -h
is free for an option of your own. Either way they are global options, and
defining your own option with the same name is a duplicate-name error
(ADR-025).
Value kinds
The constructor names the kind. The kind decides the PHP type you read back, and whether the option takes an option-argument: a flag and a count take none, and every other kind takes one (ADR-039).
| Constructor | Command line | PHP type | Accessor |
|---|---|---|---|
Option::flag() | --loud | bool | bool() |
Option::count() | -vvv | int (3) | int() |
Option::int() | --port 80 | ?int | int() |
Option::float() | --ratio 1.5 | ?float | float() |
Option::string() | --name Ada | ?string | string() |
Option::path() | --file a.txt | ?string | string() |
Option::choice() | --mode fast | ?string | string() |
Option::list() | --tag a,b --tag c | list<string> | list() |
The command-line column shows the long spelling, which needs long options. Under the POSIX mode the same option is written with its short name.
The rules on a value are named arguments of its constructor: min: and
max: for numbers, minLength:, maxLength: and matches: for text,
choices: for a choice or for the items of a list, and check: for a rule
you write. The parser checks them after conversion and reports the first
failure as InvalidValue, or as ValueOutOfRange for a number outside its
range. They apply to the final value wherever it came from, so a default or
an environment value that breaks one fails the parse. On Option::list(),
the rules on text hold for every item, and the failure names the item.
Value resolution
The library picks one value per option, in this order of precedence:
| Precedence | Source | ResolvedValue::$source |
|---|---|---|
| 1 | Command line | ValueSource::CommandLine |
| 2 | The variable named by env: | ValueSource::Environment |
| 3 | default: | ValueSource::Default |
An option nothing set has a null value and the source
ValueSource::Default. Check the value before the source.
An environment value that fails conversion, such as abc for an
Option::int(), fails the parse with InvalidValue, as abc on the
command line does. So does a value that breaks a rule, with InvalidValue,
or with ValueOutOfRange for a number outside its range. The error names
the variable. A variable is not judged when the command line gives the
option, and help and the version still answer.
Argument syntax
| Input | Read as |
|---|---|
-l | Short option |
-abc | Clustered short flags: -a -b -c |
-n Ada, -nAda | Short option with a value |
--name Ada | Long option with a separate value. Long options only |
--name=Ada | Long option with an attached value. Long options only |
--na Ada | Abbreviated long option, if the prefix is unique. Abbreviations only |
-- | End of options. The rest are operands, also in remainder() |
An abbreviation that matches more than one option fails with
AmbiguousOption. Under the POSIX mode a --name is an unknown option,
whatever the definition holds. An option-argument is never read as an
option: -o --foo gives -o the value --foo.
Parse modes
A mode is three independent choices, and POSIX is the default for each.
| Choice | POSIX | Extension |
|---|---|---|
| Syntax | Short options only: -v | longOptions: -v and --verbose |
| Order | Options end at the first operand | optionsAfterOperands: tool a.txt -v reads -v as an option |
| Matching | Exact names | abbreviations: --verb for --verbose |
Two presets name the ends:
| Preset | Long options | Options after operands | Abbreviations |
|---|---|---|---|
ParseMode::Posix (the default) | No | No | No |
ParseMode::Permissive | Yes | Yes | Yes |
The mode is the mode: argument of Cli::build(), and it is chosen with
the rest of the definition, because it decides what the other arguments may
declare. For a mode between the two, name the extensions you turn on with a
CustomMode. Long options read options-first with exact names is:
<?php
use Getopt\Cli;
use Getopt\Definition\Option;
use Getopt\Mode\CustomMode;
$cli = Cli::build(
name: 'tool',
mode: new CustomMode(longOptions: true),
options: [Option::flag(short: 'v', long: 'verbose', description: 'Print more')],
);
$result = $cli->runOrExit();
echo $result->bool('verbose') ? 'verbose' : 'quiet', PHP_EOL;
$ tool --verbose
verbose
$ tool a.txt --verbose
quiet
The second line reads --verbose as an operand, because the options ended
at a.txt.
Without long options, Cli::build() throws a DefinitionError for any
option with a long name, on any command, and the message names the two ways
out: remove the long name, or pass mode: ParseMode::Permissive. A
CustomMode with abbreviations: true and no long options is also
refused, because there are no long names to abbreviate.
Without long options, Cli::build() also refuses a tool name that POSIX
would not give a utility: the name must be two to nine characters, each a
lowercase letter or a digit. Rename the tool, or pass
mode: ParseMode::Permissive, which leaves the name to you. Pass the name
as a literal, not the base name of the script, so that renaming the file
cannot stop the tool from starting. Command names are not held to this.
POSIXLY_CORRECT is not read. It is a GNU convention that POSIX does not
define, and a tool parses in the mode its developer chose on every machine.
The POSIX guidelines
In the default mode, ParseMode::Posix, the library follows XBD 12.2
except as listed. XBD 12.2 is the Utility Syntax Guidelines of
POSIX.1-2024, which say how a utility names its options and reads its
arguments.
Nothing is listed. The tests have found no departure from XBD 12.2 in the default mode.
The statement covers the default mode and no other. ParseMode::Permissive
is a documented departure and stands outside it, as does a CustomMode
that turns on one of the extensions in Parse modes.
This reports what the project's tests have found. It is not a certification.
Commands
Command::define() declares a command, which can hold further commands.
After a parse, $result->command() returns the path of the commands named
below the program, such as 'db migrate', or null when none was named.
Options with global: true are accepted before or after the command name.
A top-level option without it cannot be used with a command at all:
tool -l serve fails with UnknownOption. An unknown command name fails
with UnknownCommand, and explain() suggests the closest match.
A command has no handler. Dispatch on $result->command() in your own code
(ADR-042):
<?php
use Getopt\Cli;
use Getopt\Definition\Command;
use Getopt\Definition\Operands;
use Getopt\Definition\Option;
use Getopt\Mode\ParseMode;
$cli = Cli::build(
name: 'dbtool',
mode: ParseMode::Permissive,
description: 'Manage the application database.',
options: [Option::count(short: 'v', long: 'verbose', description: 'Print more', global: true)],
commands: [
Command::define(name: 'migrate', description: 'Apply pending migrations',
options: [Option::flag(long: 'dry-run', description: 'Run nothing')],
operands: Operands::none(),
),
Command::define(name: 'seed', description: 'Load fixture data', operands: Operands::oneOrMore(name: 'fixture')),
],
);
$result = $cli->runOrExit();
match ($result->command()) {
'migrate' => print($result->bool('dry-run') ? "Would migrate\n" : "Migrating\n"),
'seed' => printf("Seeding %s\n", implode(', ', $result->operands())),
default => print $cli->help($result),
};
$ dbtool seed users orders
Seeding users, orders
$ dbtool migrat
error: unknown command migrat
did you mean migrate?
Try 'dbtool --help' for more information.
In a program with commands, the first top-level operand is read as a
command name, so a mistyped command fails with UnknownCommand instead of
reaching your program as an operand (ADR-014). The command name may be left
out: unless the program requires an option or an operand of its own, tool
alone parses, with command() returning null, and a program that needs a
command checks for that itself. The program's own operands are reachable
only after --, as in tool -- a.txt, because a word after -- is not
read as a command name. The usage of a program that declares nothing of its
operands says both, on two lines (ADR-035):
Usage:
tool [-h] [<command>]
tool [-h] -- [operand...]
The first line ends at the command word. What may follow one, as in
tool serve 80, is on the help page of that command. A program that takes
no operands of its own declares Operands::none(), and the second line
then has no operands. It goes altogether where every top-level option is
global. Where one is not, as -l below, the first line leaves it out and
the second keeps it, because it is refused beside a command name:
Usage:
tool [-h] [<command>]
tool [-lh]
Exactly, the second line is printed where the program takes operands of its
own, or where its options are written differently from the first line's. So
under Operands::none() there is one line where both would read
[options], as with long names, and where the only option that is not
global is shut out by a required member of its exclusion group.
run() and runOrExit()
runOrExit(?array $arguments = null): ParseResult | run(?array $arguments = null): ParseResult | |
|---|---|---|
| Help option | Writes help to standard output, exits 0 | Returns a result whose outcome() is Outcome::HelpRequested |
| Version option | Writes the version to standard output, exits 0 | Returns a result whose outcome() is Outcome::VersionRequested |
| Parse error | Writes the explain() text and a usage hint to standard error, exits 1 | Throws the CLIParseError |
| Exit statuses | 0, 0 and 1, or the ones exitStatuses: names | Ends nothing |
| Writes output | Yes | Never |
Most programs should use runOrExit(). It returns only a result the
program should act on. Use run() when the program must act before
exiting, such as flushing a log:
<?php
use Getopt\Cli;
use Getopt\Definition\Option;
use Getopt\Definition\Version;
use Getopt\Error\CLIParseError;
use Getopt\Result\Outcome;
$cli = Cli::build(
name: 'tool',
help: 'h',
version: new Version(text: '1.2.0', short: 'V'),
options: [Option::flag(short: 'q', description: 'Print nothing')],
);
try {
$result = $cli->run();
} catch (CLIParseError $error) {
fwrite(STDERR, $cli->explain($error));
exit(1);
}
match ($result->outcome()) {
Outcome::HelpRequested => print $cli->help($result),
Outcome::VersionRequested => print $cli->version(),
Outcome::Parsed => print "Running\n",
};
$ tool -V
tool 1.2.0
$ tool -x
error: unknown option -x
run() writes nothing. $cli->help($result) returns the generated page,
$cli->version() the version line, and $cli->explain($error) the error
message without the hint, and your program decides where each goes.
Exit statuses
runOrExit() ends help and the version with 0, and an error with 1.
exitStatuses: replaces any of the three. A row you do not name keeps the
library's status. A tool whose scripts read 2 as a mistake in the command
line, as GNU grep and ls do, names the error row:
<?php
use Getopt\Cli;
use Getopt\Definition\ExitStatuses;
$cli = Cli::build(name: 'tool', help: 'h', exitStatuses: new ExitStatuses(error: 2));
$cli->runOrExit();
$ tool -x
error: unknown option -x
Try 'tool -h' for more information.
That run ends with 2, and tool -h still ends with 0. The rows are the
named arguments help:, version: and error: of ExitStatuses.
Cli::build() refuses a status outside 0 to 255, and an error that ends
with 0, because a script reads 0 as success. run() ends nothing, so a
program that uses it chooses its own status. ADR-038 records the decision.
Errors
Every error run() throws is a CLIParseError, an abstract exception with
nine final subclasses, each with readonly public properties. The name keeps
clear of PHP's own ParseError (ADR-041).
| Class | Cause |
|---|---|
UnknownOption | The option is not defined |
MissingValue | An option that takes a value had none |
InvalidValue | Conversion or a rule failed |
MissingRequired | A required: true option was not given |
MutualExclusion | Two options from one exclusion group were given |
UnknownCommand | The command is not defined |
AmbiguousOption | An abbreviation matched more than one option |
InvalidOperands | The operands fall outside operands: |
ValueOutOfRange | A number is outside its range or its type's |
Catch the base class, or the one you care about:
<?php
use Getopt\Cli;
use Getopt\Definition\Option;
use Getopt\Error\InvalidValue;
$cli = Cli::build(name: 'tool', options: [Option::int(short: 'p', description: 'The port')]);
try {
$cli->run(['-p', 'eighty']);
} catch (InvalidValue $invalid) {
echo "bad value '{$invalid->value}' for {$invalid->option}: {$invalid->reason}", PHP_EOL;
echo $invalid->getMessage(), PHP_EOL;
echo $cli->explain($invalid);
}
$ tool
bad value 'eighty' for -p: expected a whole number
invalid value for option -p: eighty
error: invalid value 'eighty' for option -p
expected a whole number
getMessage() returns a short message for logs, such as
unknown option: --lod, with no suggestions or colour.
$cli->explain($error) returns the user-facing text, with suggestions, and
with colour when the terminal supports it (ADR-007).
Environment
The library reads these variables, as well as the ones named by env::
| Variable | Effect |
|---|---|
NO_COLOR | Disable colour, whatever its value. Takes precedence over FORCE_COLOR |
FORCE_COLOR | Enable colour, whatever its value, even when output is not a terminal |
TERM=dumb | Disable colour |
COLUMNS | Width used to wrap the help page, if it is a whole number of 20 or more. Otherwise 80 |
These are read when the library writes an error or the help page.
POSIXLY_CORRECT is not among them (see Parse modes).
Colour appears only in error messages, never on the help page. With none of these set, colour is on only when standard output is a terminal. The library does not ask the terminal for its width, because PHP cannot do that without starting another process (ADR-040).
Known limits
docs/api.md lists the features the library does
not have, and the limits that are there by design. The one most likely to
affect you: a program with commands takes top-level operands only after
--. The first top-level operand before it is read as a command name
(ADR-014).
How it differs from GetOpt.PHP
GetOpt.PHP is a GNU-style parser with flexible settings. It hands the program strings and leaves checking to callbacks. This library is a POSIX parser by default, with typed values.
- POSIX by default. GetOpt.PHP always reads options after operands, so
tool file -xtreats-xas an option, which POSIX forbids. Here that is opt-in. - Typed values.
-p 80arrives asint(80), checked against its range, not as the string"80". - Rules in the definition. Required options, exclusion groups, environment variables and constraints are declared, not written as callbacks.
- Errors a user can act on. Nine kinds, with suggestions for typos, against three exception classes with a one-line message.
- Immutable. Definitions and results never change, so one
Clican parse any number of lines.
GetOpt.PHP has things this library does not: named operands with their own validation, optional option-arguments, translated messages, a replaceable help page, and support for older PHP versions.
Architecture
The library follows the iDesign Method. Each namespace under
Getopt\Internal\ is one component in one layer, and calls go only
downward:
| Layer | Components |
|---|---|
| Client | Getopt\Cli |
| Manager | Parse Manager, Guidance Manager |
| Engine | Tokenizer, Value, Resolver, Help, Error |
| Accessor | Definitions, Terminal, Environment, Process |
| Utility | String Matching |
The shared vocabulary holds types and no behaviour, so every layer may use
it. Most of it is public, because a program names it: Getopt\Definition,
Getopt\Mode, Getopt\Result, Getopt\Error and Getopt\Attribute. The
types only the library names are in Getopt\Internal\Contracts.
The design adds three rules:
- Only Accessors reach the outside world: the environment, the streams, the terminal and the process.
- Only the Guidance Manager writes output. Every other component that needs to know about the terminal receives its capabilities, which cannot write.
- Engines never call other Engines. The Manager above them sequences the calls.
make check-layers holds every dependency to the layer matrix with
deptrac, make check-resources keeps the outside world inside the
Accessors, make check-contracts checks the contract interfaces against
ADR-008, and make check-records checks the design document's index of
decision records against the records. Each fails the build on a violation.
architecture/sdd.md is the software design document. The decision records in architecture/adr/ record the decisions taken since it, and why. Read the design document before you add a component or change a contract.
Development
| Command | Effect |
|---|---|
make help | List every target |
make install | Install the development tools from composer.lock |
make test | Run every test |
make test-unit | Run the unit tests only |
make cover | Report test coverage, which needs Xdebug or PCOV |
make check | Check the design, the dependencies, the style and the types |
make ci | Everything a change must pass: check, then test |
make fix | Apply the formatter's fixes |
make clean | Remove caches and coverage output |
make check runs the design checks first (layers, resources, contracts,
records and the standalone check), then the formatter and Psalm at its
strictest level. Run make ci before you submit a change.
make ci PHP=php8.5 runs it all under another PHP.
Licence
parasoled/getopt is licensed under the MIT License. The full text is in
LICENSE.
You can use it in any program, open or closed. The one condition is that you keep the copyright notice and the licence text with it.