Yaffs site version 1.1
[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      * @throws \Exception When binding input fails. Bypass this by calling {@link ignoreValidationErrors()}.
209      *
210      * @see setCode()
211      * @see execute()
212      */
213     public function run(InputInterface $input, OutputInterface $output)
214     {
215         // force the creation of the synopsis before the merge with the app definition
216         $this->getSynopsis(true);
217         $this->getSynopsis(false);
218
219         // add the application arguments and options
220         $this->mergeApplicationDefinition();
221
222         // bind the input against the command specific arguments/options
223         try {
224             $input->bind($this->definition);
225         } catch (ExceptionInterface $e) {
226             if (!$this->ignoreValidationErrors) {
227                 throw $e;
228             }
229         }
230
231         $this->initialize($input, $output);
232
233         if (null !== $this->processTitle) {
234             if (function_exists('cli_set_process_title')) {
235                 if (false === @cli_set_process_title($this->processTitle)) {
236                     if ('Darwin' === PHP_OS) {
237                         $output->writeln('<comment>Running "cli_get_process_title" as an unprivileged user is not supported on MacOS.</comment>');
238                     } else {
239                         $error = error_get_last();
240                         trigger_error($error['message'], E_USER_WARNING);
241                     }
242                 }
243             } elseif (function_exists('setproctitle')) {
244                 setproctitle($this->processTitle);
245             } elseif (OutputInterface::VERBOSITY_VERY_VERBOSE === $output->getVerbosity()) {
246                 $output->writeln('<comment>Install the proctitle PECL to be able to change the process title.</comment>');
247             }
248         }
249
250         if ($input->isInteractive()) {
251             $this->interact($input, $output);
252         }
253
254         // The command name argument is often omitted when a command is executed directly with its run() method.
255         // It would fail the validation if we didn't make sure the command argument is present,
256         // since it's required by the application.
257         if ($input->hasArgument('command') && null === $input->getArgument('command')) {
258             $input->setArgument('command', $this->getName());
259         }
260
261         $input->validate();
262
263         if ($this->code) {
264             $statusCode = call_user_func($this->code, $input, $output);
265         } else {
266             $statusCode = $this->execute($input, $output);
267         }
268
269         return is_numeric($statusCode) ? (int) $statusCode : 0;
270     }
271
272     /**
273      * Sets the code to execute when running this command.
274      *
275      * If this method is used, it overrides the code defined
276      * in the execute() method.
277      *
278      * @param callable $code A callable(InputInterface $input, OutputInterface $output)
279      *
280      * @return $this
281      *
282      * @throws InvalidArgumentException
283      *
284      * @see execute()
285      */
286     public function setCode($code)
287     {
288         if (!is_callable($code)) {
289             throw new InvalidArgumentException('Invalid callable provided to Command::setCode.');
290         }
291
292         if (PHP_VERSION_ID >= 50400 && $code instanceof \Closure) {
293             $r = new \ReflectionFunction($code);
294             if (null === $r->getClosureThis()) {
295                 if (PHP_VERSION_ID < 70000) {
296                     // Bug in PHP5: https://bugs.php.net/bug.php?id=64761
297                     // This means that we cannot bind static closures and therefore we must
298                     // ignore any errors here.  There is no way to test if the closure is
299                     // bindable.
300                     $code = @\Closure::bind($code, $this);
301                 } else {
302                     $code = \Closure::bind($code, $this);
303                 }
304             }
305         }
306
307         $this->code = $code;
308
309         return $this;
310     }
311
312     /**
313      * Merges the application definition with the command definition.
314      *
315      * This method is not part of public API and should not be used directly.
316      *
317      * @param bool $mergeArgs Whether to merge or not the Application definition arguments to Command definition arguments
318      */
319     public function mergeApplicationDefinition($mergeArgs = true)
320     {
321         if (null === $this->application || (true === $this->applicationDefinitionMerged && ($this->applicationDefinitionMergedWithArgs || !$mergeArgs))) {
322             return;
323         }
324
325         $this->definition->addOptions($this->application->getDefinition()->getOptions());
326
327         if ($mergeArgs) {
328             $currentArguments = $this->definition->getArguments();
329             $this->definition->setArguments($this->application->getDefinition()->getArguments());
330             $this->definition->addArguments($currentArguments);
331         }
332
333         $this->applicationDefinitionMerged = true;
334         if ($mergeArgs) {
335             $this->applicationDefinitionMergedWithArgs = true;
336         }
337     }
338
339     /**
340      * Sets an array of argument and option instances.
341      *
342      * @param array|InputDefinition $definition An array of argument and option instances or a definition instance
343      *
344      * @return $this
345      */
346     public function setDefinition($definition)
347     {
348         if ($definition instanceof InputDefinition) {
349             $this->definition = $definition;
350         } else {
351             $this->definition->setDefinition($definition);
352         }
353
354         $this->applicationDefinitionMerged = false;
355
356         return $this;
357     }
358
359     /**
360      * Gets the InputDefinition attached to this Command.
361      *
362      * @return InputDefinition An InputDefinition instance
363      */
364     public function getDefinition()
365     {
366         return $this->definition;
367     }
368
369     /**
370      * Gets the InputDefinition to be used to create XML and Text representations of this Command.
371      *
372      * Can be overridden to provide the original command representation when it would otherwise
373      * be changed by merging with the application InputDefinition.
374      *
375      * This method is not part of public API and should not be used directly.
376      *
377      * @return InputDefinition An InputDefinition instance
378      */
379     public function getNativeDefinition()
380     {
381         return $this->getDefinition();
382     }
383
384     /**
385      * Adds an argument.
386      *
387      * @param string $name        The argument name
388      * @param int    $mode        The argument mode: InputArgument::REQUIRED or InputArgument::OPTIONAL
389      * @param string $description A description text
390      * @param mixed  $default     The default value (for InputArgument::OPTIONAL mode only)
391      *
392      * @return $this
393      */
394     public function addArgument($name, $mode = null, $description = '', $default = null)
395     {
396         $this->definition->addArgument(new InputArgument($name, $mode, $description, $default));
397
398         return $this;
399     }
400
401     /**
402      * Adds an option.
403      *
404      * @param string $name        The option name
405      * @param string $shortcut    The shortcut (can be null)
406      * @param int    $mode        The option mode: One of the InputOption::VALUE_* constants
407      * @param string $description A description text
408      * @param mixed  $default     The default value (must be null for InputOption::VALUE_NONE)
409      *
410      * @return $this
411      */
412     public function addOption($name, $shortcut = null, $mode = null, $description = '', $default = null)
413     {
414         $this->definition->addOption(new InputOption($name, $shortcut, $mode, $description, $default));
415
416         return $this;
417     }
418
419     /**
420      * Sets the name of the command.
421      *
422      * This method can set both the namespace and the name if
423      * you separate them by a colon (:)
424      *
425      *     $command->setName('foo:bar');
426      *
427      * @param string $name The command name
428      *
429      * @return $this
430      *
431      * @throws InvalidArgumentException When the name is invalid
432      */
433     public function setName($name)
434     {
435         $this->validateName($name);
436
437         $this->name = $name;
438
439         return $this;
440     }
441
442     /**
443      * Sets the process title of the command.
444      *
445      * This feature should be used only when creating a long process command,
446      * like a daemon.
447      *
448      * PHP 5.5+ or the proctitle PECL library is required
449      *
450      * @param string $title The process title
451      *
452      * @return $this
453      */
454     public function setProcessTitle($title)
455     {
456         $this->processTitle = $title;
457
458         return $this;
459     }
460
461     /**
462      * Returns the command name.
463      *
464      * @return string The command name
465      */
466     public function getName()
467     {
468         return $this->name;
469     }
470
471     /**
472      * Sets the description for the command.
473      *
474      * @param string $description The description for the command
475      *
476      * @return $this
477      */
478     public function setDescription($description)
479     {
480         $this->description = $description;
481
482         return $this;
483     }
484
485     /**
486      * Returns the description for the command.
487      *
488      * @return string The description for the command
489      */
490     public function getDescription()
491     {
492         return $this->description;
493     }
494
495     /**
496      * Sets the help for the command.
497      *
498      * @param string $help The help for the command
499      *
500      * @return $this
501      */
502     public function setHelp($help)
503     {
504         $this->help = $help;
505
506         return $this;
507     }
508
509     /**
510      * Returns the help for the command.
511      *
512      * @return string The help for the command
513      */
514     public function getHelp()
515     {
516         return $this->help;
517     }
518
519     /**
520      * Returns the processed help for the command replacing the %command.name% and
521      * %command.full_name% patterns with the real values dynamically.
522      *
523      * @return string The processed help for the command
524      */
525     public function getProcessedHelp()
526     {
527         $name = $this->name;
528
529         $placeholders = array(
530             '%command.name%',
531             '%command.full_name%',
532         );
533         $replacements = array(
534             $name,
535             $_SERVER['PHP_SELF'].' '.$name,
536         );
537
538         return str_replace($placeholders, $replacements, $this->getHelp() ?: $this->getDescription());
539     }
540
541     /**
542      * Sets the aliases for the command.
543      *
544      * @param string[] $aliases An array of aliases for the command
545      *
546      * @return $this
547      *
548      * @throws InvalidArgumentException When an alias is invalid
549      */
550     public function setAliases($aliases)
551     {
552         if (!is_array($aliases) && !$aliases instanceof \Traversable) {
553             throw new InvalidArgumentException('$aliases must be an array or an instance of \Traversable');
554         }
555
556         foreach ($aliases as $alias) {
557             $this->validateName($alias);
558         }
559
560         $this->aliases = $aliases;
561
562         return $this;
563     }
564
565     /**
566      * Returns the aliases for the command.
567      *
568      * @return array An array of aliases for the command
569      */
570     public function getAliases()
571     {
572         return $this->aliases;
573     }
574
575     /**
576      * Returns the synopsis for the command.
577      *
578      * @param bool $short Whether to show the short version of the synopsis (with options folded) or not
579      *
580      * @return string The synopsis
581      */
582     public function getSynopsis($short = false)
583     {
584         $key = $short ? 'short' : 'long';
585
586         if (!isset($this->synopsis[$key])) {
587             $this->synopsis[$key] = trim(sprintf('%s %s', $this->name, $this->definition->getSynopsis($short)));
588         }
589
590         return $this->synopsis[$key];
591     }
592
593     /**
594      * Add a command usage example.
595      *
596      * @param string $usage The usage, it'll be prefixed with the command name
597      *
598      * @return $this
599      */
600     public function addUsage($usage)
601     {
602         if (0 !== strpos($usage, $this->name)) {
603             $usage = sprintf('%s %s', $this->name, $usage);
604         }
605
606         $this->usages[] = $usage;
607
608         return $this;
609     }
610
611     /**
612      * Returns alternative usages of the command.
613      *
614      * @return array
615      */
616     public function getUsages()
617     {
618         return $this->usages;
619     }
620
621     /**
622      * Gets a helper instance by name.
623      *
624      * @param string $name The helper name
625      *
626      * @return mixed The helper value
627      *
628      * @throws LogicException           if no HelperSet is defined
629      * @throws InvalidArgumentException if the helper is not defined
630      */
631     public function getHelper($name)
632     {
633         if (null === $this->helperSet) {
634             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));
635         }
636
637         return $this->helperSet->get($name);
638     }
639
640     /**
641      * Returns a text representation of the command.
642      *
643      * @return string A string representing the command
644      *
645      * @deprecated since version 2.3, to be removed in 3.0.
646      */
647     public function asText()
648     {
649         @trigger_error('The '.__METHOD__.' method is deprecated since version 2.3 and will be removed in 3.0.', E_USER_DEPRECATED);
650
651         $descriptor = new TextDescriptor();
652         $output = new BufferedOutput(BufferedOutput::VERBOSITY_NORMAL, true);
653         $descriptor->describe($output, $this, array('raw_output' => true));
654
655         return $output->fetch();
656     }
657
658     /**
659      * Returns an XML representation of the command.
660      *
661      * @param bool $asDom Whether to return a DOM or an XML string
662      *
663      * @return string|\DOMDocument An XML string representing the command
664      *
665      * @deprecated since version 2.3, to be removed in 3.0.
666      */
667     public function asXml($asDom = false)
668     {
669         @trigger_error('The '.__METHOD__.' method is deprecated since version 2.3 and will be removed in 3.0.', E_USER_DEPRECATED);
670
671         $descriptor = new XmlDescriptor();
672
673         if ($asDom) {
674             return $descriptor->getCommandDocument($this);
675         }
676
677         $output = new BufferedOutput();
678         $descriptor->describe($output, $this);
679
680         return $output->fetch();
681     }
682
683     /**
684      * Validates a command name.
685      *
686      * It must be non-empty and parts can optionally be separated by ":".
687      *
688      * @param string $name
689      *
690      * @throws InvalidArgumentException When the name is invalid
691      */
692     private function validateName($name)
693     {
694         if (!preg_match('/^[^\:]++(\:[^\:]++)*$/', $name)) {
695             throw new InvalidArgumentException(sprintf('Command name "%s" is invalid.', $name));
696         }
697     }
698 }