Download the PHP package consolidation/annotation-command without Composer
On this page you can find all versions of the php package consolidation/annotation-command. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package annotation-command
Consolidation\AnnotatedCommand
Initialize Symfony Console commands from annotated/attributed command class methods.
Component Status
Currently in use in Robo (1.x+), Drush (9.x+) and Terminus (1.x+).
Motivation
Symfony Console provides a set of classes that are widely used to implement command line tools. Increasingly, it is becoming popular to use annotations to describe the characteristics of the command (e.g. its arguments, options and so on) implemented by the annotated method.
Extant commandline tools that utilize this technique include:
This library provides routines to produce the Symfony\Component\Console\Command\Command from all public methods defined in the provided class.
Note If you are looking for a very fast way to write a Symfony Console-base command-line tool, you should consider using Robo, which is built on top of this library, and adds additional conveniences to get you going quickly. Use g1a/starter to quickly scaffold a new commandline tool. See Using Robo as a Framework. It is possible to use this project without Robo if desired, of course.
Library Usage
This is a library intended to be used in some other project. Require from your composer.json file:
Example Annotated Command Class
The public methods of the command class define its commands, and the parameters of each method define its arguments and options. If a parameter has a corresponding "@option" annotation in the docblock, then it is an option; otherwise, it is an argument.
or via PHP 8 attributes.
Legacy Annotated Command Methods
The legacy method for declaring commands is still supported. When using the legacy method, the command options, if any, are declared as the last parameter of the methods. The options will be passed in as an associative array; the default options of the last parameter should list the options recognized by the command. The rest of the parameters are arguments. Parameters with a default value are optional; those without a default value are required.
Option Default Values
The $options
array must be an associative array whose key is the name of the option, and whose value is one of:
- The boolean value
false
, which indicates that the option takes no value. - A string containing the default value for options that may be provided a value, but are not required to.
- The special value InputOption::VALUE_REQUIRED, which indicates that the user must provide a value for the option whenever it is used.
- The special value InputOption::VALUE_OPTIONAL, which produces the following behavior:
- If the option is given a value (e.g.
--foo=bar
), then the value will be a string. - If the option exists on the commandline, but has no value (e.g.
--foo
), then the value will betrue
. - If the option does not exist on the commandline at all, then the value will be
null
. - If the user explicitly sets
--foo=0
, then the value will be converted tofalse
. - LIMITATION: If any Input object other than ArgvInput (or a subclass thereof) is used, then the value will be
null
for both the no-value case (--foo
) and the no-option case. When using a StringInput, use--foo=1
instead of--foo
to avoid this problem.
- If the option is given a value (e.g.
- The special value
true
produces the following behavior:- If the option is given a value (e.g.
--foo=bar
), then the value will be a string. - If the option exists on the commandline, but has no value (e.g.
--foo
), then the value will betrue
. - If the option does not exist on the commandline at all, then the value will also be
true
. - If the user explicitly sets
--foo=0
, then the value will be converted tofalse
. - If the user adds
--no-foo
on the commandline, then the value offoo
will befalse
.
- If the option is given a value (e.g.
- An empty array, which indicates that the option may appear multiple times on the command line.
No other values should be used for the default value. For example, $options = ['a' => 1]
is incorrect; instead, use $options = ['a' => '1']
.
Default values for options may also be provided via the @default
annotation. See hook alter, below.
Hooks
Commandfiles may provide hooks in addition to commands. A commandfile method that contains a @hook annotation is registered as a hook instead of a command. The format of the hook annotation is:
The hook type determines when during the command lifecycle this hook will be called. The available hook types are described in detail below.
The hook target specifies which command or commands the hook will be attached to. There are several different ways to specify the hook target.
- The command's primary name (e.g.
my:command
) or the command's method name (e.g. myCommand) will attach the hook to only that command. - An annotation (e.g.
@foo
) will attach the hook to any command that is annotated with the given label. - If the target is specified as
*
, then the hook will be attached to all commands. - If the target is omitted, then the hook will be attached to every command defined in the same class as the hook implementation.
There are ten types of hooks in the command processing request flow:
- Command Event (Symfony)
- @pre-command-event
- @command-event
- @post-command-event
- Option
- @pre-option
- @option
- @post-option
- Initialize (Symfony)
- @pre-init
- @init
- @post-init
- Interact (Symfony)
- @pre-interact
- @interact
- @post-interact
- Validate
- @pre-validate
- @validate
- @post-validate
- Command
- @pre-command
- @command
- @post-command
- Process
- @pre-process
- @process
- @post-process
- Alter
- @pre-alter
- @alter
- @post-alter
- Status
- @status
- Extract
- @extract
In addition to these, there are two more hooks available:
- On-event
- @on-event
- Replace Command
- @replace-command
The "pre" and "post" varieties of these hooks, where available, give more flexibility vis-a-vis hook ordering (and for consistency). Within one type of hook, the running order is undefined and not guaranteed. Note that many validate, process and alter hooks may run, but the first status or extract hook that successfully returns a result will halt processing of further hooks of the same type.
Each hook has an interface that defines its calling conventions; however, any callable may be used when registering a hook, which is convenient if versions of PHP prior to 7.0 (with no anonymous classes) need to be supported.
Command Event Hook
The command-event hook is called via the Symfony Console command event notification callback mechanism. This happens prior to event dispatching and command / option validation. Note that Symfony does not allow the $input object to be altered in this hook; any change made here will be reset, as Symfony re-parses the object. Changes to arguments and options should be done in the initialize hook (non-interactive alterations) or the interact hook (which is naturally for interactive alterations).
Option Event Hook
The option event hook (Alter Hook documentation below for an example.
Initialize Hook
The initialize hook (InitializeHookInterface) runs prior to the interact hook. It may supply command arguments and options from a configuration file or other sources. It should never do any user interaction.
The consolidation/config project (which is used in Robo PHP) uses @hook init
to automatically inject values from config.yml
configuration files for options that were not provided on the command line.
You may alter the AnnotationData here by using simple array syntax. Below, we add an additional display field label for a Property List.
Alternately, you may use the set()
or append()
methods on the AnnotationData
class.
Interact Hook
The interact hook (InteractorInterface) runs prior to argument and option validation. Required arguments and options not supplied on the command line may be provided during this phase by prompting the user. Note that the interact hook is not called if the --no-interaction flag is supplied, whereas the command-event hook and the init hook are.
Validate Hook
The purpose of the validate hook (ValidatorInterface) is to ensure the state of the targets of the current command are usabe in the context required by that command. Symfony has already validated the arguments and options prior to this hook. It is possible to alter the values of the arguments and options if necessary, although this is better done in the configure hook. A validation hook may take one of several actions:
- Do nothing. This indicates that validation succeeded.
- Return a CommandError. Validation fails, and execution stops. The CommandError contains a status result code and a message, which is printed.
- Throw an exception. The exception is converted into a CommandError.
- Return false. Message is empty, and status is 1. Deprecated.
The validate hook may change the arguments and options of the command by modifying the Input object in the provided CommandData parameter. Any number of validation hooks may run, but if any fails, then execution of the command stops.
Command Hook
The command hook is provided for semantic purposes. The pre-command and command hooks are equivalent to the post-validate hook, and should confirm to the interface (ProcessResultInterface).
The command callback itself (the method annotated @command) is called after the last command hook, and prior to the first post-command hook.
Process Hook
The process hook (CollectionProcessHook class; if a Robo command returns a TaskInterface, then a Robo process hook will execute the task and return the result. This allows a pre-process hook to alter the task, e.g. by adding more operations to a task collection.
The process hook should not be used for other purposes.
Alter Hook
An alter hook (AlterResultInterface) changes the result object. Alter hooks should only operate on result objects of a type they explicitly recognize. They may return an object of the same type, or they may convert the object to some other type.
If something goes wrong, and the alter hooks wishes to force the command to fail, then it may either return a CommandError object, or throw an exception.
If an option needs to be provided with a default value, that may be done via the @default
annotation.
Status Hook
DEPRECATED
Instead of using a Status Determiner hook, commands should simply return their exit code and result data separately using a CommandResult object.
The status hook (ExitCodeInterface, then the getExitCode()
method of the result object is called to determine what the status result code for the command should be. If ExitCodeInterface is not implemented, then all of the status hooks attached to this command are executed; the first one that successfully returns a result will stop further execution of status hooks, and the result it returned will be used as the status result code for this operation.
If no status hook returns any result, then success is presumed.
Extract Hook
DEPRECATED
See RowsOfFieldsWithMetadata in output-formatters for an alternative that is more flexible for most use cases.
The extract hook (OutputDataInterface, then the getOutputData()
method of the result object is called to determine what information should be displayed to the user as a result of the command's execution. If OutputDataInterface is not implemented, then all of the extract hooks attached to this command are executed; the first one that successfully returns output data will stop further execution of extract hooks.
If no extract hook returns any data, then the result object itself is printed if it is a string; otherwise, no output is emitted (other than any produced by the command itself).
On-Event hook
Commands can define their own custom events; to do so, they need only implement the CustomEventAwareInterface, and use the CustomEventAwareTrait. Event handlers for each custom event can then be defined using the on-event hook.
A handler using an on-event hook looks something like the following:
Then, to utilize this in a command:
It is up to the command that defines the custom event to declare what the expected parameters for the callback function should be, and what the return value is and how it should be used.
Replace Command Hook
The replace-command (ReplaceCommandHookInterface) hook permits you to replace a command's method with another method of your own.
For instance, if you'd like to replace the foo:bar
command, you could utilize the following code:
Output
If a command method returns an integer, it is used as the command exit status code. If the command method returns a string, it is printed.
If the Consolidation/OutputFormatters project is used, then users may specify a --format option to select the formatter to use to transform the output from whatever form the command provides to a string. To make this work, the application must provide a formatter to the AnnotatedCommandFactory. See API Usage below.
Logging
The Annotated-Command project is completely agnostic to logging. If a command wishes to log progress, then the CommandFile class should implement LoggerAwareInterface, and the Commandline tool should inject a logger for its use via the LoggerAwareTrait setLogger()
method. Using Robo is recommended.
Access to Symfony Objects
If you want to use annotations, but still want access to the Symfony Command, e.g. to get a reference to the helpers in order to call some legacy code, you may create an ordinary Symfony Command that extends \Consolidation\AnnotatedCommand\AnnotatedCommand, which is a \Symfony\Component\Console\Command\Command. Omit the configure method, and place your annotations on the execute()
method.
It is also possible to add InputInterface and/or OutputInterface parameters to any annotated method of a command file (the parameters must go before command arguments).
Parameter Injection
Just as this library will by default inject $input and/or $output at the head of the parameter list of any command function, it is also possible to add a handler to inject other objects as well.
Given an implementation of SymfonyStyleInjector similar to the example below:
Then, an instance of 'MySymfonyStyle' will be provided to any command handler method that takes a SymfonyStyle parameter if the SymfonyStyleInjector is registered in your application's initialization code like so:
The following classes are available to be injected into the command method by default:
- Symfony\Component\Console\Input\InputInterface
- Symfony\Component\Console\Output\OutputInterface
- Consolidation\AnnotatedCommand\AnnotationData
- Consolidation\OutputFormatters\Options\FormatterOptions
Note that these instances are also available via the CommandData object passed to most command hooks.
Handling Standard Input
Any Symfony command may use the provided StdinHandler to imlement commands that read from standard input.
This example will read all of the data available from the stdin stream into $data, or, alternately, will read the entire contents of the file specified via the --file=/path
option.
For more details, including examples of using the StdinHandle with a DI container, see the comments in StdinHandler.php.
API Usage
If you would like to use Annotated Commands to build a commandline tool, it is recommended that you use Robo as a framework, as it will set up all of the various command classes for you. If you would like to integrate Annotated Commands into some other framework, see the sections below.
Set up Command Factory and Instantiate Commands
To use annotated commands in an application, pass an instance of your command class in to AnnotatedCommandFactory::createCommandsFromClass(). The result will be a list of Commands that may be added to your application.
You may have more than one command class, if you wish. If so, simply call AnnotatedCommandFactory::createCommandsFromClass() multiple times.
If you do not wish every public method in your classes to be added as commands, use AnnotatedCommandFactory::setIncludeAllPublicMethods(false)
, and only methods annotated with @command will become commands.
Note that the setFormatterManager()
operation is optional; omit this if not using Consolidation/OutputFormatters.
A CommandInfoAltererInterface can be added via AnnotatedCommandFactory::addCommandInfoAlterer(); it will be given the opportunity to adjust every CommandInfo object parsed from a command file prior to the creation of commands.
Command File Discovery
A discovery class, CommandFileDiscovery, is also provided to help find command files on the filesystem. Usage is as follows:
For a discussion on command file naming conventions and search locations, see https://github.com/consolidation/annotated-command/issues/12.
If different namespaces are used at different command file paths, change the call to discover as follows:
As a shortcut for the above, the method discoverNamespaced()
will take the last directory name of each path, and append it to the base namespace provided. This matches the conventions used by Drupal modules, for example.
Configuring Output Formatts (e.g. to enable wordwrap)
The Output Formatters project supports automatic formatting of tabular output. In order for wordwrapping to work correctly, the terminal width must be passed in to the Output Formatters handlers via FormatterOptions::setWidth()
.
In the Annotated Commands project, this is done via dependency injection. If a PrepareFormatter
object is passed to CommandProcessor::addPrepareFormatter()
, then it will be given an opportunity to set properties on the FormatterOptions
when it is created.
A PrepareTerminalWidthOption
class is provided to use the Symfony Application class to fetch the terminal width, and provide it to the FormatterOptions. It is injected as follows:
To provide greater control over the width used, create your own PrepareTerminalWidthOption
subclass, and adjust the width as needed.
Other Callbacks
In addition to the hooks provided by the hook manager, there are additional callbacks available to alter the way the annotated command library operates.
Factory Listeners
Factory listeners are notified every time a command file instance is used to create annotated commands.
Listeners can be used to construct command file instances as they are provided to the command factory.
Option Providers
An option provider is given an opportunity to add options to a command as it is being constructed.
The complete CommandInfo record with all of the annotation data is available, so you can, for example, add an option --foo
to every command whose method is annotated @fooable
.
CommandInfo Alterers
CommandInfo alterers can adjust information about a command immediately before it is created. Typically, these will be used to supply default values for annotations custom to the command, or take other actions based on the interfaces implemented by the commandfile instance.
All versions of annotation-command with dependencies
consolidation/output-formatters Version ^4.3.1
psr/log Version ^1 || ^2 || ^3
symfony/console Version ^4.4.8 || ^5 || ^6 || ^7
symfony/event-dispatcher Version ^4.4.8 || ^5 || ^6 || ^7
symfony/finder Version ^4.4.8 || ^5 || ^6 || ^7