Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 0
API Reference
The full public surface of initphp/console. Behavioural deep-dives are
linked into the Building Commands and
Output & Interaction sections.
Signatures are shown as they appear in the source. The library targets PHP 7.2+, so it uses PHPDoc (not native types) for
mixed/union return values.?Typenullable hints and scalar parameter/return types are native.
Classes & interfaces
ApplicationCommandInput/InputInterfaceInputArgumentOutput/OutputInterfaceQuestionHelpersUtils\Table
InitPHP\Console\Application — the command registry and dispatcher.
publicconstVERSION = '2.1.0';publicfunction __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 is created lazily during run(). Inject
one (e.g. backed by a memory stream) to capture output in tests.
publicfunction register(string$command, ?callable$execute = null, string$definition = ''): self;Registers a command. Two modes:
- Closure mode (
$executeis a callable):$commandis the command name,$definitionis the short listing description. - Class mode (
$executeisnull):$commandis the fully-qualified name of aCommandsubclass. It is instantiated; its$command,definition()andhelp()are read from the instance.
Returns $this. Throws:
\InvalidArgumentException— the class does not exist, is not aCommand, or (closure mode) the handler is not callable.\LogicException— aCommandclass does not set its$commandname.
See Exceptions.
publicfunction 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/listran, 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.
InitPHP\Console\Command — abstract base class for class-based commands.
public$command; // the invocation name (set in a subclass)abstractpublicfunction execute(Input$input, Output$output);
publicfunction help(): string; // default: 'No explanation for this command is specified.'publicfunction definition(): string; // default: ''publicfunction arguments(): array; // default: [] — array<int, InputArgument>$command must be set by the subclass. arguments() returns the typed
InputArgument declarations validated before execute().
See Commands.
InitPHP\Console\InputInterface — read access to parsed tokens.
publicfunction hasArgument(string$name): bool;
publicfunction getArgument(string$name, $default = null); // mixedpublicfunction allArguments(): array; // array<string, mixed>publicfunction hasSegment(int$index): bool;
publicfunction getSegment(int$index, $default = null); // mixedpublicfunction allSegment(): array; // array<int, mixed>publicfunction hasOption(string$name): bool;
publicfunction getOption(string$name, $default = null); // mixedpublicfunction allOptions(): array; // array<string, mixed>publicfunction importArguments(array ...$arguments): void; // merge maps (later wins)Implemented by Input. Depend on the interface in helpers that only
read input.
InitPHP\Console\Input implements InputInterface — parses the tokens that
follow the command name.
publicfunction __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().
Identical to InputInterface. See Input for
worked examples.
InitPHP\Console\InputArgument (final) — a typed --name argument.
publicconstANY = 'ANY';
publicconstINT = 'INT';
publicconstFLOAT = 'FLOAT';
publicconstNUMERIC = 'NUMBER';
publicconstBOOL = 'BOOL';
publicconstSTR = 'STRING';publicfunction __construct(
string$name,
$type, // one of the constants above$default, // must satisfy $typebool$isOptional = true,
string$definition = ''
);Throws \InvalidArgumentException if $type is unsupported or $default
does not satisfy it.
publicfunction isOptional(): bool;
publicfunction getType(): string; // the type constant value, e.g. "INT"publicfunction getName(): string; // the name prefixed with "--"publicfunction getDefinition(): string;
publicfunction getDefault(): ?string; // default as a string, or nullpublicfunction 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.
InitPHP\Console\OutputInterface — the writing/prompting contract.
publicfunction write(string$str, array$context = [], bool$newLine = false, array$format = []): void;
publicfunction writeln(string$str, array$context = [], array$format = []): void;
publicfunction list(array$rows, int$leftSpace = 0): void;
publicfunction progressBar($done, $total): void;
publicfunction ask(string$question, bool$empty = true); // mixedpublicfunction question(Question$question); // mixedpublicfunction error(string$msg, array$context = []): void;
publicfunction success(string$msg, array$context = []): void;
publicfunction warning(string$msg, array$context = []): void;
publicfunction info(string$msg, array$context = []): void;Implemented by Output.
The concrete
Outputuses[Output::COLOR_DEFAULT]as the default$formatforwrite()/writeln()(the interface declares[]since it cannot reference the implementation's constants). Both render uncoloured text by default.
InitPHP\Console\Output implements OutputInterface.
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).
publicfunction __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.
publicfunction write(string$str, array$context = [], bool$newLine = false, array$format = [self::COLOR_DEFAULT]): void;
publicfunction writeln(string$str, array$context = [], array$format = [self::COLOR_DEFAULT]): void;
publicfunction list(array$rows, int$leftSpace = 0): void;
publicfunction progressBar($done, $total): void; // throws \InvalidArgumentExceptionpublicfunction ask(string$question, bool$empty = true);
publicfunction question(Question$question);
publicfunction error(string$msg, array$context = []): void;
publicfunction success(string$msg, array$context = []): void;
publicfunction warning(string$msg, array$context = []): void;
publicfunction 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.
protectedfunction 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.
InitPHP\Console\Question — value object for an interactive question.
publicconstNO_DEFAULT = '__Qu€sti0nN0D€f@ultV@lue__'; // sentinel; prefer hasDefault()publicfunction isOptional(): bool;
publicfunction optional(): self;
publicfunction notOptional(): self;
publicfunction hasOption(string$option): bool; // matches verbatim or castpublicfunction setOptions(array$options): self;
publicfunction getOptions(): array;
publicfunction addOption(string$option, $value = self::NO_DEFAULT): self;
publicfunction setQuestion(string$question): self;
publicfunction getQuestion(): string; // '' when unsetpublicfunction setDefault($default): self;
publicfunction hasDefault(): bool;
publicfunctiongetDefault(); // mixed, or NO_DEFAULT when unsetDefault options are [true, false]. See Questions.
InitPHP\Console\Helpers (final).
publicstaticfunction strValueCast(string$value); // mixedCasts 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.
InitPHP\Console\Utils\Table — ASCII/ANSI table renderer.
The same COLOR_*, BACKGROUND_*, ITALIC/BOLD/UNDERLINE/STRIKETHROUGH
constants (and values) as Output.
publicstaticfunction create(): Table;
publicfunction __toString(): string; // === getContent()publicfunction setHeaderStyle(int ...$format): self; // default [BOLD]publicfunction setCellStyle(int ...$format): self;
publicfunction setBorderStyle(int ...$format): self;
publicfunction setColumnCellStyle(string$column, int ...$format): self;
publicfunction row(array$assoc): self; // append a rowpublicfunction getContent(): string; // renderrow() 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.
src/aliases.php (loaded via Composer files autoloading) registers:
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.
initphp/console · MIT License · part of the InitPHP family
Source · Issues · Discussions · Packagist · Contributing · Security Policy
Getting Started
Building Commands
Output & Interaction
Reference
Practical Guides
Migration & Help