Security update for Core, with self-updated composer
[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](http://robo.li/framework/).  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 - The special value InputOption::VALUE_REQUIRED, which indicates that the user must provide a value for the option whenever it is used.
76 - The special value InputOption::VALUE_OPTIONAL, which produces the following behavior:
77   - If the option is given a value (e.g. `--foo=bar`), then the value will be a string.
78   - If the option exists on the commandline, but has no value (e.g. `--foo`), then the value will be `true`.
79   - If the option does not exist on the commandline at all, then the value will be `null`.
80   - If the user explicitly sets `--foo=0`, then the value will be converted to `false`.
81   - 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.
82 - The special value `true` produces the following behavior:
83   - If the option is given a value (e.g. `--foo=bar`), then the value will be a string.
84   - If the option exists on the commandline, but has no value (e.g. `--foo`), then the value will be `true`.
85   - If the option does not exist on the commandline at all, then the value will also be `true`.
86   - If the user explicitly sets `--foo=0`, then the value will be converted to `false`.
87   - If the user adds `--no-foo` on the commandline, then the value of `foo` will be `false`.
88 - An empty array, which indicates that the option may appear multiple times on the command line.
89
90 No other values should be used for the default value. For example, `$options = ['a' => 1]` is **incorrect**; instead, use `$options = ['a' => '1']`.
91
92 Default values for options may also be provided via the `@default` annotation. See hook alter, below.
93
94 ## Hooks
95
96 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:
97 ```
98 @hook type target
99 ```
100 The hook **type** determines when during the command lifecycle this hook will be called. The available hook types are described in detail below.
101
102 The hook **target** specifies which command or commands the hook will be attached to. There are several different ways to specify the hook target.
103
104 - 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.
105 - An annotation (e.g. `@foo`) will attach the hook to any command that is annotated with the given label.
106 - If the target is omitted, then the hook will be attached to every command defined in the same class as the hook implementation.
107
108 There are ten types of hooks in the command processing request flow:
109
110 - [Command Event](#command-event-hook) (Symfony)
111    - @pre-command-event
112    - @command-event
113    - @post-command-event
114 - [Option](#option-event-hook)
115    - @pre-option
116    - @option
117    - @post-option
118 - [Initialize](#initialize-hook) (Symfony)
119    - @pre-init
120    - @init
121    - @post-init
122 - [Interact](#interact-hook) (Symfony)
123    - @pre-interact
124    - @interact
125    - @post-interact
126 - [Validate](#validate-hook)
127    - @pre-validate
128    - @validate
129    - @post-validate
130 - [Command](#command-hook)
131    - @pre-command
132    - @command
133    - @command-init
134 - [Process](#process-hook)
135    - @pre-process
136    - @process
137    - @post-process
138 - [Alter](#alter-hook)
139    - @pre-alter
140    - @alter
141    - @post-alter
142 - [Status](#status-hook)
143    - @status
144 - [Extract](#extract-hook)
145    - @extract
146    
147 In addition to these, there are two more hooks available:
148
149 - [On-event](#on-event-hook)
150    - @on-event
151 - [Replace Command](#replace-command-hook)
152    - @replace-command
153
154 The "pre" and "post" varieties of these hooks, where avalable, 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.
155
156 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.
157
158 ### Command Event Hook
159
160 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).
161
162 ### Option Event Hook
163
164 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 calling the `addOption` method of the provided `$command` object. Note that the option hook is only necessary for calculating dynamic options. Static options may be added via the @option annotation on any hook that uses them. See the [Alter Hook](https://github.com/consolidation/annotated-command#alter-hook) documentation below for an example.
165 ```
166 use Consolidation\AnnotatedCommand\AnnotationData;
167 use Symfony\Component\Console\Command\Command;
168
169 /**
170  * @hook option some:command
171  */
172 public function additionalOption(Command $command, AnnotationData $annotationData)
173 {
174     $command->addOption(
175         'dynamic',
176         '',
177         InputOption::VALUE_NONE,
178         'Option added by @hook option some:command'
179     );
180 }
181 ```
182
183 ### Initialize Hook
184
185 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.
186
187 The [consolidation/config](https://github.com/consolidation/config) project (which is used in [Robo PHP](https://github.com/consolidation/robo)) uses `@hook init` to automatically inject values from `config.yml` configuration files for options that were not provided on the command line.
188 ```
189 use Consolidation\AnnotatedCommand\AnnotationData;
190 use Symfony\Component\Console\Input\InputInterface;
191
192 /**
193  * @hook init some:command
194  */
195 public function initSomeCommand(InputInterface $input, AnnotationData $annotationData)
196 {
197     $value = $input->getOption('some-option');
198     if (!$value) {
199         $input->setOption('some-option', $this->generateRandomOptionValue());
200     }
201 }
202 ```
203
204 ### Interact Hook
205
206 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 init hook are.
207 ```
208 use Consolidation\AnnotatedCommand\AnnotationData;
209 use Symfony\Component\Console\Input\InputInterface;
210 use Symfony\Component\Console\Output\OutputInterface;
211 use Symfony\Component\Console\Style\SymfonyStyle;
212
213 /**
214  * @hook interact some:command
215  */
216 public function interact(InputInterface $input, OutputInterface $output, AnnotationData $annotationData)
217 {
218     $io = new SymfonyStyle($input, $output);
219
220     // If the user did not specify a password, then prompt for one.
221     $password = $input->getOption('password');
222     if (empty($password)) {
223         $password = $io->askHidden("Enter a password:", function ($value) { return $value; });
224         $input->setOption('password', $password);
225     }
226 }
227 ```
228
229 ### Validate Hook
230
231 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:
232
233 - Do nothing. This indicates that validation succeeded.
234 - Return a CommandError. Validation fails, and execution stops. The CommandError contains a status result code and a message, which is printed.
235 - Throw an exception. The exception is converted into a CommandError.
236 - Return false. Message is empty, and status is 1. Deprecated.
237
238 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.
239 ```
240 use Consolidation\AnnotatedCommand\CommandData;
241
242 /**
243  * @hook validate some:command
244  */
245 public function validatePassword(CommandData $commandData)
246 {
247     $input = $commandData->input();
248     $password = $input->getOption('password');
249
250     if (strpbrk($password, '!;$`') === false) {
251         throw new \Exception("Your password MUST contain at least one of the characters ! ; ` or $, for no rational reason whatsoever.");
252     }
253 }
254 ```
255
256 ### Command Hook
257
258 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)).
259
260 The command callback itself (the method annotated @command) is called after the last command hook, and prior to the first post-command hook.
261 ```
262 use Consolidation\AnnotatedCommand\CommandData;
263
264 /**
265  * @hook pre-command some:command
266  */
267 public function preCommand(CommandData $commandData)
268 {
269     // Do something before some:command
270 }
271
272 /**
273  * @hook post-command some:command
274  */
275 public function postCommand($result, CommandData $commandData)
276 {
277     // Do something after some:command
278 }
279 ```
280
281 ### Process Hook
282
283 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 in the [CollectionProcessHook](https://github.com/consolidation/Robo/blob/master/src/Collection/CollectionProcessHook.php) 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.
284
285 The process hook should not be used for other purposes.
286 ```
287 use Consolidation\AnnotatedCommand\CommandData;
288
289 /**
290  * @hook process some:command
291  */
292 public function process($result, CommandData $commandData)
293 {
294     if ($result instanceof MyInterimType) {
295         $result = $this->convertInterimResult($result);
296     }
297 }
298 ```
299
300 ### Alter Hook
301
302 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.
303
304 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.
305 ```
306 use Consolidation\AnnotatedCommand\CommandData;
307
308 /**
309  * Demonstrate an alter hook with an option
310  *
311  * @hook alter some:command
312  * @option $alteration Alter the result of the command in some way.
313  * @usage some:command --alteration
314  */
315 public function alterSomeCommand($result, CommandData $commandData)
316 {
317     if ($commandData->input()->getOption('alteration')) {
318         $result[] = $this->getOneMoreRow();
319     }
320
321     return $result;
322 }
323 ```
324
325 If an option needs to be provided with a default value, that may be done via the `@default` annotation.
326
327 ```
328 use Consolidation\AnnotatedCommand\CommandData;
329
330 /**
331  * Demonstrate an alter hook with an option that has a default value
332  *
333  * @hook alter some:command
334  * @option $name Give the result a name.
335  * @default $name George
336  * @usage some:command --name=George
337  */
338 public function nameSomeCommand($result, CommandData $commandData)
339 {
340     $result['name'] = $commandData->input()->getOption('name')
341
342     return $result;
343 }
344 ```
345
346 ### Status Hook
347
348 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.
349
350 If no status hook returns any result, then success is presumed.
351
352 ### Extract Hook
353
354 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.
355
356 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).
357
358 ### On-Event hook
359
360 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.
361
362 A handler using an on-event hook looks something like the following:
363 ```
364 /**
365  * @hook on-event custom-event
366  */
367 public function handlerForCustomEvent(/* arbitrary parameters, as defined by custom-event */)
368 {
369     // do the needful, return what custom-event expects
370 }
371 ```
372 Then, to utilize this in a command:
373 ```
374 class MyCommands implements CustomEventAwareInterface
375 {
376     use CustomEventAwareTrait;
377
378     /**
379      * @command my-command
380      */
381     public myCommand($options = [])
382     {
383         $handlers = $this->getCustomEventHandlers('custom-event');
384         // iterate and call $handlers
385     }
386 }
387 ```
388 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.
389
390 ### Replace Command Hook
391
392 The replace-command ([ReplaceCommandHookInterface](src/Hooks/ReplaceCommandHookInterface.php)) hook permits you to replace a command's method with another method of your own.
393
394 For instance, if you'd like to replace the `foo:bar` command, you could utilize the following code:
395
396 ```php
397 <?php
398 class MyReplaceCommandHook  {
399
400   /**
401    * @hook replace-command foo:bar
402    * 
403    * Parameters must match original command method. 
404    */
405   public function myFooBarReplacement($value) {
406     print "Hello $value!";
407   }
408 }
409 ```
410
411 ## Output
412
413 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.
414
415 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.
416
417 ## Logging
418
419 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.
420
421 ## Access to Symfony Objects
422
423 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.
424
425 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).
426
427 ## API Usage
428
429 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.
430
431 ### Set up Command Factory and Instantiate Commands
432
433 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.
434 ```php
435 $myCommandClassInstance = new MyCommandClass();
436 $commandFactory = new AnnotatedCommandFactory();
437 $commandFactory->setIncludeAllPublicMethods(true);
438 $commandFactory->commandProcessor()->setFormatterManager(new FormatterManager());
439 $commandList = $commandFactory->createCommandsFromClass($myCommandClassInstance);
440 foreach ($commandList as $command) {
441     $application->add($command);
442 }
443 ```
444 You may have more than one command class, if you wish. If so, simply call AnnotatedCommandFactory::createCommandsFromClass() multiple times.
445
446 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.
447
448 Note that the `setFormatterManager()` operation is optional; omit this if not using [Consolidation/OutputFormatters](https://github.com/consolidation/output-formatters).
449
450 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.
451
452 ### Command File Discovery
453
454 A discovery class, CommandFileDiscovery, is also provided to help find command files on the filesystem. Usage is as follows:
455 ```php
456 $discovery = new CommandFileDiscovery();
457 $myCommandFiles = $discovery->discover($path, '\Drupal');
458 foreach ($myCommandFiles as $myCommandClass) {
459     $myCommandClassInstance = new $myCommandClass();
460     // ... as above
461 }
462 ```
463 For a discussion on command file naming conventions and search locations, see https://github.com/consolidation/annotated-command/issues/12.
464
465 If different namespaces are used at different command file paths, change the call to discover as follows:
466 ```php
467 $myCommandFiles = $discovery->discover(['\Ns1' => $path1, '\Ns2' => $path2]);
468 ```
469 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.
470
471 ### Configuring Output Formatts (e.g. to enable wordwrap)
472
473 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()`.
474
475 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.
476
477 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:
478 ```php
479 $terminalWidthOption = new PrepareTerminalWidthOption();
480 $terminalWidthOption->setApplication($application);
481 $commandFactory->commandProcessor()->addPrepareFormatter($terminalWidthOption);
482 ```
483 To provide greater control over the width used, create your own `PrepareTerminalWidthOption` subclass, and adjust the width as needed.
484
485 ## Other Callbacks
486
487 In addition to the hooks provided by the hook manager, there are additional callbacks available to alter the way the annotated command library operates.
488
489 ### Factory Listeners
490
491 Factory listeners are notified every time a command file instance is used to create annotated commands.
492 ```
493 public function AnnotatedCommandFactory::addListener(CommandCreationListenerInterface $listener);
494 ```
495 Listeners can be used to construct command file instances as they are provided to the command factory.
496
497 ### Option Providers
498
499 An option provider is given an opportunity to add options to a command as it is being constructed.  
500 ```
501 public function AnnotatedCommandFactory::addAutomaticOptionProvider(AutomaticOptionsProviderInterface $listener);
502 ```
503 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`.
504
505 ### CommandInfo Alterers
506
507 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.
508 ```
509 public function alterCommandInfo(CommandInfo $commandInfo, $commandFileInstance);
510 ```
511
512 ## Comparison to Existing Solutions
513
514 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.