Version 1
[yaffs-website] / vendor / consolidation / annotated-command / README.md
1 # Consolidation\AnnotatedCommand
2
3 Initialize Symfony Console commands from annotated command class methods.
4
5 [![Travis CI](https://travis-ci.org/consolidation/annotated-command.svg?branch=master)](https://travis-ci.org/consolidation/annotated-command)
6 [![Windows CI](https://ci.appveyor.com/api/projects/status/c2c4lcf43ux4c30p?svg=true)](https://ci.appveyor.com/project/greg-1-anderson/annotated-command)
7 [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/consolidation/annotated-command/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/consolidation/annotated-command/?branch=master)
8 [![Coverage Status](https://coveralls.io/repos/github/consolidation/annotated-command/badge.svg?branch=master)](https://coveralls.io/github/consolidation/annotated-command?branch=master) 
9 [![License](https://poser.pugx.org/consolidation/annotated-command/license)](https://packagist.org/packages/consolidation/annotated-command)
10
11 ## Component Status
12
13 Currently in use in [Robo](https://github.com/consolidation/Robo) (1.x+), [Drush](https://github.com/drush-ops/drush) (9.x+) and [Terminus](https://github.com/pantheon-systems/terminus) (1.x+).
14
15 ## Motivation
16
17 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.
18
19 Extant commandline tools that utilize this technique include:
20
21 - [Robo](https://github.com/consolidation/Robo)
22 - [wp-cli](https://github.com/wp-cli/wp-cli)
23 - [Pantheon Terminus](https://github.com/pantheon-systems/terminus)
24
25 This library provides routines to produce the Symfony\Component\Console\Command\Command from all public methods defined in the provided class.
26
27 **Note** If you are looking for a very fast way to write a Symfony Console-base command-line tool, you should consider using [Robo](https://github.com/consolidation/Robo), which is built on top of this library, and adds additional conveniences to get you going quickly. See [Using Robo as a Framework](https://github.com/consolidation/Robo/docs/framework.md).  It is possible to use this project without Robo if desired, of course.
28
29 ## Library Usage
30
31 This is a library intended to be used in some other project.  Require from your composer.json file:
32 ```
33     "require": {
34         "consolidation/annotated-command": "~2"
35     },
36 ```
37
38 ## Example Annotated Command Class
39 The public methods of the command class define its commands, and the parameters of each method define its arguments and options. 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.
40
41 The rest of the parameters are arguments. Parameters with a default value are optional; those without a default value are required.
42 ```php
43 class MyCommandClass
44 {
45     /**
46      * This is the my:cat command
47      *
48      * This command will concatenate two parameters. If the --flip flag
49      * is provided, then the result is the concatenation of two and one.
50      *
51      * @command my:cat
52      * @param integer $one The first parameter.
53      * @param integer $two The other parameter.
54      * @option arr An option that takes multiple values.
55      * @option flip Whether or not the second parameter should come first in the result.
56      * @aliases c
57      * @usage bet alpha --flip
58      *   Concatenate "alpha" and "bet".
59      */
60     public function myCat($one, $two, $options = ['flip' => false])
61     {
62         if ($options['flip']) {
63             return "{$two}{$one}";
64         }
65         return "{$one}{$two}";
66     }
67 }
68 ``` 
69 ## Option Default Values
70
71 The `$options` array must be an associative array whose key is the name of the option, and whose value is one of:
72
73 - The boolean value `false`, which indicates that the option takes no value.
74 - A **string** containing the default value for options that may be provided a value, but are not required to.
75 - NULL for options that may be provided an optional value, but that have no default when a value is not provided.
76 - The special value InputOption::VALUE_REQUIRED, which indicates that the user must provide a value for the option whenever it is used.
77 - An empty array, which indicates that the option may appear multiple times on the command line.
78
79 No other values should be used for the default value. For example, `$options = ['a' => 1]` is **incorrect**; instead, use `$options = ['a' => '1']`. Similarly, `$options = ['a' => true]` is unsupported, or at least not useful, as this would indicate that the value of `--a` was always `true`, whether or not it appeared on the command line.
80
81 ## Hooks
82
83 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:
84 ```
85 @hook type commandname|annotation
86 ```
87 The commandname may be the command's primary name (e.g. `my:command`), it's method name (e.g. myCommand) or any of its aliases.
88
89 If an annotation is given instead, then this hook function will run for all commands with the specified annotation.
90
91 There are ten types of hooks supported:
92
93 - Command Event (Symfony)
94 - Option
95 - Initialize (Symfony)
96 - Interact (Symfony)
97 - Validate
98 - Command
99 - Process
100 - Alter
101 - Status
102 - Extract
103 - On-event
104 - Replace Command
105
106 Most of these also have "pre" and "post" varieties, to give more flexibility vis-a-vis hook ordering (and for consistency). 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.
107
108 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.
109
110 ### Command Event Hook
111
112 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).
113
114 ### Option Event Hook
115
116 The option event hook ([OptionHookInterface](src/Hooks/OptionHookInterface.php)) is called for a specific command, whenever it is executed, or its help command is called. Any additional options for the command may be added here by instantiating and returnng an InputOption array.
117
118 ### Initialize Hook
119
120 The initialize hook ([InitializeHookInterface](src/Hooks/InitializeHookInterface.php)) 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.
121
122 ### Interact Hook
123
124 The interact hook ([InteractorInterface](src/Hooks/InteractorInterface.php)) 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 inject-configuration hook are.
125
126 ### Validate Hook
127
128 The purpose of the validate hook ([ValidatorInterface](src/Hooks/ValidatorInterface.php)) 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:
129
130 - Do nothing. This indicates that validation succeeded.
131 - Return a CommandError. Validation fails, and execution stops. The CommandError contains a status result code and a message, which is printed.
132 - Throw an exception. The exception is converted into a CommandError.
133 - Return false. Message is empty, and status is 1. Deprecated.
134
135 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.
136
137 ### Command Hook
138
139 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 ([ValidatorInterface](src/Hooks/ValidatorInterface.php)).  All of the post-validate hooks will be called before the first pre-command hook is called.  Similarly, the post-command hook is equivalent to the pre-process hook, and should implement the interface ([ProcessResultInterface](src/Hooks/ProcessResultInterface.php)).
140
141 The command callback itself (the method annotated @command) is called after the last command hook, and prior to the first post-command hook.
142
143 ### Process Hook
144
145 The process hook ([ProcessResultInterface](src/Hooks/ProcessResultInterface.php)) is specifically designed to convert a series of processing instructions into a final result.  An example of this is implemented in Robo; 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.
146
147 The process hook should not be used for other purposes.
148
149 ### Alter Hook
150
151 An alter hook ([AlterResultInterface](src/Hooks/AlterResultInterface.php)) 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.
152
153 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.
154
155 ### Status Hook
156
157 The status hook ([StatusDeterminerInterface](src/Hooks/StatusDeterminerInterface.php)) is responsible for determing whether a command succeeded (status code 0) or failed (status code > 0).  The result object returned by a command may be a compound object that contains multiple bits of information about the command result.  If the result object implements [ExitCodeInterface](ExitCodeInterface.php), 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.
158
159 If no status hook returns any result, then success is presumed.
160
161 ### Extract Hook
162
163 The extract hook ([ExtractOutputInterface](src/Hooks/ExtractOutputInterface.php)) is responsible for determining what the actual rendered output for the command should be.  The result object returned by a command may be a compound object that contains multiple bits of information about the command result.  If the result object implements [OutputDataInterface](OutputDataInterface.php), 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.
164
165 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).
166
167 ### On-Event hook
168
169 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.
170
171 A handler using an on-event hook looks something like the following:
172 ```
173 /**
174  * @hook on-event custom-event
175  */
176 public function handlerForCustomEvent(/* arbitrary parameters, as defined by custom-event */)
177 {
178     // do the needful, return what custom-event expects
179 }
180 ```
181 Then, to utilize this in a command:
182 ```
183 class MyCommands implements CustomEventAwareInterface
184 {
185     use CustomEventAwareTrait;
186
187     /**
188      * @command my-command
189      */
190     public myCommand($options = [])
191     {
192         $handlers = $this->getCustomEventHandlers('custom-event');
193         // iterate and call $handlers
194     }
195 }
196 ```
197 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.
198
199 ### Replace Command Hook
200
201 The replace-command ([ReplaceCommandHookInterface](src/Hooks/ReplaceCommandHookInterface.php)) hook permits you to replace a command's method with another method of your own.
202
203 For instance, if you'd like to replace the `foo:bar` command, you could utilize the following code:
204
205 ```php
206 <?php
207 class MyReplaceCommandHook  {
208
209   /**
210    * @hook replace-command foo:bar
211    * 
212    * Parameters must match original command method. 
213    */
214   public function myFooBarReplacement($value) {
215     print "Hello $value!";
216   }
217 }
218 ```
219
220 ## Output
221
222 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.
223
224 If the [Consolidation/OutputFormatters](https://github.com/consolidation/output-formatters) 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](#api-usage) below.
225
226 ## Logging
227
228 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](https://github.com/consolidation/robo) is recommended.
229
230 ## Access to Symfony Objects
231
232 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.
233
234 It is also possible to add InputInterface or OutputInterface parameters to any annotated method of a command file.
235
236 ## API Usage
237
238 If you would like to use Annotated Commands to build a commandline tool, it is recommended that you use [Robo as a framework](http://robo.li/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.
239
240 ### Set up Command Factory and Instantiate Commands
241
242 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.
243 ```php
244 $myCommandClassInstance = new MyCommandClass();
245 $commandFactory = new AnnotatedCommandFactory();
246 $commandFactory->setIncludeAllPublicMethods(true);
247 $commandFactory->commandProcessor()->setFormatterManager(new FormatterManager());
248 $commandList = $commandFactory->createCommandsFromClass($myCommandClassInstance);
249 foreach ($commandList as $command) {
250     $application->add($command);
251 }
252 ```
253 You may have more than one command class, if you wish. If so, simply call AnnotatedCommandFactory::createCommandsFromClass() multiple times.
254
255 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.
256
257 Note that the `setFormatterManager()` operation is optional; omit this if not using [Consolidation/OutputFormatters](https://github.com/consolidation/output-formatters).
258
259 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.
260
261 ### Command File Discovery
262
263 A discovery class, CommandFileDiscovery, is also provided to help find command files on the filesystem. Usage is as follows:
264 ```php
265 $discovery = new CommandFileDiscovery();
266 $myCommandFiles = $discovery->discover($path, '\Drupal');
267 foreach ($myCommandFiles as $myCommandClass) {
268     $myCommandClassInstance = new $myCommandClass();
269     // ... as above
270 }
271 ```
272 For a discussion on command file naming conventions and search locations, see https://github.com/consolidation/annotated-command/issues/12.
273
274 If different namespaces are used at different command file paths, change the call to discover as follows:
275 ```php
276 $myCommandFiles = $discovery->discover(['\Ns1' => $path1, '\Ns2' => $path2]);
277 ```
278 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.
279
280 ### Configuring Output Formatts (e.g. to enable wordwrap)
281
282 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()`.
283
284 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.
285
286 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:
287 ```php
288 $terminalWidthOption = new PrepareTerminalWidthOption();
289 $terminalWidthOption->setApplication($application);
290 $commandFactory->commandProcessor()->addPrepareFormatter($terminalWidthOption);
291 ```
292 To provide greater control over the width used, create your own `PrepareTerminalWidthOption` subclass, and adjust the width as needed.
293
294 ## Other Callbacks
295
296 In addition to the hooks provided by the hook manager, there are additional callbacks available to alter the way the annotated command library operates.
297
298 ### Factory Listeners
299
300 Factory listeners are notified every time a command file instance is used to create annotated commands.
301 ```
302 public function AnnotatedCommandFactory::addListener(CommandCreationListenerInterface $listener);
303 ```
304 Listeners can be used to construct command file instances as they are provided to the command factory.
305
306 ### Option Providers
307
308 An option provider is given an opportunity to add options to a command as it is being constructed.  
309 ```
310 public function AnnotatedCommandFactory::addAutomaticOptionProvider(AutomaticOptionsProviderInterface $listener);
311 ```
312 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`.
313
314 ### CommandInfo Alterers
315
316 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.
317 ```
318 public function alterCommandInfo(CommandInfo $commandInfo, $commandFileInstance);
319 ```
320
321 ## Comparison to Existing Solutions
322
323 The existing solutions used their own hand-rolled regex-based parsers to process the contents of the DocBlock comments. consolidation/annotated-command uses the [phpdocumentor/reflection-docblock](https://github.com/phpDocumentor/ReflectionDocBlock) project (which is itself a regex-based parser) to interpret DocBlock contents.