mini\CLI\ArgManager
class
Documentation
Command-line argument parser with subcommand support
Provides an immutable, fluent interface for parsing CLI arguments with support for subcommands, option validation, and positional arguments.
Features
- Subcommand support: Parse nested command structures (git commit -m "message")
- Short options:
-v,-vvv,-i value,-ivalue - Long options:
--verbose,--match=pattern,--match pattern - Unified short/long: Query by either name, get same result
- Option validation: Required/optional values with automatic error handling
- Immutable design: All operations return new instances
- Command delegation: Easy pass-through to external tools
Quick Start
// Simple command: myapp -v --output=file.txt
$args = mini\args(
(new ArgManager())
->withFlag('v', 'verbose')
->withRequiredValue('o', 'output')
);
if ($args->getUnparsedArgs()) {
die("Unexpected: " . implode(', ', $args->getUnparsedArgs()));
}
$verbosity = $args->getFlag('verbose');
$output = $args->getOption('output');
Subcommands
// myapp -v run --fast target
$args = mini\args(
(new ArgManager())
->withFlag('v', 'verbose')
->withSubcommand('run', 'build', 'test')
);
if ($args->getUnparsedArgs()) {
die("Unexpected: " . implode(', ', $args->getUnparsedArgs()));
}
$sub = $args->nextCommand();
if ($sub?->getCommand() === 'run') {
$run = $sub->withFlag(null, 'fast');
$target = $run->getUnparsedArgs()[0] ?? null;
}
Stopping Option Parsing
Use -- to stop option parsing and treat everything after as unparsed arguments:
// myapp -v -- --not-an-option file.txt
$args = mini\args((new ArgManager())->withFlag('v', 'verbose'));
$args->getUnparsedArgs(); // ['--not-an-option', 'file.txt']
Properties (10)
int $next_index
array $declared
array $shortToCanonical
array $subcommands
array $parsedOpts
array $unparsedArgs
string $matchedSubcommand
array $customArgv
int $start_index
Methods (21)
Create a new ArgManager instance
Create an ArgManager from a custom argv array
Get the argv array to parse
Declare a boolean flag option
Declare an option that requires a value
Declare an option with an optional value
Declare valid subcommands
Get the count of times a flag was provided
Get the value of an option
Check if an option was provided
Get unparsed arguments (unknown options, undeclared subcommands, or args after --)
Get the command name at this context's starting position
Get a new ArgManager for the next subcommand
Get the parent command's ArgManager
Get all remaining arguments from current position (unparsed)
Declare an option
Resolve option name to canonical form
Parse argv if not already done
Parse a long option, return next index or false if unknown
Parse short option(s), return next index or false if unknown
Add option value, handling repeated options as arrays