Search by

parasoled / getopt

parasoled

A POSIX command-line parser with typed values, validation and generated help.

v1.0.0 2026-11-21 13:37 UTC

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.

  1. Define. Each option comes from a typed constructor, such as Option::int(short: 'p', description: 'The port', min: 1), and each command from Command::define(). A definition is a final readonly value, and making one checks nothing beyond PHP's types.
  2. Build. Cli::build(name: 'name', ...) takes the whole definition as named arguments, validates it, and returns an immutable Cli. It throws a DefinitionError for an invalid definition, such as a duplicate name, a long name under the POSIX mode, or a default: of the wrong type. Treat a DefinitionError as a programming error. Cli::fromClass() does the same from a readonly class whose constructor parameters carry option attributes.
  3. Parse. runOrExit() or run() 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()).
  4. Read. The ParseResult has a typed accessor for each kind of value: bool(), int(), float(), string() and list(), 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 is false, an unset count 0 and an unset list []. Any other option nothing set is null. A name no option has, or an accessor that does not suit the option's kind, throws a LogicException, 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).

ConstructorCommand linePHP typeAccessor
Option::flag()--loudboolbool()
Option::count()-vvvint (3)int()
Option::int()--port 80?intint()
Option::float()--ratio 1.5?floatfloat()
Option::string()--name Ada?stringstring()
Option::path()--file a.txt?stringstring()
Option::choice()--mode fast?stringstring()
Option::list()--tag a,b --tag clist<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:

PrecedenceSourceResolvedValue::$source
1Command lineValueSource::CommandLine
2The variable named by env:ValueSource::Environment
3default: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

InputRead as
-lShort option
-abcClustered short flags: -a -b -c
-n Ada, -nAdaShort option with a value
--name AdaLong option with a separate value. Long options only
--name=AdaLong option with an attached value. Long options only
--na AdaAbbreviated 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.

ChoicePOSIXExtension
SyntaxShort options only: -vlongOptions: -v and --verbose
OrderOptions end at the first operandoptionsAfterOperands: tool a.txt -v reads -v as an option
MatchingExact namesabbreviations: --verb for --verbose

Two presets name the ends:

PresetLong optionsOptions after operandsAbbreviations
ParseMode::Posix (the default)NoNoNo
ParseMode::PermissiveYesYesYes

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): ParseResultrun(?array $arguments = null): ParseResult
Help optionWrites help to standard output, exits 0Returns a result whose outcome() is Outcome::HelpRequested
Version optionWrites the version to standard output, exits 0Returns a result whose outcome() is Outcome::VersionRequested
Parse errorWrites the explain() text and a usage hint to standard error, exits 1Throws the CLIParseError
Exit statuses0, 0 and 1, or the ones exitStatuses: namesEnds nothing
Writes outputYesNever

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).

ClassCause
UnknownOptionThe option is not defined
MissingValueAn option that takes a value had none
InvalidValueConversion or a rule failed
MissingRequiredA required: true option was not given
MutualExclusionTwo options from one exclusion group were given
UnknownCommandThe command is not defined
AmbiguousOptionAn abbreviation matched more than one option
InvalidOperandsThe operands fall outside operands:
ValueOutOfRangeA 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::

VariableEffect
NO_COLORDisable colour, whatever its value. Takes precedence over FORCE_COLOR
FORCE_COLOREnable colour, whatever its value, even when output is not a terminal
TERM=dumbDisable colour
COLUMNSWidth 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 -x treats -x as an option, which POSIX forbids. Here that is opt-in.
  • Typed values. -p 80 arrives as int(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 Cli can 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:

LayerComponents
ClientGetopt\Cli
ManagerParse Manager, Guidance Manager
EngineTokenizer, Value, Resolver, Help, Error
AccessorDefinitions, Terminal, Environment, Process
UtilityString 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

CommandEffect
make helpList every target
make installInstall the development tools from composer.lock
make testRun every test
make test-unitRun the unit tests only
make coverReport test coverage, which needs Xdebug or PCOV
make checkCheck the design, the dependencies, the style and the types
make ciEverything a change must pass: check, then test
make fixApply the formatter's fixes
make cleanRemove 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.