|
8 | 8 | use Throwable; |
9 | 9 | use Toolkit\Cli\Cli; |
10 | 10 | use Toolkit\Cli\Color; |
| 11 | +use Toolkit\PFlag\Contract\CmdHandlerInterface; |
11 | 12 | use Toolkit\Stdlib\Arr; |
| 13 | +use Toolkit\Stdlib\Helper\Assert; |
| 14 | +use Toolkit\Stdlib\Helper\Valid; |
12 | 15 | use Toolkit\Stdlib\Obj\Traits\AutoConfigTrait; |
13 | 16 | use function array_merge; |
14 | 17 | use function array_shift; |
@@ -61,12 +64,14 @@ class CliApp |
61 | 64 | /** |
62 | 65 | * @var FlagsParser |
63 | 66 | */ |
64 | | - protected FlagsParser|SFlags $flags; |
| 67 | + protected FlagsParser $flags; |
65 | 68 |
|
66 | 69 | /** |
| 70 | + * Flags for current run command |
| 71 | + * |
67 | 72 | * @var FlagsParser|null |
68 | 73 | */ |
69 | | - protected ?FlagsParser $cmdFlags; |
| 74 | + protected ?FlagsParser $cmdFlags = null; |
70 | 75 |
|
71 | 76 | /** |
72 | 77 | * @var string |
@@ -358,6 +363,27 @@ public function add(string $command, callable $handler, array $config = []): voi |
358 | 363 | $this->addCommand($command, $handler, $config); |
359 | 364 | } |
360 | 365 |
|
| 366 | + /** |
| 367 | + * @param class-string|CmdHandlerInterface $handler |
| 368 | + */ |
| 369 | + public function addHandler(string|CmdHandlerInterface $handler): void |
| 370 | + { |
| 371 | + if (is_string($handler)) { |
| 372 | + // class string. |
| 373 | + if (class_exists($handler)) { |
| 374 | + $handler = new $handler; |
| 375 | + Assert::isTrue($handler instanceof CmdHandlerInterface, 'must be an class and instance of CmdHandlerInterface'); |
| 376 | + } else { |
| 377 | + throw new InvalidArgumentException('must be an class string'); |
| 378 | + } |
| 379 | + } |
| 380 | + |
| 381 | + $config = $handler->metadata(); |
| 382 | + $command = Valid::arrayHasNoEmptyKey($config, 'name'); |
| 383 | + |
| 384 | + $this->addCommand($command, $handler, $config); |
| 385 | + } |
| 386 | + |
361 | 387 | /** |
362 | 388 | * @param string $command |
363 | 389 | * @param callable|object|class-string $handler |
|
0 commit comments