Command.php 11 KB

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