Command.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2015 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: yunwuxin <448901948@qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace think\console;
  12. use think\Console;
  13. use think\console\input\Argument;
  14. use think\console\input\Definition;
  15. use think\console\input\Option;
  16. class Command
  17. {
  18. /** @var Console */
  19. private $console;
  20. private $name;
  21. private $aliases = [];
  22. private $definition;
  23. private $help;
  24. private $description;
  25. private $ignoreValidationErrors = false;
  26. private $consoleDefinitionMerged = false;
  27. private $consoleDefinitionMergedWithArgs = false;
  28. private $code;
  29. private $synopsis = [];
  30. private $usages = [];
  31. /** @var Input */
  32. protected $input;
  33. /** @var Output */
  34. protected $output;
  35. /**
  36. * 构造方法
  37. * @param string|null $name 命令名称,如果没有设置则比如在 configure() 里设置
  38. * @throws \LogicException
  39. * @api
  40. */
  41. public function __construct($name = null)
  42. {
  43. $this->definition = new Definition();
  44. if (null !== $name) {
  45. $this->setName($name);
  46. }
  47. $this->configure();
  48. if (!$this->name) {
  49. throw new \LogicException(sprintf('The command defined in "%s" cannot have an empty name.', get_class($this)));
  50. }
  51. }
  52. /**
  53. * 忽略验证错误
  54. */
  55. public function ignoreValidationErrors()
  56. {
  57. $this->ignoreValidationErrors = true;
  58. }
  59. /**
  60. * 设置控制台
  61. * @param Console $console
  62. */
  63. public function setConsole(Console $console = null)
  64. {
  65. $this->console = $console;
  66. }
  67. /**
  68. * 获取控制台
  69. * @return Console
  70. * @api
  71. */
  72. public function getConsole()
  73. {
  74. return $this->console;
  75. }
  76. /**
  77. * 是否有效
  78. * @return bool
  79. */
  80. public function isEnabled()
  81. {
  82. return true;
  83. }
  84. /**
  85. * 配置指令
  86. */
  87. protected function configure()
  88. {
  89. }
  90. /**
  91. * 执行指令
  92. * @param Input $input
  93. * @param Output $output
  94. * @return null|int
  95. * @throws \LogicException
  96. * @see setCode()
  97. */
  98. protected function execute(Input $input, Output $output)
  99. {
  100. throw new \LogicException('You must override the execute() method in the concrete command class.');
  101. }
  102. /**
  103. * 用户验证
  104. * @param Input $input
  105. * @param Output $output
  106. */
  107. protected function interact(Input $input, Output $output)
  108. {
  109. }
  110. /**
  111. * 初始化
  112. * @param Input $input An InputInterface instance
  113. * @param Output $output An OutputInterface instance
  114. */
  115. protected function initialize(Input $input, Output $output)
  116. {
  117. }
  118. /**
  119. * 执行
  120. * @param Input $input
  121. * @param Output $output
  122. * @return int
  123. * @throws \Exception
  124. * @see setCode()
  125. * @see execute()
  126. */
  127. public function run(Input $input, Output $output)
  128. {
  129. $this->input = $input;
  130. $this->output = $output;
  131. $this->getSynopsis(true);
  132. $this->getSynopsis(false);
  133. $this->mergeConsoleDefinition();
  134. try {
  135. $input->bind($this->definition);
  136. } catch (\Exception $e) {
  137. if (!$this->ignoreValidationErrors) {
  138. throw $e;
  139. }
  140. }
  141. $this->initialize($input, $output);
  142. if ($input->isInteractive()) {
  143. $this->interact($input, $output);
  144. }
  145. $input->validate();
  146. if ($this->code) {
  147. $statusCode = call_user_func($this->code, $input, $output);
  148. } else {
  149. $statusCode = $this->execute($input, $output);
  150. }
  151. return is_numeric($statusCode) ? (int) $statusCode : 0;
  152. }
  153. /**
  154. * 设置执行代码
  155. * @param callable $code callable(InputInterface $input, OutputInterface $output)
  156. * @return Command
  157. * @throws \InvalidArgumentException
  158. * @see execute()
  159. */
  160. public function setCode(callable $code)
  161. {
  162. if (!is_callable($code)) {
  163. throw new \InvalidArgumentException('Invalid callable provided to Command::setCode.');
  164. }
  165. if (PHP_VERSION_ID >= 50400 && $code instanceof \Closure) {
  166. $r = new \ReflectionFunction($code);
  167. if (null === $r->getClosureThis()) {
  168. $code = \Closure::bind($code, $this);
  169. }
  170. }
  171. $this->code = $code;
  172. return $this;
  173. }
  174. /**
  175. * 合并参数定义
  176. * @param bool $mergeArgs
  177. */
  178. public function mergeConsoleDefinition($mergeArgs = true)
  179. {
  180. if (null === $this->console
  181. || (true === $this->consoleDefinitionMerged
  182. && ($this->consoleDefinitionMergedWithArgs || !$mergeArgs))
  183. ) {
  184. return;
  185. }
  186. if ($mergeArgs) {
  187. $currentArguments = $this->definition->getArguments();
  188. $this->definition->setArguments($this->console->getDefinition()->getArguments());
  189. $this->definition->addArguments($currentArguments);
  190. }
  191. $this->definition->addOptions($this->console->getDefinition()->getOptions());
  192. $this->consoleDefinitionMerged = true;
  193. if ($mergeArgs) {
  194. $this->consoleDefinitionMergedWithArgs = true;
  195. }
  196. }
  197. /**
  198. * 设置参数定义
  199. * @param array|Definition $definition
  200. * @return Command
  201. * @api
  202. */
  203. public function setDefinition($definition)
  204. {
  205. if ($definition instanceof Definition) {
  206. $this->definition = $definition;
  207. } else {
  208. $this->definition->setDefinition($definition);
  209. }
  210. $this->consoleDefinitionMerged = false;
  211. return $this;
  212. }
  213. /**
  214. * 获取参数定义
  215. * @return Definition
  216. * @api
  217. */
  218. public function getDefinition()
  219. {
  220. return $this->definition;
  221. }
  222. /**
  223. * 获取当前指令的参数定义
  224. * @return Definition
  225. */
  226. public function getNativeDefinition()
  227. {
  228. return $this->getDefinition();
  229. }
  230. /**
  231. * 添加参数
  232. * @param string $name 名称
  233. * @param int $mode 类型
  234. * @param string $description 描述
  235. * @param mixed $default 默认值
  236. * @return Command
  237. */
  238. public function addArgument($name, $mode = null, $description = '', $default = null)
  239. {
  240. $this->definition->addArgument(new Argument($name, $mode, $description, $default));
  241. return $this;
  242. }
  243. /**
  244. * 添加选项
  245. * @param string $name 选项名称
  246. * @param string $shortcut 别名
  247. * @param int $mode 类型
  248. * @param string $description 描述
  249. * @param mixed $default 默认值
  250. * @return Command
  251. */
  252. public function addOption($name, $shortcut = null, $mode = null, $description = '', $default = null)
  253. {
  254. $this->definition->addOption(new Option($name, $shortcut, $mode, $description, $default));
  255. return $this;
  256. }
  257. /**
  258. * 设置指令名称
  259. * @param string $name
  260. * @return Command
  261. * @throws \InvalidArgumentException
  262. */
  263. public function setName($name)
  264. {
  265. $this->validateName($name);
  266. $this->name = $name;
  267. return $this;
  268. }
  269. /**
  270. * 获取指令名称
  271. * @return string
  272. */
  273. public function getName()
  274. {
  275. return $this->name;
  276. }
  277. /**
  278. * 设置描述
  279. * @param string $description
  280. * @return Command
  281. */
  282. public function setDescription($description)
  283. {
  284. $this->description = $description;
  285. return $this;
  286. }
  287. /**
  288. * 获取描述
  289. * @return string
  290. */
  291. public function getDescription()
  292. {
  293. return $this->description;
  294. }
  295. /**
  296. * 设置帮助信息
  297. * @param string $help
  298. * @return Command
  299. */
  300. public function setHelp($help)
  301. {
  302. $this->help = $help;
  303. return $this;
  304. }
  305. /**
  306. * 获取帮助信息
  307. * @return string
  308. */
  309. public function getHelp()
  310. {
  311. return $this->help;
  312. }
  313. /**
  314. * 描述信息
  315. * @return string
  316. */
  317. public function getProcessedHelp()
  318. {
  319. $name = $this->name;
  320. $placeholders = [
  321. '%command.name%',
  322. '%command.full_name%',
  323. ];
  324. $replacements = [
  325. $name,
  326. $_SERVER['PHP_SELF'] . ' ' . $name,
  327. ];
  328. return str_replace($placeholders, $replacements, $this->getHelp());
  329. }
  330. /**
  331. * 设置别名
  332. * @param string[] $aliases
  333. * @return Command
  334. * @throws \InvalidArgumentException
  335. */
  336. public function setAliases($aliases)
  337. {
  338. if (!is_array($aliases) && !$aliases instanceof \Traversable) {
  339. throw new \InvalidArgumentException('$aliases must be an array or an instance of \Traversable');
  340. }
  341. foreach ($aliases as $alias) {
  342. $this->validateName($alias);
  343. }
  344. $this->aliases = $aliases;
  345. return $this;
  346. }
  347. /**
  348. * 获取别名
  349. * @return array
  350. */
  351. public function getAliases()
  352. {
  353. return $this->aliases;
  354. }
  355. /**
  356. * 获取简介
  357. * @param bool $short 是否简单的
  358. * @return string
  359. */
  360. public function getSynopsis($short = false)
  361. {
  362. $key = $short ? 'short' : 'long';
  363. if (!isset($this->synopsis[$key])) {
  364. $this->synopsis[$key] = trim(sprintf('%s %s', $this->name, $this->definition->getSynopsis($short)));
  365. }
  366. return $this->synopsis[$key];
  367. }
  368. /**
  369. * 添加用法介绍
  370. * @param string $usage
  371. * @return $this
  372. */
  373. public function addUsage($usage)
  374. {
  375. if (0 !== strpos($usage, $this->name)) {
  376. $usage = sprintf('%s %s', $this->name, $usage);
  377. }
  378. $this->usages[] = $usage;
  379. return $this;
  380. }
  381. /**
  382. * 获取用法介绍
  383. * @return array
  384. */
  385. public function getUsages()
  386. {
  387. return $this->usages;
  388. }
  389. /**
  390. * 验证指令名称
  391. * @param string $name
  392. * @throws \InvalidArgumentException
  393. */
  394. private function validateName($name)
  395. {
  396. if (!preg_match('/^[^\:]++(\:[^\:]++)*$/', $name)) {
  397. throw new \InvalidArgumentException(sprintf('Command name "%s" is invalid.', $name));
  398. }
  399. }
  400. }