Console.php 21 KB

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