BaseCommand.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 4.0.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Console;
  17. use Cake\Console\Exception\ConsoleException;
  18. use Cake\Console\Exception\StopException;
  19. use Cake\Event\EventDispatcherInterface;
  20. use Cake\Event\EventDispatcherTrait;
  21. use Cake\Utility\Inflector;
  22. /**
  23. * Base class for console commands.
  24. *
  25. * Provides hooks for common command features:
  26. *
  27. * - `initialize` Acts as a post-construct hook.
  28. * - `buildOptionParser` Build/Configure the option parser for your command.
  29. * - `execute` Execute your command with parsed Arguments and ConsoleIo
  30. *
  31. * @implements \Cake\Event\EventDispatcherInterface<\Cake\Command\Command>
  32. */
  33. abstract class BaseCommand implements CommandInterface, EventDispatcherInterface
  34. {
  35. /**
  36. * @use \Cake\Event\EventDispatcherTrait<\Cake\Command\Command>
  37. */
  38. use EventDispatcherTrait;
  39. /**
  40. * The name of this command.
  41. *
  42. * @var string
  43. */
  44. protected string $name = 'cake unknown';
  45. protected ?CommandFactoryInterface $factory = null;
  46. /**
  47. * Constructor
  48. *
  49. * @param \Cake\Console\CommandFactoryInterface $factory Command factory instance.
  50. */
  51. public function __construct(?CommandFactoryInterface $factory = null)
  52. {
  53. $this->factory = $factory;
  54. }
  55. /**
  56. * @inheritDoc
  57. */
  58. public function setName(string $name)
  59. {
  60. assert(
  61. str_contains($name, ' ') && !str_starts_with($name, ' '),
  62. "The name '{$name}' is missing a space. Names should look like `cake routes`"
  63. );
  64. $this->name = $name;
  65. return $this;
  66. }
  67. /**
  68. * Get the command name.
  69. *
  70. * @return string
  71. */
  72. public function getName(): string
  73. {
  74. return $this->name;
  75. }
  76. /**
  77. * Get the command description.
  78. *
  79. * @return string
  80. */
  81. public static function getDescription(): string
  82. {
  83. return '';
  84. }
  85. /**
  86. * Get the root command name.
  87. *
  88. * @return string
  89. */
  90. public function getRootName(): string
  91. {
  92. [$root] = explode(' ', $this->name);
  93. return $root;
  94. }
  95. /**
  96. * Get the command name.
  97. *
  98. * Returns the command name based on class name.
  99. * For e.g. for a command with class name `UpdateTableCommand` the default
  100. * name returned would be `'update_table'`.
  101. *
  102. * @return string
  103. */
  104. public static function defaultName(): string
  105. {
  106. $pos = strrpos(static::class, '\\');
  107. /** @psalm-suppress PossiblyFalseOperand */
  108. $name = substr(static::class, $pos + 1, -7);
  109. return Inflector::underscore($name);
  110. }
  111. /**
  112. * Get the option parser.
  113. *
  114. * You can override buildOptionParser() to define your options & arguments.
  115. *
  116. * @return \Cake\Console\ConsoleOptionParser
  117. * @throws \Cake\Core\Exception\CakeException When the parser is invalid
  118. */
  119. public function getOptionParser(): ConsoleOptionParser
  120. {
  121. [$root, $name] = explode(' ', $this->name, 2);
  122. $parser = new ConsoleOptionParser($name);
  123. $parser->setRootName($root);
  124. $parser->setDescription(static::getDescription());
  125. $parser = $this->buildOptionParser($parser);
  126. return $parser;
  127. }
  128. /**
  129. * Hook method for defining this command's option parser.
  130. *
  131. * @param \Cake\Console\ConsoleOptionParser $parser The parser to be defined
  132. * @return \Cake\Console\ConsoleOptionParser The built parser.
  133. */
  134. protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser
  135. {
  136. return $parser;
  137. }
  138. /**
  139. * Hook method invoked by CakePHP when a command is about to be executed.
  140. *
  141. * Override this method and implement expensive/important setup steps that
  142. * should not run on every command run. This method will be called *before*
  143. * the options and arguments are validated and processed.
  144. *
  145. * @return void
  146. */
  147. public function initialize(): void
  148. {
  149. }
  150. /**
  151. * @inheritDoc
  152. */
  153. public function run(array $argv, ConsoleIo $io): ?int
  154. {
  155. $this->initialize();
  156. $parser = $this->getOptionParser();
  157. try {
  158. [$options, $arguments] = $parser->parse($argv, $io);
  159. $args = new Arguments(
  160. $arguments,
  161. $options,
  162. $parser->argumentNames()
  163. );
  164. } catch (ConsoleException $e) {
  165. $io->err('Error: ' . $e->getMessage());
  166. return static::CODE_ERROR;
  167. }
  168. $this->setOutputLevel($args, $io);
  169. if ($args->getOption('help')) {
  170. $this->displayHelp($parser, $args, $io);
  171. return static::CODE_SUCCESS;
  172. }
  173. if ($args->getOption('quiet')) {
  174. $io->setInteractive(false);
  175. }
  176. $this->dispatchEvent('Command.beforeExecute', ['args' => $args]);
  177. /** @var int|null $result */
  178. $result = $this->execute($args, $io);
  179. $this->dispatchEvent('Command.afterExecute', ['args' => $args, 'result' => $result]);
  180. return $result;
  181. }
  182. /**
  183. * Output help content
  184. *
  185. * @param \Cake\Console\ConsoleOptionParser $parser The option parser.
  186. * @param \Cake\Console\Arguments $args The command arguments.
  187. * @param \Cake\Console\ConsoleIo $io The console io
  188. * @return void
  189. */
  190. protected function displayHelp(ConsoleOptionParser $parser, Arguments $args, ConsoleIo $io): void
  191. {
  192. $format = 'text';
  193. if ($args->getArgumentAt(0) === 'xml') {
  194. $format = 'xml';
  195. $io->setOutputAs(ConsoleOutput::RAW);
  196. }
  197. $io->out($parser->help($format));
  198. }
  199. /**
  200. * Set the output level based on the Arguments.
  201. *
  202. * @param \Cake\Console\Arguments $args The command arguments.
  203. * @param \Cake\Console\ConsoleIo $io The console io
  204. * @return void
  205. */
  206. protected function setOutputLevel(Arguments $args, ConsoleIo $io): void
  207. {
  208. $io->setLoggers(ConsoleIo::NORMAL);
  209. if ($args->getOption('quiet')) {
  210. $io->level(ConsoleIo::QUIET);
  211. $io->setLoggers(ConsoleIo::QUIET);
  212. }
  213. if ($args->getOption('verbose')) {
  214. $io->level(ConsoleIo::VERBOSE);
  215. $io->setLoggers(ConsoleIo::VERBOSE);
  216. }
  217. }
  218. /**
  219. * Implement this method with your command's logic.
  220. *
  221. * @param \Cake\Console\Arguments $args The command arguments.
  222. * @param \Cake\Console\ConsoleIo $io The console io
  223. * @return int|null|void The exit code or null for success
  224. * @phpcsSuppress SlevomatCodingStandard.TypeHints.ReturnTypeHint.MissingNativeTypeHint
  225. */
  226. abstract public function execute(Arguments $args, ConsoleIo $io);
  227. /**
  228. * Halt the current process with a StopException.
  229. *
  230. * @param int $code The exit code to use.
  231. * @throws \Cake\Console\Exception\StopException
  232. * @return never
  233. */
  234. public function abort(int $code = self::CODE_ERROR): never
  235. {
  236. throw new StopException('Command aborted', $code);
  237. }
  238. /**
  239. * Execute another command with the provided set of arguments.
  240. *
  241. * If you are using a string command name, that command's dependencies
  242. * will not be resolved with the application container. Instead you will
  243. * need to pass the command as an object with all of its dependencies.
  244. *
  245. * @param \Cake\Console\CommandInterface|string $command The command class name or command instance.
  246. * @param array $args The arguments to invoke the command with.
  247. * @param \Cake\Console\ConsoleIo|null $io The ConsoleIo instance to use for the executed command.
  248. * @return int|null The exit code or null for success of the command.
  249. */
  250. public function executeCommand(CommandInterface|string $command, array $args = [], ?ConsoleIo $io = null): ?int
  251. {
  252. if (is_string($command)) {
  253. assert(
  254. is_subclass_of($command, CommandInterface::class),
  255. sprintf('Command `%s` is not a subclass of `%s`.', $command, CommandInterface::class)
  256. );
  257. $command = $this->factory?->create($command) ?? new $command();
  258. }
  259. $io = $io ?: new ConsoleIo();
  260. try {
  261. return $command->run($args, $io);
  262. } catch (StopException $e) {
  263. return $e->getCode();
  264. }
  265. }
  266. }