Console.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | TopThink [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2015 http://www.topthink.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Author: zhangyajun <448901948@qq.com>
  8. // +----------------------------------------------------------------------
  9. declare (strict_types = 1);
  10. namespace think;
  11. use Closure;
  12. use InvalidArgumentException;
  13. use LogicException;
  14. use think\console\Command;
  15. use think\console\command\Clear;
  16. use think\console\command\Help;
  17. use think\console\command\Help as HelpCommand;
  18. use think\console\command\Lists;
  19. use think\console\command\make\Command as MakeCommand;
  20. use think\console\command\make\Controller;
  21. use think\console\command\make\Event;
  22. use think\console\command\make\Listener;
  23. use think\console\command\make\Middleware;
  24. use think\console\command\make\Model;
  25. use think\console\command\make\Service;
  26. use think\console\command\make\Subscribe;
  27. use think\console\command\make\Validate;
  28. use think\console\command\optimize\Route;
  29. use think\console\command\optimize\Schema;
  30. use think\console\command\RouteList;
  31. use think\console\command\RunServer;
  32. use think\console\command\ServiceDiscover;
  33. use think\console\command\VendorPublish;
  34. use think\console\command\Version;
  35. use think\console\Input;
  36. use think\console\input\Argument as InputArgument;
  37. use think\console\input\Definition as InputDefinition;
  38. use think\console\input\Option as InputOption;
  39. use think\console\Output;
  40. use think\console\output\driver\Buffer;
  41. /**
  42. * 控制台应用管理类
  43. */
  44. class Console
  45. {
  46. protected $app;
  47. /** @var Command[] */
  48. protected $commands = [];
  49. protected $wantHelps = false;
  50. protected $catchExceptions = true;
  51. protected $autoExit = true;
  52. protected $definition;
  53. protected $defaultCommand = 'list';
  54. protected $defaultCommands = [
  55. 'help' => Help::class,
  56. 'list' => Lists::class,
  57. 'clear' => Clear::class,
  58. 'make:command' => MakeCommand::class,
  59. 'make:controller' => Controller::class,
  60. 'make:model' => Model::class,
  61. 'make:middleware' => Middleware::class,
  62. 'make:validate' => Validate::class,
  63. 'make:event' => Event::class,
  64. 'make:listener' => Listener::class,
  65. 'make:service' => Service::class,
  66. 'make:subscribe' => Subscribe::class,
  67. 'optimize:route' => Route::class,
  68. 'optimize:schema' => Schema::class,
  69. 'run' => RunServer::class,
  70. 'version' => Version::class,
  71. 'route:list' => RouteList::class,
  72. 'service:discover' => ServiceDiscover::class,
  73. 'vendor:publish' => VendorPublish::class,
  74. ];
  75. /**
  76. * 启动器
  77. * @var array
  78. */
  79. protected static $startCallbacks = [];
  80. public function __construct(App $app)
  81. {
  82. $this->app = $app;
  83. if (!$this->app->initialized()) {
  84. $this->app->initialize();
  85. }
  86. $this->definition = $this->getDefaultInputDefinition();
  87. //加载指令
  88. $this->loadCommands();
  89. $this->start();
  90. }
  91. /**
  92. * 添加初始化器
  93. * @param Closure $callback
  94. */
  95. public static function starting(Closure $callback): void
  96. {
  97. static::$startCallbacks[] = $callback;
  98. }
  99. /**
  100. * 清空启动器
  101. */
  102. public static function flushStartCallbacks(): void
  103. {
  104. static::$startCallbacks = [];
  105. }
  106. /**
  107. * 设置执行用户
  108. * @param $user
  109. */
  110. public static function setUser(string $user): void
  111. {
  112. if (extension_loaded('posix')) {
  113. $user = posix_getpwnam($user);
  114. if (!empty($user)) {
  115. posix_setgid($user['gid']);
  116. posix_setuid($user['uid']);
  117. }
  118. }
  119. }
  120. /**
  121. * 启动
  122. */
  123. protected function start(): void
  124. {
  125. foreach (static::$startCallbacks as $callback) {
  126. $callback($this);
  127. }
  128. }
  129. /**
  130. * 加载指令
  131. * @access protected
  132. */
  133. protected function loadCommands(): void
  134. {
  135. $commands = $this->app->config->get('console.commands', []);
  136. $commands = array_merge($this->defaultCommands, $commands);
  137. $this->addCommands($commands);
  138. }
  139. /**
  140. * @access public
  141. * @param string $command
  142. * @param array $parameters
  143. * @param string $driver
  144. * @return Output|Buffer
  145. */
  146. public function call(string $command, array $parameters = [], string $driver = 'buffer')
  147. {
  148. array_unshift($parameters, $command);
  149. $input = new Input($parameters);
  150. $output = new Output($driver);
  151. $this->setCatchExceptions(false);
  152. $this->find($command)->run($input, $output);
  153. return $output;
  154. }
  155. /**
  156. * 执行当前的指令
  157. * @access public
  158. * @return int
  159. * @throws \Exception
  160. * @api
  161. */
  162. public function run()
  163. {
  164. $input = new Input();
  165. $output = new Output();
  166. $this->configureIO($input, $output);
  167. try {
  168. $exitCode = $this->doRun($input, $output);
  169. } catch (\Exception $e) {
  170. if (!$this->catchExceptions) {
  171. throw $e;
  172. }
  173. $output->renderException($e);
  174. $exitCode = $e->getCode();
  175. if (is_numeric($exitCode)) {
  176. $exitCode = (int) $exitCode;
  177. if (0 === $exitCode) {
  178. $exitCode = 1;
  179. }
  180. } else {
  181. $exitCode = 1;
  182. }
  183. }
  184. if ($this->autoExit) {
  185. if ($exitCode > 255) {
  186. $exitCode = 255;
  187. }
  188. exit($exitCode);
  189. }
  190. return $exitCode;
  191. }
  192. /**
  193. * 执行指令
  194. * @access public
  195. * @param Input $input
  196. * @param Output $output
  197. * @return int
  198. */
  199. public function doRun(Input $input, Output $output)
  200. {
  201. if (true === $input->hasParameterOption(['--version', '-V'])) {
  202. $output->writeln($this->getLongVersion());
  203. return 0;
  204. }
  205. $name = $this->getCommandName($input);
  206. if (true === $input->hasParameterOption(['--help', '-h'])) {
  207. if (!$name) {
  208. $name = 'help';
  209. $input = new Input(['help']);
  210. } else {
  211. $this->wantHelps = true;
  212. }
  213. }
  214. if (!$name) {
  215. $name = $this->defaultCommand;
  216. $input = new Input([$this->defaultCommand]);
  217. }
  218. $command = $this->find($name);
  219. return $this->doRunCommand($command, $input, $output);
  220. }
  221. /**
  222. * 设置输入参数定义
  223. * @access public
  224. * @param InputDefinition $definition
  225. */
  226. public function setDefinition(InputDefinition $definition): void
  227. {
  228. $this->definition = $definition;
  229. }
  230. /**
  231. * 获取输入参数定义
  232. * @access public
  233. * @return InputDefinition The InputDefinition instance
  234. */
  235. public function getDefinition(): InputDefinition
  236. {
  237. return $this->definition;
  238. }
  239. /**
  240. * Gets the help message.
  241. * @access public
  242. * @return string A help message.
  243. */
  244. public function getHelp(): string
  245. {
  246. return $this->getLongVersion();
  247. }
  248. /**
  249. * 是否捕获异常
  250. * @access public
  251. * @param bool $boolean
  252. * @api
  253. */
  254. public function setCatchExceptions(bool $boolean): void
  255. {
  256. $this->catchExceptions = $boolean;
  257. }
  258. /**
  259. * 是否自动退出
  260. * @access public
  261. * @param bool $boolean
  262. * @api
  263. */
  264. public function setAutoExit(bool $boolean): void
  265. {
  266. $this->autoExit = $boolean;
  267. }
  268. /**
  269. * 获取完整的版本号
  270. * @access public
  271. * @return string
  272. */
  273. public function getLongVersion(): string
  274. {
  275. if ($this->app->version()) {
  276. return sprintf('version <comment>%s</comment>', $this->app->version());
  277. }
  278. return '<info>Console Tool</info>';
  279. }
  280. /**
  281. * 添加指令集
  282. * @access public
  283. * @param array $commands
  284. */
  285. public function addCommands(array $commands): void
  286. {
  287. foreach ($commands as $key => $command) {
  288. if (is_subclass_of($command, Command::class)) {
  289. // 注册指令
  290. $this->addCommand($command, is_numeric($key) ? '' : $key);
  291. }
  292. }
  293. }
  294. /**
  295. * 添加一个指令
  296. * @access public
  297. * @param string|Command $command 指令对象或者指令类名
  298. * @param string $name 指令名 留空则自动获取
  299. * @return Command|void
  300. */
  301. public function addCommand($command, string $name = '')
  302. {
  303. if ($name) {
  304. $this->commands[$name] = $command;
  305. return;
  306. }
  307. if (is_string($command)) {
  308. $command = $this->app->invokeClass($command);
  309. }
  310. $command->setConsole($this);
  311. if (!$command->isEnabled()) {
  312. $command->setConsole(null);
  313. return;
  314. }
  315. $command->setApp($this->app);
  316. if (null === $command->getDefinition()) {
  317. throw new LogicException(sprintf('Command class "%s" is not correctly initialized. You probably forgot to call the parent constructor.', get_class($command)));
  318. }
  319. $this->commands[$command->getName()] = $command;
  320. foreach ($command->getAliases() as $alias) {
  321. $this->commands[$alias] = $command;
  322. }
  323. return $command;
  324. }
  325. /**
  326. * 获取指令
  327. * @access public
  328. * @param string $name 指令名称
  329. * @return Command
  330. * @throws InvalidArgumentException
  331. */
  332. public function getCommand(string $name): Command
  333. {
  334. if (!isset($this->commands[$name])) {
  335. throw new InvalidArgumentException(sprintf('The command "%s" does not exist.', $name));
  336. }
  337. $command = $this->commands[$name];
  338. if (is_string($command)) {
  339. $command = $this->app->invokeClass($command);
  340. /** @var Command $command */
  341. $command->setConsole($this);
  342. $command->setApp($this->app);
  343. }
  344. if ($this->wantHelps) {
  345. $this->wantHelps = false;
  346. /** @var HelpCommand $helpCommand */
  347. $helpCommand = $this->getCommand('help');
  348. $helpCommand->setCommand($command);
  349. return $helpCommand;
  350. }
  351. return $command;
  352. }
  353. /**
  354. * 某个指令是否存在
  355. * @access public
  356. * @param string $name 指令名称
  357. * @return bool
  358. */
  359. public function hasCommand(string $name): bool
  360. {
  361. return isset($this->commands[$name]);
  362. }
  363. /**
  364. * 获取所有的命名空间
  365. * @access public
  366. * @return array
  367. */
  368. public function getNamespaces(): array
  369. {
  370. $namespaces = [];
  371. foreach ($this->commands as $key => $command) {
  372. if (is_string($command)) {
  373. $namespaces = array_merge($namespaces, $this->extractAllNamespaces($key));
  374. } else {
  375. $namespaces = array_merge($namespaces, $this->extractAllNamespaces($command->getName()));
  376. foreach ($command->getAliases() as $alias) {
  377. $namespaces = array_merge($namespaces, $this->extractAllNamespaces($alias));
  378. }
  379. }
  380. }
  381. return array_values(array_unique(array_filter($namespaces)));
  382. }
  383. /**
  384. * 查找注册命名空间中的名称或缩写。
  385. * @access public
  386. * @param string $namespace
  387. * @return string
  388. * @throws InvalidArgumentException
  389. */
  390. public function findNamespace(string $namespace): string
  391. {
  392. $allNamespaces = $this->getNamespaces();
  393. $expr = preg_replace_callback('{([^:]+|)}', function ($matches) {
  394. return preg_quote($matches[1]) . '[^:]*';
  395. }, $namespace);
  396. $namespaces = preg_grep('{^' . $expr . '}', $allNamespaces);
  397. if (empty($namespaces)) {
  398. $message = sprintf('There are no commands defined in the "%s" namespace.', $namespace);
  399. if ($alternatives = $this->findAlternatives($namespace, $allNamespaces)) {
  400. if (1 == count($alternatives)) {
  401. $message .= "\n\nDid you mean this?\n ";
  402. } else {
  403. $message .= "\n\nDid you mean one of these?\n ";
  404. }
  405. $message .= implode("\n ", $alternatives);
  406. }
  407. throw new InvalidArgumentException($message);
  408. }
  409. $exact = in_array($namespace, $namespaces, true);
  410. if (count($namespaces) > 1 && !$exact) {
  411. throw new InvalidArgumentException(sprintf('The namespace "%s" is ambiguous (%s).', $namespace, $this->getAbbreviationSuggestions(array_values($namespaces))));
  412. }
  413. return $exact ? $namespace : reset($namespaces);
  414. }
  415. /**
  416. * 查找指令
  417. * @access public
  418. * @param string $name 名称或者别名
  419. * @return Command
  420. * @throws InvalidArgumentException
  421. */
  422. public function find(string $name): Command
  423. {
  424. $allCommands = array_keys($this->commands);
  425. $expr = preg_replace_callback('{([^:]+|)}', function ($matches) {
  426. return preg_quote($matches[1]) . '[^:]*';
  427. }, $name);
  428. $commands = preg_grep('{^' . $expr . '}', $allCommands);
  429. if (empty($commands) || count(preg_grep('{^' . $expr . '$}', $commands)) < 1) {
  430. if (false !== $pos = strrpos($name, ':')) {
  431. $this->findNamespace(substr($name, 0, $pos));
  432. }
  433. $message = sprintf('Command "%s" is not defined.', $name);
  434. if ($alternatives = $this->findAlternatives($name, $allCommands)) {
  435. if (1 == count($alternatives)) {
  436. $message .= "\n\nDid you mean this?\n ";
  437. } else {
  438. $message .= "\n\nDid you mean one of these?\n ";
  439. }
  440. $message .= implode("\n ", $alternatives);
  441. }
  442. throw new InvalidArgumentException($message);
  443. }
  444. $exact = in_array($name, $commands, true);
  445. if (count($commands) > 1 && !$exact) {
  446. $suggestions = $this->getAbbreviationSuggestions(array_values($commands));
  447. throw new InvalidArgumentException(sprintf('Command "%s" is ambiguous (%s).', $name, $suggestions));
  448. }
  449. return $this->getCommand($exact ? $name : reset($commands));
  450. }
  451. /**
  452. * 获取所有的指令
  453. * @access public
  454. * @param string $namespace 命名空间
  455. * @return Command[]
  456. * @api
  457. */
  458. public function all(string $namespace = null): array
  459. {
  460. if (null === $namespace) {
  461. return $this->commands;
  462. }
  463. $commands = [];
  464. foreach ($this->commands as $name => $command) {
  465. if ($this->extractNamespace($name, substr_count($namespace, ':') + 1) === $namespace) {
  466. $commands[$name] = $command;
  467. }
  468. }
  469. return $commands;
  470. }
  471. /**
  472. * 配置基于用户的参数和选项的输入和输出实例。
  473. * @access protected
  474. * @param Input $input 输入实例
  475. * @param Output $output 输出实例
  476. */
  477. protected function configureIO(Input $input, Output $output): void
  478. {
  479. if (true === $input->hasParameterOption(['--ansi'])) {
  480. $output->setDecorated(true);
  481. } elseif (true === $input->hasParameterOption(['--no-ansi'])) {
  482. $output->setDecorated(false);
  483. }
  484. if (true === $input->hasParameterOption(['--no-interaction', '-n'])) {
  485. $input->setInteractive(false);
  486. }
  487. if (true === $input->hasParameterOption(['--quiet', '-q'])) {
  488. $output->setVerbosity(Output::VERBOSITY_QUIET);
  489. } elseif ($input->hasParameterOption('-vvv') || $input->hasParameterOption('--verbose=3') || $input->getParameterOption('--verbose') === 3) {
  490. $output->setVerbosity(Output::VERBOSITY_DEBUG);
  491. } elseif ($input->hasParameterOption('-vv') || $input->hasParameterOption('--verbose=2') || $input->getParameterOption('--verbose') === 2) {
  492. $output->setVerbosity(Output::VERBOSITY_VERY_VERBOSE);
  493. } elseif ($input->hasParameterOption('-v') || $input->hasParameterOption('--verbose=1') || $input->hasParameterOption('--verbose') || $input->getParameterOption('--verbose')) {
  494. $output->setVerbosity(Output::VERBOSITY_VERBOSE);
  495. }
  496. }
  497. /**
  498. * 执行指令
  499. * @access protected
  500. * @param Command $command 指令实例
  501. * @param Input $input 输入实例
  502. * @param Output $output 输出实例
  503. * @return int
  504. * @throws \Exception
  505. */
  506. protected function doRunCommand(Command $command, Input $input, Output $output)
  507. {
  508. return $command->run($input, $output);
  509. }
  510. /**
  511. * 获取指令的基础名称
  512. * @access protected
  513. * @param Input $input
  514. * @return string
  515. */
  516. protected function getCommandName(Input $input): string
  517. {
  518. return $input->getFirstArgument() ?: '';
  519. }
  520. /**
  521. * 获取默认输入定义
  522. * @access protected
  523. * @return InputDefinition
  524. */
  525. protected function getDefaultInputDefinition(): InputDefinition
  526. {
  527. return new InputDefinition([
  528. new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'),
  529. new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display this help message'),
  530. new InputOption('--version', '-V', InputOption::VALUE_NONE, 'Display this console version'),
  531. new InputOption('--quiet', '-q', InputOption::VALUE_NONE, 'Do not output any message'),
  532. new InputOption('--verbose', '-v|vv|vvv', InputOption::VALUE_NONE, 'Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug'),
  533. new InputOption('--ansi', '', InputOption::VALUE_NONE, 'Force ANSI output'),
  534. new InputOption('--no-ansi', '', InputOption::VALUE_NONE, 'Disable ANSI output'),
  535. new InputOption('--no-interaction', '-n', InputOption::VALUE_NONE, 'Do not ask any interactive question'),
  536. ]);
  537. }
  538. /**
  539. * 获取可能的建议
  540. * @access private
  541. * @param array $abbrevs
  542. * @return string
  543. */
  544. private function getAbbreviationSuggestions(array $abbrevs): string
  545. {
  546. return sprintf('%s, %s%s', $abbrevs[0], $abbrevs[1], count($abbrevs) > 2 ? sprintf(' and %d more', count($abbrevs) - 2) : '');
  547. }
  548. /**
  549. * 返回命名空间部分
  550. * @access public
  551. * @param string $name 指令
  552. * @param int $limit 部分的命名空间的最大数量
  553. * @return string
  554. */
  555. public function extractNamespace(string $name, int $limit = 0): string
  556. {
  557. $parts = explode(':', $name);
  558. array_pop($parts);
  559. return implode(':', 0 === $limit ? $parts : array_slice($parts, 0, $limit));
  560. }
  561. /**
  562. * 查找可替代的建议
  563. * @access private
  564. * @param string $name
  565. * @param array|\Traversable $collection
  566. * @return array
  567. */
  568. private function findAlternatives(string $name, $collection): array
  569. {
  570. $threshold = 1e3;
  571. $alternatives = [];
  572. $collectionParts = [];
  573. foreach ($collection as $item) {
  574. $collectionParts[$item] = explode(':', $item);
  575. }
  576. foreach (explode(':', $name) as $i => $subname) {
  577. foreach ($collectionParts as $collectionName => $parts) {
  578. $exists = isset($alternatives[$collectionName]);
  579. if (!isset($parts[$i]) && $exists) {
  580. $alternatives[$collectionName] += $threshold;
  581. continue;
  582. } elseif (!isset($parts[$i])) {
  583. continue;
  584. }
  585. $lev = levenshtein($subname, $parts[$i]);
  586. if ($lev <= strlen($subname) / 3 || '' !== $subname && false !== strpos($parts[$i], $subname)) {
  587. $alternatives[$collectionName] = $exists ? $alternatives[$collectionName] + $lev : $lev;
  588. } elseif ($exists) {
  589. $alternatives[$collectionName] += $threshold;
  590. }
  591. }
  592. }
  593. foreach ($collection as $item) {
  594. $lev = levenshtein($name, $item);
  595. if ($lev <= strlen($name) / 3 || false !== strpos($item, $name)) {
  596. $alternatives[$item] = isset($alternatives[$item]) ? $alternatives[$item] - $lev : $lev;
  597. }
  598. }
  599. $alternatives = array_filter($alternatives, function ($lev) use ($threshold) {
  600. return $lev < 2 * $threshold;
  601. });
  602. asort($alternatives);
  603. return array_keys($alternatives);
  604. }
  605. /**
  606. * 返回所有的命名空间
  607. * @access private
  608. * @param string $name
  609. * @return array
  610. */
  611. private function extractAllNamespaces(string $name): array
  612. {
  613. $parts = explode(':', $name, -1);
  614. $namespaces = [];
  615. foreach ($parts as $part) {
  616. if (count($namespaces)) {
  617. $namespaces[] = end($namespaces) . ':' . $part;
  618. } else {
  619. $namespaces[] = $part;
  620. }
  621. }
  622. return $namespaces;
  623. }
  624. }