comparison vendor/symfony/console/Command/Command.php @ 0:4c8ae668cc8c

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
children 7a779792577d
comparison
equal deleted inserted replaced
-1:000000000000 0:4c8ae668cc8c
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 private $application;
33 private $name;
34 private $processTitle;
35 private $aliases = array();
36 private $definition;
37 private $hidden = false;
38 private $help;
39 private $description;
40 private $ignoreValidationErrors = false;
41 private $applicationDefinitionMerged = false;
42 private $applicationDefinitionMergedWithArgs = false;
43 private $code;
44 private $synopsis = array();
45 private $usages = array();
46 private $helperSet;
47
48 /**
49 * Constructor.
50 *
51 * @param string|null $name The name of the command; passing null means it must be set in configure()
52 *
53 * @throws LogicException When the command name is empty
54 */
55 public function __construct($name = null)
56 {
57 $this->definition = new InputDefinition();
58
59 if (null !== $name) {
60 $this->setName($name);
61 }
62
63 $this->configure();
64
65 if (!$this->name) {
66 throw new LogicException(sprintf('The command defined in "%s" cannot have an empty name.', get_class($this)));
67 }
68 }
69
70 /**
71 * Ignores validation errors.
72 *
73 * This is mainly useful for the help command.
74 */
75 public function ignoreValidationErrors()
76 {
77 $this->ignoreValidationErrors = true;
78 }
79
80 /**
81 * Sets the application instance for this command.
82 *
83 * @param Application $application An Application instance
84 */
85 public function setApplication(Application $application = null)
86 {
87 $this->application = $application;
88 if ($application) {
89 $this->setHelperSet($application->getHelperSet());
90 } else {
91 $this->helperSet = null;
92 }
93 }
94
95 /**
96 * Sets the helper set.
97 *
98 * @param HelperSet $helperSet A HelperSet instance
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 * @param InputInterface $input An InputInterface instance
154 * @param OutputInterface $output An OutputInterface instance
155 *
156 * @return null|int null or 0 if everything went fine, or an error code
157 *
158 * @throws LogicException When this abstract method is not implemented
159 *
160 * @see setCode()
161 */
162 protected function execute(InputInterface $input, OutputInterface $output)
163 {
164 throw new LogicException('You must override the execute() method in the concrete command class.');
165 }
166
167 /**
168 * Interacts with the user.
169 *
170 * This method is executed before the InputDefinition is validated.
171 * This means that this is the only place where the command can
172 * interactively ask for values of missing required arguments.
173 *
174 * @param InputInterface $input An InputInterface instance
175 * @param OutputInterface $output An OutputInterface instance
176 */
177 protected function interact(InputInterface $input, OutputInterface $output)
178 {
179 }
180
181 /**
182 * Initializes the command just after the input has been validated.
183 *
184 * This is mainly useful when a lot of commands extends one main command
185 * where some things need to be initialized based on the input arguments and options.
186 *
187 * @param InputInterface $input An InputInterface instance
188 * @param OutputInterface $output An OutputInterface instance
189 */
190 protected function initialize(InputInterface $input, OutputInterface $output)
191 {
192 }
193
194 /**
195 * Runs the command.
196 *
197 * The code to execute is either defined directly with the
198 * setCode() method or by overriding the execute() method
199 * in a sub-class.
200 *
201 * @param InputInterface $input An InputInterface instance
202 * @param OutputInterface $output An OutputInterface instance
203 *
204 * @return int The command exit code
205 *
206 * @throws \Exception When binding input fails. Bypass this by calling {@link ignoreValidationErrors()}.
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(callable $code)
285 {
286 if ($code instanceof \Closure) {
287 $r = new \ReflectionFunction($code);
288 if (null === $r->getClosureThis()) {
289 if (PHP_VERSION_ID < 70000) {
290 // Bug in PHP5: https://bugs.php.net/bug.php?id=64761
291 // This means that we cannot bind static closures and therefore we must
292 // ignore any errors here. There is no way to test if the closure is
293 // bindable.
294 $code = @\Closure::bind($code, $this);
295 } else {
296 $code = \Closure::bind($code, $this);
297 }
298 }
299 }
300
301 $this->code = $code;
302
303 return $this;
304 }
305
306 /**
307 * Merges the application definition with the command definition.
308 *
309 * This method is not part of public API and should not be used directly.
310 *
311 * @param bool $mergeArgs Whether to merge or not the Application definition arguments to Command definition arguments
312 */
313 public function mergeApplicationDefinition($mergeArgs = true)
314 {
315 if (null === $this->application || (true === $this->applicationDefinitionMerged && ($this->applicationDefinitionMergedWithArgs || !$mergeArgs))) {
316 return;
317 }
318
319 $this->definition->addOptions($this->application->getDefinition()->getOptions());
320
321 if ($mergeArgs) {
322 $currentArguments = $this->definition->getArguments();
323 $this->definition->setArguments($this->application->getDefinition()->getArguments());
324 $this->definition->addArguments($currentArguments);
325 }
326
327 $this->applicationDefinitionMerged = true;
328 if ($mergeArgs) {
329 $this->applicationDefinitionMergedWithArgs = true;
330 }
331 }
332
333 /**
334 * Sets an array of argument and option instances.
335 *
336 * @param array|InputDefinition $definition An array of argument and option instances or a definition instance
337 *
338 * @return $this
339 */
340 public function setDefinition($definition)
341 {
342 if ($definition instanceof InputDefinition) {
343 $this->definition = $definition;
344 } else {
345 $this->definition->setDefinition($definition);
346 }
347
348 $this->applicationDefinitionMerged = false;
349
350 return $this;
351 }
352
353 /**
354 * Gets the InputDefinition attached to this Command.
355 *
356 * @return InputDefinition An InputDefinition instance
357 */
358 public function getDefinition()
359 {
360 return $this->definition;
361 }
362
363 /**
364 * Gets the InputDefinition to be used to create representations of this Command.
365 *
366 * Can be overridden to provide the original command representation when it would otherwise
367 * be changed by merging with the application InputDefinition.
368 *
369 * This method is not part of public API and should not be used directly.
370 *
371 * @return InputDefinition An InputDefinition instance
372 */
373 public function getNativeDefinition()
374 {
375 return $this->getDefinition();
376 }
377
378 /**
379 * Adds an argument.
380 *
381 * @param string $name The argument name
382 * @param int $mode The argument mode: InputArgument::REQUIRED or InputArgument::OPTIONAL
383 * @param string $description A description text
384 * @param mixed $default The default value (for InputArgument::OPTIONAL mode only)
385 *
386 * @return $this
387 */
388 public function addArgument($name, $mode = null, $description = '', $default = null)
389 {
390 $this->definition->addArgument(new InputArgument($name, $mode, $description, $default));
391
392 return $this;
393 }
394
395 /**
396 * Adds an option.
397 *
398 * @param string $name The option name
399 * @param string $shortcut The shortcut (can be null)
400 * @param int $mode The option mode: One of the InputOption::VALUE_* constants
401 * @param string $description A description text
402 * @param mixed $default The default value (must be null for InputOption::VALUE_NONE)
403 *
404 * @return $this
405 */
406 public function addOption($name, $shortcut = null, $mode = null, $description = '', $default = null)
407 {
408 $this->definition->addOption(new InputOption($name, $shortcut, $mode, $description, $default));
409
410 return $this;
411 }
412
413 /**
414 * Sets the name of the command.
415 *
416 * This method can set both the namespace and the name if
417 * you separate them by a colon (:)
418 *
419 * $command->setName('foo:bar');
420 *
421 * @param string $name The command name
422 *
423 * @return $this
424 *
425 * @throws InvalidArgumentException When the name is invalid
426 */
427 public function setName($name)
428 {
429 $this->validateName($name);
430
431 $this->name = $name;
432
433 return $this;
434 }
435
436 /**
437 * Sets the process title of the command.
438 *
439 * This feature should be used only when creating a long process command,
440 * like a daemon.
441 *
442 * PHP 5.5+ or the proctitle PECL library is required
443 *
444 * @param string $title The process title
445 *
446 * @return $this
447 */
448 public function setProcessTitle($title)
449 {
450 $this->processTitle = $title;
451
452 return $this;
453 }
454
455 /**
456 * Returns the command name.
457 *
458 * @return string The command name
459 */
460 public function getName()
461 {
462 return $this->name;
463 }
464
465 /**
466 * @param bool $hidden Whether or not the command should be hidden from the list of commands
467 *
468 * @return Command The current instance
469 */
470 public function setHidden($hidden)
471 {
472 $this->hidden = (bool) $hidden;
473
474 return $this;
475 }
476
477 /**
478 * @return bool Whether the command should be publicly shown or not.
479 */
480 public function isHidden()
481 {
482 return $this->hidden;
483 }
484
485 /**
486 * Sets the description for the command.
487 *
488 * @param string $description The description for the command
489 *
490 * @return $this
491 */
492 public function setDescription($description)
493 {
494 $this->description = $description;
495
496 return $this;
497 }
498
499 /**
500 * Returns the description for the command.
501 *
502 * @return string The description for the command
503 */
504 public function getDescription()
505 {
506 return $this->description;
507 }
508
509 /**
510 * Sets the help for the command.
511 *
512 * @param string $help The help for the command
513 *
514 * @return $this
515 */
516 public function setHelp($help)
517 {
518 $this->help = $help;
519
520 return $this;
521 }
522
523 /**
524 * Returns the help for the command.
525 *
526 * @return string The help for the command
527 */
528 public function getHelp()
529 {
530 return $this->help;
531 }
532
533 /**
534 * Returns the processed help for the command replacing the %command.name% and
535 * %command.full_name% patterns with the real values dynamically.
536 *
537 * @return string The processed help for the command
538 */
539 public function getProcessedHelp()
540 {
541 $name = $this->name;
542
543 $placeholders = array(
544 '%command.name%',
545 '%command.full_name%',
546 );
547 $replacements = array(
548 $name,
549 $_SERVER['PHP_SELF'].' '.$name,
550 );
551
552 return str_replace($placeholders, $replacements, $this->getHelp() ?: $this->getDescription());
553 }
554
555 /**
556 * Sets the aliases for the command.
557 *
558 * @param string[] $aliases An array of aliases for the command
559 *
560 * @return $this
561 *
562 * @throws InvalidArgumentException When an alias is invalid
563 */
564 public function setAliases($aliases)
565 {
566 if (!is_array($aliases) && !$aliases instanceof \Traversable) {
567 throw new InvalidArgumentException('$aliases must be an array or an instance of \Traversable');
568 }
569
570 foreach ($aliases as $alias) {
571 $this->validateName($alias);
572 }
573
574 $this->aliases = $aliases;
575
576 return $this;
577 }
578
579 /**
580 * Returns the aliases for the command.
581 *
582 * @return array An array of aliases for the command
583 */
584 public function getAliases()
585 {
586 return $this->aliases;
587 }
588
589 /**
590 * Returns the synopsis for the command.
591 *
592 * @param bool $short Whether to show the short version of the synopsis (with options folded) or not
593 *
594 * @return string The synopsis
595 */
596 public function getSynopsis($short = false)
597 {
598 $key = $short ? 'short' : 'long';
599
600 if (!isset($this->synopsis[$key])) {
601 $this->synopsis[$key] = trim(sprintf('%s %s', $this->name, $this->definition->getSynopsis($short)));
602 }
603
604 return $this->synopsis[$key];
605 }
606
607 /**
608 * Add a command usage example.
609 *
610 * @param string $usage The usage, it'll be prefixed with the command name
611 *
612 * @return $this
613 */
614 public function addUsage($usage)
615 {
616 if (0 !== strpos($usage, $this->name)) {
617 $usage = sprintf('%s %s', $this->name, $usage);
618 }
619
620 $this->usages[] = $usage;
621
622 return $this;
623 }
624
625 /**
626 * Returns alternative usages of the command.
627 *
628 * @return array
629 */
630 public function getUsages()
631 {
632 return $this->usages;
633 }
634
635 /**
636 * Gets a helper instance by name.
637 *
638 * @param string $name The helper name
639 *
640 * @return mixed The helper value
641 *
642 * @throws LogicException if no HelperSet is defined
643 * @throws InvalidArgumentException if the helper is not defined
644 */
645 public function getHelper($name)
646 {
647 if (null === $this->helperSet) {
648 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));
649 }
650
651 return $this->helperSet->get($name);
652 }
653
654 /**
655 * Validates a command name.
656 *
657 * It must be non-empty and parts can optionally be separated by ":".
658 *
659 * @param string $name
660 *
661 * @throws InvalidArgumentException When the name is invalid
662 */
663 private function validateName($name)
664 {
665 if (!preg_match('/^[^\:]++(\:[^\:]++)*$/', $name)) {
666 throw new InvalidArgumentException(sprintf('Command name "%s" is invalid.', $name));
667 }
668 }
669 }