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