Console.php 21 KB

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