forked from inhere/php-console
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbstractCommand.php
More file actions
471 lines (394 loc) · 11.7 KB
/
Copy pathAbstractCommand.php
File metadata and controls
471 lines (394 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
<?php
/**
* Created by PhpStorm.
* User: inhere
* Date: 2017-03-17
* Time: 11:40
*/
namespace Inhere\Console\Base;
use Inhere\Console\Application;
use Inhere\Console\IO\Input;
use Inhere\Console\IO\InputDefinition;
use Inhere\Console\IO\Output;
use Inhere\Console\Traits\InputOutputTrait;
use Inhere\Console\Traits\UserInteractTrait;
use Inhere\Console\Utils\Annotation;
/**
* Class AbstractCommand
* @package Inhere\Console
*/
abstract class AbstractCommand implements CommandInterface
{
use InputOutputTrait, UserInteractTrait;
// name -> {$name}
const ANNOTATION_VAR = '{%s}'; // '{$%s}';
/**
* command name e.g 'test' 'test:one'
* @var string
*/
protected static $name = '';
/**
* command/controller description message
* please use the property setting current controller/command description
* @var string
*/
protected static $description = '';
/**
* Allow display message tags in the command annotation
* @var array
*/
protected static $annotationTags = [
// tag name => multi line align
'description' => false,
'usage' => false,
'arguments' => true,
'options' => true,
'example' => true,
];
/** @var Application */
protected $app;
/** @var InputDefinition|null */
private $definition;
/** @var string */
private $processTitle;
/**
* Command constructor.
* @param Input $input
* @param Output $output
* @param InputDefinition|null $definition
*/
public function __construct(Input $input, Output $output, InputDefinition $definition = null)
{
$this->input = $input;
$this->output = $output;
if ($definition) {
$this->definition = $definition;
}
$this->init();
}
protected function init()
{
}
/**
* Configure input definition for command
* @return InputDefinition|null
*/
protected function configure()
{
return null;
}
/**
* @return InputDefinition
*/
protected function createDefinition()
{
if (!$this->definition) {
$this->definition = new InputDefinition();
}
return $this->definition;
}
/**
* 为命令注解提供可解析解析变量. 可以在命令的注释中使用
* @return array
*/
public function annotationVars()
{
// e.g: `more info see {name}/index`
return [
'script' => $this->input->getScript(),
'command' => $this->input->getCommand(),
'fullCommand' => $this->input->getScript() . ' ' . $this->input->getCommand(),
'name' => self::getName(),
];
}
/**************************************************************************
* running a command
**************************************************************************/
/**
* run command
* @param string $command
* @return int
*/
public function run($command = '')
{
// load input definition configure
$this->configure();
if ($this->input->sameOpt(['h', 'help'])) {
return $this->showHelp();
}
if (true !== $this->prepare()) {
return -1;
}
if (true !== $this->beforeExecute()) {
return -1;
}
$status = $this->execute($this->input, $this->output);
$this->afterExecute();
return $status;
}
/**
* before command execute
* @return boolean It MUST return TRUE to continue execute.
*/
protected function beforeExecute()
{
return true;
}
/**
* do execute
* @param Input $input
* @param Output $output
* @return int
*/
abstract protected function execute($input, $output);
/**
* after command execute
*/
protected function afterExecute()
{
}
/**
* display help information
* @return bool
*/
protected function showHelp()
{
// 创建了 InputDefinition , 则使用它的信息。
// 不会再解析和使用命令的注释。
if ($def = $this->getDefinition()) {
$this->output->mList($def->getSynopsis());
return true;
}
return false;
}
/**
* prepare run
*/
protected function prepare()
{
if ($this->processTitle) {
if (\function_exists('cli_set_process_title')) {
if (false === @cli_set_process_title($this->processTitle)) {
if ('Darwin' === PHP_OS) {
$this->output->writeln('<comment>Running "cli_get_process_title" as an unprivileged user is not supported on MacOS.</comment>');
} else {
$error = error_get_last();
trigger_error($error['message'], E_USER_WARNING);
}
}
} elseif (\function_exists('setproctitle')) {
setproctitle($this->processTitle);
// } elseif (isDebug) {
// $output->writeln('<comment>Install the proctitle PECL to be able to change the process title.</comment>');
}
}
// do validate input arg and opt
return $this->validateInput();
}
/**
* validate input arguments and options
* @return bool
*/
public function validateInput()
{
if (!$def = $this->definition) {
return true;
}
$in = $this->input;
$givenArgs = $errArgs = [];
foreach ($in->getArgs() as $key => $value) {
if (\is_int($key)) {
$givenArgs[$key] = $value;
} else {
$errArgs[] = $key;
}
}
if (\count($errArgs) > 0) {
$this->output->liteError(sprintf('Unknown arguments (error: "%s").', implode(', ', $errArgs)));
return false;
}
$defArgs = $def->getArguments();
$missingArgs = array_filter(array_keys($defArgs), function ($name, $key) use ($def, $givenArgs) {
return !array_key_exists($key, $givenArgs) && $def->argumentIsRequired($name);
}, ARRAY_FILTER_USE_BOTH);
if (\count($missingArgs) > 0) {
$this->output->liteError(sprintf('Not enough arguments (missing: "%s").', implode(', ', $missingArgs)));
return false;
}
$index = 0;
$args = [];
foreach ($defArgs as $name => $conf) {
$args[$name] = $givenArgs[$index] ?? $conf['default'];
$index++;
}
$in->setArgs($args);
// check options
$opts = $missingOpts = [];
//$givenLOpts = $in->getLongOpts();
$defOpts = $def->getOptions();
foreach ($defOpts as $name => $conf) {
if (!$in->hasLOpt($name)) {
if (($srt = $conf['shortcut']) && $in->hasSOpt($srt)) {
$opts[$name] = $in->sOpt($srt);
} elseif ($conf['required']) {
$missingOpts[] = "--{$name}" . ($srt ? "|-{$srt}" : '');
}
}
}
if (\count($missingOpts) > 0) {
$this->output->liteError(sprintf('Not enough options parameters (missing: "%s").', implode(', ', $missingOpts)));
return false;
}
if ($opts) {
$in->setLOpts($opts);
}
return true;
}
/**************************************************************************
* helper methods
**************************************************************************/
/**
* 为命令注解提供可解析解析变量. 可以在命令的注释中使用
* @param string $str
* @return string
*/
protected function handleAnnotationVars($str)
{
$map = [];
foreach ($this->annotationVars() as $key => $value) {
$key = sprintf(self::ANNOTATION_VAR, $key);
$map[$key] = $value;
}
return $map ? strtr($str, $map) : $str;
}
/**
* show help by parse method annotation
* @param string $method
* @param null|string $action
* @return int
* @throws \ReflectionException
*/
protected function showHelpByMethodAnnotation($method, $action = null)
{
$ref = new \ReflectionClass($this);
$name = $this->input->getCommand();
if (!$ref->hasMethod($method)) {
$this->write("The command [<info>$name</info>] don't exist in the group: " . static::getName());
return 0;
}
// is a console controller command
if ($action && !$ref->getMethod($method)->isPublic()) {
$this->write("The command [<info>$name</info>] don't allow access in the class.");
return 0;
}
$doc = $ref->getMethod($method)->getDocComment();
$tags = Annotation::tagList($this->handleAnnotationVars($doc));
foreach ($tags as $tag => $msg) {
if (!$msg || !\is_string($msg)) {
continue;
}
if (isset(self::$annotationTags[$tag])) {
$msg = trim($msg);
// need multi align
// if (self::$annotationTags[$tag]) {
// $lines = array_map(function ($line) {
// // return trim($line);
// return $line;
// }, explode("\n", $msg));
// $msg = implode("\n", array_filter($lines, 'trim'));
// }
$tag = ucfirst($tag);
$this->write("<comment>$tag:</comment>\n $msg\n");
}
}
return 0;
}
/**************************************************************************
* getter/setter methods
**************************************************************************/
/**
* @param string $name
*/
public static function setName(string $name)
{
static::$name = $name;
}
/**
* @return string
*/
final public static function getName(): string
{
return static::$name;
}
/**
* @return string
*/
final public static function getDescription(): ?string
{
return static::$description;
}
/**
* @param string $description
*/
public static function setDescription(string $description)
{
static::$description = $description;
}
/**
* @return array
*/
public static function getAnnotationTags(): array
{
return self::$annotationTags;
}
/**
* @param array $annotationTags
* @param bool $replace
*/
public static function setAnnotationTags(array $annotationTags, $replace = false)
{
self::$annotationTags = $replace ? $annotationTags : array_merge(self::$annotationTags, $annotationTags);
}
/**
* @return InputDefinition
*/
public function getDefinition()
{
return $this->definition;
}
/**
* @param InputDefinition $definition
*/
public function setDefinition(InputDefinition $definition)
{
$this->definition = $definition;
}
/**
* @return ApplicationInterface
*/
public function getApp(): ApplicationInterface
{
return $this->app;
}
/**
* @param ApplicationInterface $app
*/
public function setApp(ApplicationInterface $app)
{
$this->app = $app;
}
/**
* @return string
*/
public function getProcessTitle(): string
{
return $this->processTitle;
}
/**
* @param string $processTitle
*/
public function setProcessTitle(string $processTitle)
{
$this->processTitle = $processTitle;
}
}