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