-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathController.php
More file actions
781 lines (675 loc) · 19.1 KB
/
Copy pathController.php
File metadata and controls
781 lines (675 loc) · 19.1 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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
<?php declare(strict_types=1);
/**
* The file is part of inhere/console
*
* @author https://github.com/inhere
* @homepage https://github.com/inhere/php-console
* @license https://github.com/inhere/php-console/blob/master/LICENSE
*/
namespace Inhere\Console;
use Generator;
use Inhere\Console\Contract\ControllerInterface;
use Inhere\Console\Decorate\ControllerHelpTrait;
use Inhere\Console\Exception\ConsoleException;
use Inhere\Console\Handler\AbstractHandler;
use Inhere\Console\IO\Input;
use Inhere\Console\IO\Output;
use Inhere\Console\Util\Helper;
use ReflectionClass;
use ReflectionException;
use ReflectionMethod;
use ReflectionObject;
use Throwable;
use Toolkit\PFlag\FlagsParser;
use Toolkit\PFlag\FlagUtil;
use Toolkit\PFlag\SFlags;
use Toolkit\Stdlib\Obj\ObjectHelper;
use Toolkit\Stdlib\Str;
use function array_flip;
use function array_shift;
use function implode;
use function is_array;
use function is_string;
use function method_exists;
use function sprintf;
use function substr;
use function trim;
use function ucfirst;
/**
* Class Controller
*
* @package Inhere\Console
*/
abstract class Controller extends AbstractHandler implements ControllerInterface
{
use ControllerHelpTrait;
/**
* @var array global options for the group command
*/
protected static array $globalOptions = [
'--show-disabled' => 'Whether display disabled commands',
];
/**
* Action name - real subcommand name, no suffix 'Command'.
*
* eg: updateCommand() -> action: 'update'
*
* @var string
*/
private string $action = '';
/**
* The input group name.
*
* @var string
*/
private string $groupName = '';
/**
* The delimiter. eg: '/' ':'
*
* @var string
*/
private string $delimiter = ':';
/**
* @var string
*/
private string $defaultAction = '';
/**
* The action method name on the controller.
*
* @var string
*/
private string $actionMethod = '';
/**
* @var string
*/
private string $actionSuffix = self::COMMAND_SUFFIX;
/**
* Flags for all action commands
*
* ```php
* [
* action => AbstractFlags,
* action2 => AbstractFlags2,
* ]
* ```
*
* @var FlagsParser[]
* @psalm-var array<string, FlagsParser>
*/
private array $subFss = [];
/**
* @var array From disabledCommands()
*/
private array $disabledCommands = [];
/**
* TODO ...
*
* @var array
*/
private array $attachedCommands = [];
/**
* Metadata for sub-commands. such as: desc, alias
* Notice: you must add metadata on `init()`
*
* [
* 'command real name' => [
* 'desc' => 'sub command description',
* 'alias' => [],
* ],
* ],
*
* @var array
*/
protected array $commandMetas = [];
/**
* Define command alias mapping. please rewrite it on sub-class.
*
* - key is command name, value is aliases.
*
* @return array{string: list<string>}
*/
protected static function commandAliases(): array
{
// Usage:
// - method 1:
// alias => command
// [
// 'i' => 'install',
// 'ins' => 'install',
// ]
//
// - method 2:
// command => alias[]
// [
// 'install' => ['i', 'ins'],
// ]
return [];
}
protected function init(): void
{
parent::init();
// up: load sub-commands alias
$this->loadCommandAliases();
$list = $this->disabledCommands();
$this->groupName = $this->getRealGName();
// save to property
$this->disabledCommands = $list ? array_flip($list) : [];
if (!$this->actionSuffix) {
$this->actionSuffix = self::COMMAND_SUFFIX;
}
}
/**
* define disabled command list.
*
* @return array
*/
protected function disabledCommands(): array
{
// ['command1', 'command2'];
return [];
}
/**
* Will call it on subcommand not found on the group.
*
* @param string $command
* @param array $args
*
* @return bool if return True, will stop goon render group help.
*/
protected function onNotFound(string $command, array $args): bool
{
// TIP: you can add custom logic on sub-command not found.
return false;
}
/**
* @param FlagsParser $fs
*/
protected function afterInitFlagsParser(FlagsParser $fs): void
{
$fs->addOptsByRules(GlobalOption::getGroupOptions());
}
/**
* Run an action with args
*
* Usage:
*
* ```php
* $args = $this->flags->getRawArgs();
* // add option
* $args[] = '--push';
* $this->runActionWithArgs('subcmd', $args);
* ```
*
* @param string $cmd
* @param array $args
*
* @return bool|int|mixed
* @throws Throwable
*/
public function runActionWithArgs(string $cmd, array $args): mixed
{
$args[0] = $cmd;
return $this->doRun($args);
}
protected function beforeRun(): void
{
}
/**
* @param array $args
*
* @return mixed
* @throws Throwable
*/
public function doRun(array $args): mixed
{
$name = self::getName();
if (!$args) {
$command = $this->defaultAction;
// and not default command
if (!$command) {
$this->debugf('cmd: %s - run args is empty, display help for the group', $name);
return $this->showHelp();
}
} else {
$first = $args[0];
if (!FlagUtil::isValidName($first)) {
$this->debugf('cmd: %s - not input subcommand, display help for the group', $name);
return $this->showHelp();
}
$command = $first;
array_shift($args);
}
// update subcommand
$this->commandName = $command;
// update some comment vars
$fullCmd = $this->input->buildFullCmd($name, $command);
$this->setCommentsVar('fullCmd', $fullCmd);
$this->setCommentsVar('fullCommand', $fullCmd);
$this->setCommentsVar('binWithCmd', $this->input->buildCmdPath($name, $command));
// get real sub-command name
$command = $this->resolveAlias($command);
// update the command id.
$this->input->setCommandId("$name:$command");
// convert 'boo-foo' to 'booFoo'
$this->action = $action = Str::camelCase($command);
$this->debugf("cmd: %s - will run the subcommand: %s(action: %s)", $name, $command, $action);
$method = $this->getMethodName($action);
// fire event
$this->fire(ConsoleEvent::COMMAND_RUN_BEFORE, $this);
$this->beforeRun();
// check method not exist
if (!method_exists($this, $method)) {
if ($this->isSub($command)) {
return $this->dispatchSub($command, $args);
}
// if command not exists.
return $this->handleNotFound($name, $command, $args);
}
// init flags for subcommand
$fs = $this->newActionFlags();
$this->actionMethod = $method;
$this->input->setFs($fs);
$this->debugf('load flags by configure method, subcommand: %s', $command);
$this->configure();
// not config flags. load rules from method doc-comments
if ($fs->isEmpty()) {
$this->loadRulesByDocblock($method, $fs);
}
$this->log(Console::VERB_DEBUG, "run subcommand '$name.$command' - parse options", ['args' => $args]);
// parse subcommand flags.
if (!$fs->parse($args)) {
return 0;
}
// do running
return parent::doRun($args);
}
/**
* Load command configure
*/
protected function configure(): void
{
// eg. use `indexConfigure()` for `indexCommand()`
$method = $this->action . self::CONFIGURE_SUFFIX;
if (method_exists($this, $method)) {
$this->$method($this->input);
}
}
/**
* Before controller method execute
*
* @return boolean It MUST return TRUE to continue execute. if return False, will stop run.
*/
protected function beforeAction(): bool
{
return true;
}
/**
* After controller method execute
*/
protected function afterAction(): void
{
}
/**
* Run command action in the group
*
* @param Input $input
* @param Output $output
*
* @return mixed
* @throws ReflectionException
*/
final public function execute(Input $input, Output $output): mixed
{
$action = $this->action;
$group = static::getName();
if ($this->isDisabled($action)) {
$this->debugf('command %s is disabled on the group %s', $action, $group);
$output->error(sprintf("Sorry, The command '%s' is invalid in the group '%s'!", $action, $group));
return -1;
}
$method = $this->getMethodName($action);
// trigger event
$this->fire(ConsoleEvent::SUBCOMMAND_RUN_BEFORE, $this);
// the action method exists and only allow access public method.
// if (method_exists($this, $method)) {
// before run action
if (!$this->beforeAction()) {
$this->debugf('beforeAction() returns FALSE, interrupt processing continues');
return 0;
}
if (method_exists($this, $beforeFunc = 'before' . ucfirst($action))) {
$beforeOk = $this->$beforeFunc($input, $output);
if ($beforeOk === false) {
$this->debugf('%s() returns FALSE, interrupt processing continues', $beforeFunc);
return 0;
}
}
// current action flags
$flags = $this->actionFlags($action);
$rftMethod = new ReflectionMethod($this, $method);
$callArgs = ObjectHelper::buildReflectCallArgs($rftMethod, [
Input::class => $this->input,
Output::class => $this->output,
FlagsParser::class => $flags,
// 'args' => $args,
]);
// call action method
$result = $rftMethod->invokeArgs($this, $callArgs);
// call action method
// $result = $this->$method($input, $output, $flags);
// after run action
if (method_exists($this, $after = 'after' . ucfirst($action))) {
$this->$after($input, $output);
}
$this->afterAction();
return $result;
}
/**
* @param string $group
* @param string $command
* @param array $args
*
* @return int
*/
protected function handleNotFound(string $group, string $command, array $args): int
{
// if user custom handle not found logic.
if ($this->onNotFound($command, $args)) {
$this->debugf('group: %s - user custom handle the subcommand "%s" not found', $group, $command);
return 0;
}
$this->debugf('group: %s - command "%s" is not found on the group', $group, $command);
// if you defined the method '$this->notFoundCallback' , will call it
// if (($notFoundCallback = $this->notFoundCallback) && method_exists($this, $notFoundCallback)) {
// $result = $this->{$notFoundCallback}($action);
// } else {
$this->output->liteError("Sorry, The command '$command' not exist of the group '$group'!");
// find similar command names
$similar = Helper::findSimilar($command, $this->getAllCommandMethods(null, true));
if ($similar) {
$this->output->writef("\nMaybe what you mean is:\n <info>%s</info>", implode(', ', $similar));
} else {
$this->showCommandList();
}
return -1;
}
/**
* @param string $action
*
* @return FlagsParser
*/
protected function newActionFlags(string $action = ''): FlagsParser
{
$action = $action ?: $this->action;
if (!$fs = $this->getActionFlags($action)) {
$fs = new SFlags(['name' => $action]);
$fs->setStopOnFistArg(false);
$fs->setBeforePrintHelp(function (string $text) {
return $this->parseCommentsVars($text);
});
$fs->setHelpRenderer(function (): void {
$this->logf(Console::VERB_DEBUG, 'show subcommand help by input flags: -h, --help');
$this->showHelp();
});
// old mode: options and arguments at method annotations
// if ($this->compatible) {
// $fs->setSkipOnUndefined(true);
// }
// save
$this->subFss[$action] = $fs;
}
return $fs;
}
/**
* @param string $action
*
* @return string
*/
protected function getMethodName(string $action): string
{
return $this->actionSuffix ? $action . ucfirst($this->actionSuffix) : $action;
}
/**
* @return bool
*/
protected function showHelp(): bool
{
return $this->helpCommand() === 0;
}
/**
* @param array $help
*/
protected function beforeRenderCommandHelp(array &$help): void
{
$help['Group Options:'] = FlagUtil::alignOptions($this->flags->getOptsHelpLines());
}
/**
* @param ReflectionClass|null $ref
* @param bool $onlyName
*
* @return ?Generator
*/
protected function getAllCommandMethods(?ReflectionClass $ref = null, bool $onlyName = false): ?Generator
{
$ref = $ref ?: new ReflectionObject($this);
$suffix = $this->actionSuffix;
$suffixLen = Str::len($suffix);
foreach ($ref->getMethods() as $m) {
$mName = $m->getName();
if ($m->isPublic() && substr($mName, -$suffixLen) === $suffix) {
// suffix is empty ?
$cmd = $suffix ? substr($mName, 0, -$suffixLen) : $mName;
if ($onlyName) {
yield $cmd;
} else {
yield $cmd => $m;
}
}
}
}
/**
* @param string $name
*
* @return bool
*/
public function isDisabled(string $name): bool
{
return isset($this->disabledCommands[$name]);
}
/**
* load sub-commands aliases from sub-class::commandAliases()
*/
public function loadCommandAliases(): void
{
$cmdAliases = static::commandAliases();
if (!$cmdAliases) {
return;
}
foreach ($cmdAliases as $name => $item) {
// $name is command, $item is alias list
// eg: ['command1' => ['alias1', 'alias2']]
if (is_array($item)) {
$this->setAlias($name, $item, true);
} elseif (is_string($item)) { // $item is command, $name is alias name
$this->setAlias($item, $name, true);
}
}
}
/**************************************************************************
* getter/setter methods
**************************************************************************/
/**
* @return array
*/
public function getDisabledCommands(): array
{
return $this->disabledCommands;
}
/**
* @return string
*/
public function getGroupName(): string
{
return $this->groupName;
}
/**
* @return string
*/
public function getRealGName(): string
{
return self::getName();
}
/**
* @param string $groupName
*/
public function setGroupName(string $groupName): void
{
$this->groupName = $groupName;
}
/**
* @return string
*/
public function getRealCName(): string
{
return $this->action;
}
/**
* @return string
*/
public function getSubName(): string
{
return $this->commandName;
}
/**
* @param bool $useReal
*
* @return string
*/
public function getCommandId(bool $useReal = true): string
{
if ($useReal) {
return self::getName() . $this->delimiter . $this->action;
}
return $this->groupName . $this->delimiter . $this->commandName;
}
/**
* @return string
*/
public function getAction(): string
{
return $this->action;
}
/**
* @param string $action
*
* @return $this
*/
public function setAction(string $action): self
{
if ($action) {
$this->action = Str::camelCase($action);
}
return $this;
}
/**
* @return string
*/
public function getDefaultAction(): string
{
return $this->defaultAction;
}
/**
* @param string $action
*/
public function setDefaultAction(string $action): void
{
$this->defaultAction = trim($action, $this->delimiter);
}
/**
* @return string
*/
public function getActionSuffix(): string
{
return $this->actionSuffix;
}
/**
* @param string $actionSuffix
*/
public function setActionSuffix(string $actionSuffix): void
{
$this->actionSuffix = $actionSuffix;
}
/**
* @return string
*/
public function getDelimiter(): string
{
return $this->delimiter;
}
/**
* @param string $delimiter
*/
public function setDelimiter(string $delimiter): void
{
$this->delimiter = $delimiter;
}
/**
* @return array
*/
public function getCommandMetas(): array
{
return $this->commandMetas;
}
/**
* @param string $command
* @param array $meta eg: ['desc' => '', 'alias' => []]
*/
public function setCommandMeta(string $command, array $meta): void
{
if ($command) {
$this->commandMetas[$command] = $meta;
}
}
/**
* @param string $key
* @param null $default
* @param string $command if not set, will use $this->action
*
* @return mixed|null
*/
public function getCommandMeta(string $key, $default = null, string $command = ''): mixed
{
$action = $command ?: $this->action;
return $this->commandMetas[$action][$key] ?? $default;
}
/**
* @param string $action
*
* @return FlagsParser|null
*/
public function getActionFlags(string $action): ?FlagsParser
{
$action = $action ?: $this->action;
return $this->subFss[$action] ?? null;
}
/**
* @return FlagsParser
*/
public function curActionFlags(): FlagsParser
{
return $this->actionFlags($this->action);
}
/**
* @param string $action
*
* @return FlagsParser
*/
public function actionFlags(string $action): FlagsParser
{
$action = $action ?: $this->action;
if (!isset($this->subFss[$action])) {
throw new ConsoleException("not found flags parser for the action: $action");
}
return $this->subFss[$action];
}
}