22/**
33 * This file is part of toolkit/cli-utils.
44 *
5- * @link https://github.com/inhere
5+ * @link https://github.com/php-toolkit/cli-utils
66 * @author https://github.com/inhere
77 * @license MIT
88 */
@@ -100,7 +100,7 @@ class App
100100 * Class constructor.
101101 *
102102 * @param array $config
103- * @param array $argv
103+ * @param array|null $argv
104104 */
105105 public function __construct (array $ config = [], array $ argv = null )
106106 {
@@ -148,7 +148,6 @@ protected function findCommand(): void
148148 }
149149
150150 $ newArgs = [];
151-
152151 foreach ($ this ->args as $ key => $ value ) {
153152 if ($ key === 0 ) {
154153 $ this ->command = trim ($ value );
@@ -168,20 +167,32 @@ protected function findCommand(): void
168167 * @throws InvalidArgumentException
169168 */
170169 public function dispatch (bool $ exit = true ): void
170+ {
171+ $ status = $ this ->doHandle ();
172+
173+ if ($ exit ) {
174+ $ this ->stop ($ status );
175+ }
176+ }
177+
178+ /**
179+ * @return int
180+ */
181+ protected function doHandle (): int
171182 {
172183 if (!$ command = $ this ->command ) {
173184 $ this ->displayHelp ();
174- return ;
185+ return 0 ;
175186 }
176187
177188 if (!isset ($ this ->commands [$ command ])) {
178189 $ this ->displayHelp ("The command ' {$ command }' is not exists! " );
179- return ;
190+ return 0 ;
180191 }
181192
182193 if (isset ($ this ->opts ['h ' ]) || isset ($ this ->opts ['help ' ])) {
183194 $ this ->displayCommandHelp ($ command );
184- return ;
195+ return 0 ;
185196 }
186197
187198 try {
@@ -190,9 +201,7 @@ public function dispatch(bool $exit = true): void
190201 $ status = $ this ->handleException ($ e );
191202 }
192203
193- if ($ exit ) {
194- $ this ->stop ($ status );
195- }
204+ return $ status ;
196205 }
197206
198207 /**
@@ -360,7 +369,7 @@ public function commands(array $commands): void
360369 public function displayHelp (string $ err = '' ): void
361370 {
362371 if ($ err ) {
363- echo Color::render ("<red>ERROR</red>: $ err\n \n" );
372+ Color::println ("<red>ERROR</red>: $ err \n" );
364373 }
365374
366375 // help
@@ -383,8 +392,7 @@ public function displayHelp(string $err = ''): void
383392
384393 $ help .= "\nFor command usage please run: <cyan> {$ this ->script } COMMAND -h</cyan> " ;
385394
386- echo Color::render ($ help ) . PHP_EOL ;
387- exit (0 );
395+ Color::println ($ help );
388396 }
389397
390398 /**
@@ -427,7 +435,7 @@ public function displayCommandHelp(string $name): void
427435 ]);
428436 }
429437
430- echo Color::render ($ help );
438+ Color::println ($ help );
431439 }
432440
433441 /**
0 commit comments