627da5ec8b487796f14928b908f294a361a23fa1
[yaffs-website] / vendor / symfony / console / Command / Command.php
1 <?php
2
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 namespace Symfony\Component\Console\Command;
13
14 use Symfony\Component\Console\Exception\ExceptionInterface;
15 use Symfony\Component\Console\Input\InputDefinition;
16 use Symfony\Component\Console\Input\InputOption;
17 use Symfony\Component\Console\Input\InputArgument;
18 use Symfony\Component\Console\Input\InputInterface;
19 use Symfony\Component\Console\Output\OutputInterface;
20 use Symfony\Component\Console\Application;
21 use Symfony\Component\Console\Helper\HelperSet;
22 use Symfony\Component\Console\Exception\InvalidArgumentException;
23 use Symfony\Component\Console\Exception\LogicException;
24
25 /**
26  * Base class for all commands.
27  *
28  * @author Fabien Potencier <fabien@symfony.com>
29  */
30 class Command
31 {
32     /**
33      * @var string|null The default command name
34      */
35     protected static $defaultName;
36
37     private $application;
38     private $name;
39     private $processTitle;
40     private $aliases = array();
41     private $definition;
42     private $hidden = false;
43     private $help;
44     private $description;
45     private $ignoreValidationErrors = false;
46     private $applicationDefinitionMerged = false;
47     private $applicationDefinitionMergedWithArgs = false;
48     private $code;
49     private $synopsis = array();
50     private $usages = array();
51     private $helperSet;
52
53     /**
54      * @return string|null The default command name or null when no default name is set
55      */
56     public static function getDefaultName()
57     {
58         $class = get_called_class();
59         $r = new \ReflectionProperty($class, 'defaultName');
60
61         return $class === $r->class ? static::$defaultName : null;
62     }
63
64     /**
65      * @param string|null $name The name of the command; passing null means it must be set in configure()
66      *
67      * @throws LogicException When the command name is empty
68      */
69     public function __construct($name = null)
70     {
71         $this->definition = new InputDefinition();
72
73         if (null !== $name || null !== $name = static::getDefaultName()) {
74             $this->setName($name);
75         }
76
77         $this->configure();
78     }
79
80     /**
81      * Ignores validation errors.
82      *
83      * This is mainly useful for the help command.
84      */
85     public function ignoreValidationErrors()
86     {
87         $this->ignoreValidationErrors = true;
88     }
89
90     public function setApplication(Application $application = null)
91     {
92         $this->application = $application;
93         if ($application) {
94             $this->setHelperSet($application->getHelperSet());
95         } else {
96             $this->helperSet = null;
97         }
98     }
99
100     public function setHelperSet(HelperSet $helperSet)
101     {
102         $this->helperSet = $helperSet;
103     }
104
105     /**
106      * Gets the helper set.
107      *
108      * @return HelperSet A HelperSet instance
109      */
110     public function getHelperSet()
111     {
112         return $this->helperSet;
113     }
114
115     /**
116      * Gets the application instance for this command.
117      *
118      * @return Application An Application instance
119      */
120     public function getApplication()
121     {
122         return $this->application;
123     }
124
125     /**
126      * Checks whether the command is enabled or not in the current environment.
127      *
128      * Override this to check for x or y and return false if the command can not
129      * run properly under the current conditions.
130      *
131      * @return bool
132      */
133     public function isEnabled()
134     {
135         return true;
136     }
137
138     /**
139      * Configures the current command.
140      */
141     protected function configure()
142     {
143     }
144
145     /**
146      * Executes the current command.
147      *
148      * This method is not abstract because you can use this class
149      * as a concrete class. In this case, instead of defining the
150      * execute() method, you set the code to execute by passing
151      * a Closure to the setCode() method.
152      *
153      * @return null|int null or 0 if everything went fine, or an error code
154      *
155      * @throws LogicException When this abstract method is not implemented
156      *
157      * @see setCode()
158      */
159     protected function execute(InputInterface $input, OutputInterface $output)
160     {
161         throw new LogicException('You must override the execute() method in the concrete command class.');
162     }
163
164     /**
165      * Interacts with the user.
166      *
167      * This method is executed before the InputDefinition is validated.
168      * This means that this is the only place where the command can
169      * interactively ask for values of missing required arguments.
170      */
171     protected function interact(InputInterface $input, OutputInterface $output)
172     {
173     }
174
175     /**
176      * Initializes the command just after the input has been validated.
177      *
178      * This is mainly useful when a lot of commands extends one main command
179      * where some things need to be initialized based on the input arguments and options.
180      */
181     protected function initialize(InputInterface $input, OutputInterface $output)
182     {
183     }
184
185     /**
186      * Runs the command.
187      *
188      * The code to execute is either defined directly with the
189      * setCode() method or by overriding the execute() method
190      * in a sub-class.
191      *
192      * @return int The command exit code
193      *
194      * @throws \Exception When binding input fails. Bypass this by calling {@link ignoreValidationErrors()}.
195      *
196      * @see setCode()
197      * @see execute()
198      */
199     public function run(InputInterface $input, OutputInterface $output)
200     {
201         // force the creation of the synopsis before the merge with the app definition
202         $this->getSynopsis(true);
203         $this->getSynopsis(false);
204
205         // add the application arguments and options
206         $this->mergeApplicationDefinition();
207
208         // bind the input against the command specific arguments/options
209         try {
210             $input->bind($this->definition);
211         } catch (ExceptionInterface $e) {
212             if (!$this->ignoreValidationErrors) {
213                 throw $e;
214             }
215         }
216
217         $this->initialize($input, $output);
218
219         if (null !== $this->processTitle) {
220             if (function_exists('cli_set_process_title')) {
221                 if (!@cli_set_process_title($this->processTitle)) {
222                     if ('Darwin' === PHP_OS) {
223                         $output->writeln('<comment>Running "cli_get_process_title" as an unprivileged user is not supported on MacOS.</comment>');
224                     } else {
225                         cli_set_process_title($this->processTitle);
226                     }
227                 }
228             } elseif (function_exists('setproctitle')) {
229                 setproctitle($this->processTitle);
230             } elseif (OutputInterface::VERBOSITY_VERY_VERBOSE === $output->getVerbosity()) {
231                 $output->writeln('<comment>Install the proctitle PECL to be able to change the process title.</comment>');
232             }
233         }
234
235         if ($input->isInteractive()) {
236             $this->interact($input, $output);
237         }
238
239         // The command name argument is often omitted when a command is executed directly with its run() method.
240         // It would fail the validation if we didn't make sure the command argument is present,
241         // since it's required by the application.
242         if ($input->hasArgument('command') && null === $input->getArgument('command')) {
243             $input->setArgument('command', $this->getName());
244         }
245
246         $input->validate();
247
248         if ($this->code) {
249             $statusCode = call_user_func($this->code, $input, $output);
250         } else {
251             $statusCode = $this->execute($input, $output);
252         }
253
254         return is_numeric($statusCode) ? (int) $statusCode : 0;
255     }
256
257     /**
258      * Sets the code to execute when running this command.
259      *
260      * If this method is used, it overrides the code defined
261      * in the execute() method.
262      *
263      * @param callable $code A callable(InputInterface $input, OutputInterface $output)
264      *
265      * @return $this
266      *
267      * @throws InvalidArgumentException
268      *
269      * @see execute()
270      */
271     public function setCode(callable $code)
272     {
273         if ($code instanceof \Closure) {
274             $r = new \ReflectionFunction($code);
275             if (null === $r->getClosureThis()) {
276                 if (\PHP_VERSION_ID < 70000) {
277                     // Bug in PHP5: https://bugs.php.net/bug.php?id=64761
278                     // This means that we cannot bind static closures and therefore we must
279                     // ignore any errors here.  There is no way to test if the closure is
280                     // bindable.
281                     $code = @\Closure::bind($code, $this);
282                 } else {
283                     $code = \Closure::bind($code, $this);
284                 }
285             }
286         }
287
288         $this->code = $code;
289
290         return $this;
291     }
292
293     /**
294      * Merges the application definition with the command definition.
295      *
296      * This method is not part of public API and should not be used directly.
297      *
298      * @param bool $mergeArgs Whether to merge or not the Application definition arguments to Command definition arguments
299      */
300     public function mergeApplicationDefinition($mergeArgs = true)
301     {
302         if (null === $this->application || (true === $this->applicationDefinitionMerged && ($this->applicationDefinitionMergedWithArgs || !$mergeArgs))) {
303             return;
304         }
305
306         $this->definition->addOptions($this->application->getDefinition()->getOptions());
307
308         if ($mergeArgs) {
309             $currentArguments = $this->definition->getArguments();
310             $this->definition->setArguments($this->application->getDefinition()->getArguments());
311             $this->definition->addArguments($currentArguments);
312         }
313
314         $this->applicationDefinitionMerged = true;
315         if ($mergeArgs) {
316             $this->applicationDefinitionMergedWithArgs = true;
317         }
318     }
319
320     /**
321      * Sets an array of argument and option instances.
322      *
323      * @param array|InputDefinition $definition An array of argument and option instances or a definition instance
324      *
325      * @return $this
326      */
327     public function setDefinition($definition)
328     {
329         if ($definition instanceof InputDefinition) {
330             $this->definition = $definition;
331         } else {
332             $this->definition->setDefinition($definition);
333         }
334
335         $this->applicationDefinitionMerged = false;
336
337         return $this;
338     }
339
340     /**
341      * Gets the InputDefinition attached to this Command.
342      *
343      * @return InputDefinition An InputDefinition instance
344      */
345     public function getDefinition()
346     {
347         return $this->definition;
348     }
349
350     /**
351      * Gets the InputDefinition to be used to create representations of this Command.
352      *
353      * Can be overridden to provide the original command representation when it would otherwise
354      * be changed by merging with the application InputDefinition.
355      *
356      * This method is not part of public API and should not be used directly.
357      *
358      * @return InputDefinition An InputDefinition instance
359      */
360     public function getNativeDefinition()
361     {
362         return $this->getDefinition();
363     }
364
365     /**
366      * Adds an argument.
367      *
368      * @param string $name        The argument name
369      * @param int    $mode        The argument mode: InputArgument::REQUIRED or InputArgument::OPTIONAL
370      * @param string $description A description text
371      * @param mixed  $default     The default value (for InputArgument::OPTIONAL mode only)
372      *
373      * @return $this
374      */
375     public function addArgument($name, $mode = null, $description = '', $default = null)
376     {
377         $this->definition->addArgument(new InputArgument($name, $mode, $description, $default));
378
379         return $this;
380     }
381
382     /**
383      * Adds an option.
384      *
385      * @param string $name        The option name
386      * @param string $shortcut    The shortcut (can be null)
387      * @param int    $mode        The option mode: One of the InputOption::VALUE_* constants
388      * @param string $description A description text
389      * @param mixed  $default     The default value (must be null for InputOption::VALUE_NONE)
390      *
391      * @return $this
392      */
393     public function addOption($name, $shortcut = null, $mode = null, $description = '', $default = null)
394     {
395         $this->definition->addOption(new InputOption($name, $shortcut, $mode, $description, $default));
396
397         return $this;
398     }
399
400     /**
401      * Sets the name of the command.
402      *
403      * This method can set both the namespace and the name if
404      * you separate them by a colon (:)
405      *
406      *     $command->setName('foo:bar');
407      *
408      * @param string $name The command name
409      *
410      * @return $this
411      *
412      * @throws InvalidArgumentException When the name is invalid
413      */
414     public function setName($name)
415     {
416         $this->validateName($name);
417
418         $this->name = $name;
419
420         return $this;
421     }
422
423     /**
424      * Sets the process title of the command.
425      *
426      * This feature should be used only when creating a long process command,
427      * like a daemon.
428      *
429      * PHP 5.5+ or the proctitle PECL library is required
430      *
431      * @param string $title The process title
432      *
433      * @return $this
434      */
435     public function setProcessTitle($title)
436     {
437         $this->processTitle = $title;
438
439         return $this;
440     }
441
442     /**
443      * Returns the command name.
444      *
445      * @return string The command name
446      */
447     public function getName()
448     {
449         return $this->name;
450     }
451
452     /**
453      * @param bool $hidden Whether or not the command should be hidden from the list of commands
454      *
455      * @return Command The current instance
456      */
457     public function setHidden($hidden)
458     {
459         $this->hidden = (bool) $hidden;
460
461         return $this;
462     }
463
464     /**
465      * @return bool whether the command should be publicly shown or not
466      */
467     public function isHidden()
468     {
469         return $this->hidden;
470     }
471
472     /**
473      * Sets the description for the command.
474      *
475      * @param string $description The description for the command
476      *
477      * @return $this
478      */
479     public function setDescription($description)
480     {
481         $this->description = $description;
482
483         return $this;
484     }
485
486     /**
487      * Returns the description for the command.
488      *
489      * @return string The description for the command
490      */
491     public function getDescription()
492     {
493         return $this->description;
494     }
495
496     /**
497      * Sets the help for the command.
498      *
499      * @param string $help The help for the command
500      *
501      * @return $this
502      */
503     public function setHelp($help)
504     {
505         $this->help = $help;
506
507         return $this;
508     }
509
510     /**
511      * Returns the help for the command.
512      *
513      * @return string The help for the command
514      */
515     public function getHelp()
516     {
517         return $this->help;
518     }
519
520     /**
521      * Returns the processed help for the command replacing the %command.name% and
522      * %command.full_name% patterns with the real values dynamically.
523      *
524      * @return string The processed help for the command
525      */
526     public function getProcessedHelp()
527     {
528         $name = $this->name;
529
530         $placeholders = array(
531             '%command.name%',
532             '%command.full_name%',
533         );
534         $replacements = array(
535             $name,
536             $_SERVER['PHP_SELF'].' '.$name,
537         );
538
539         return str_replace($placeholders, $replacements, $this->getHelp() ?: $this->getDescription());
540     }
541
542     /**
543      * Sets the aliases for the command.
544      *
545      * @param string[] $aliases An array of aliases for the command
546      *
547      * @return $this
548      *
549      * @throws InvalidArgumentException When an alias is invalid
550      */
551     public function setAliases($aliases)
552     {
553         if (!is_array($aliases) && !$aliases instanceof \Traversable) {
554             throw new InvalidArgumentException('$aliases must be an array or an instance of \Traversable');
555         }
556
557         foreach ($aliases as $alias) {
558             $this->validateName($alias);
559         }
560
561         $this->aliases = $aliases;
562
563         return $this;
564     }
565
566     /**
567      * Returns the aliases for the command.
568      *
569      * @return array An array of aliases for the command
570      */
571     public function getAliases()
572     {
573         return $this->aliases;
574     }
575
576     /**
577      * Returns the synopsis for the command.
578      *
579      * @param bool $short Whether to show the short version of the synopsis (with options folded) or not
580      *
581      * @return string The synopsis
582      */
583     public function getSynopsis($short = false)
584     {
585         $key = $short ? 'short' : 'long';
586
587         if (!isset($this->synopsis[$key])) {
588             $this->synopsis[$key] = trim(sprintf('%s %s', $this->name, $this->definition->getSynopsis($short)));
589         }
590
591         return $this->synopsis[$key];
592     }
593
594     /**
595      * Add a command usage example.
596      *
597      * @param string $usage The usage, it'll be prefixed with the command name
598      *
599      * @return $this
600      */
601     public function addUsage($usage)
602     {
603         if (0 !== strpos($usage, $this->name)) {
604             $usage = sprintf('%s %s', $this->name, $usage);
605         }
606
607         $this->usages[] = $usage;
608
609         return $this;
610     }
611
612     /**
613      * Returns alternative usages of the command.
614      *
615      * @return array
616      */
617     public function getUsages()
618     {
619         return $this->usages;
620     }
621
622     /**
623      * Gets a helper instance by name.
624      *
625      * @param string $name The helper name
626      *
627      * @return mixed The helper value
628      *
629      * @throws LogicException           if no HelperSet is defined
630      * @throws InvalidArgumentException if the helper is not defined
631      */
632     public function getHelper($name)
633     {
634         if (null === $this->helperSet) {
635             throw new LogicException(sprintf('Cannot retrieve helper "%s" because there is no HelperSet defined. Did you forget to add your command to the application or to set the application on the command using the setApplication() method? You can also set the HelperSet directly using the setHelperSet() method.', $name));
636         }
637
638         return $this->helperSet->get($name);
639     }
640
641     /**
642      * Validates a command name.
643      *
644      * It must be non-empty and parts can optionally be separated by ":".
645      *
646      * @param string $name
647      *
648      * @throws InvalidArgumentException When the name is invalid
649      */
650     private function validateName($name)
651     {
652         if (!preg_match('/^[^\:]++(\:[^\:]++)*$/', $name)) {
653             throw new InvalidArgumentException(sprintf('Command name "%s" is invalid.', $name));
654         }
655     }
656 }