Skip to content

Commit 1dc923b

Browse files
committed
update some logic, modify error handle
1 parent fedcc2a commit 1dc923b

24 files changed

+349
-182
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,7 @@ $app->registerGroups('App\\Console\\Controllers', dirname(__DIR__) . '/Controlle
254254

255255
## 错误/异常捕获
256256

257-
<img src="docs/screenshots/error-catch.jpg" alt="error-catch" style="width: 500px">
257+
![error-handle-display](docs/screenshots/error-handle-display.png)
258258

259259
## 输入
260260

docs/screenshots/error-catch.jpg

-110 KB
Binary file not shown.

docs/screenshots/error-catch.png

-858 KB
Binary file not shown.
80.5 KB
Loading

examples/Controllers/HomeController.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ public function exCommand()
129129
*/
130130
public function errorCommand()
131131
{
132-
trigger_error('oo, this is a runtime error!', E_USER_ERROR);
132+
\trigger_error('oo, this is a runtime error!', E_USER_ERROR);
133133
}
134134

135135
/**

examples/home renamed to examples/alone

Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ define('BASE_PATH', dirname(__DIR__));
1111
require dirname(__DIR__) . '/test/boot.php';
1212

1313
$input = new \Inhere\Console\IO\Input();
14-
$ctrl = new HomeController($input, new \Inhere\Console\IO\Output());
14+
$ctrl = new HomeController($input, new \Inhere\Console\IO\Output());
1515
$ctrl->setExecutionAlone();
1616

1717
try {
@@ -24,15 +24,4 @@ try {
2424
);
2525
}
2626

27-
// can also:
28-
29-
// $app = new \Inhere\Console\Application([
30-
// 'debug' => true,
31-
// 'rootPath' => BASE_PATH,
32-
// ]);
33-
//
34-
// $app->controller('home', HomeController::class);
35-
//
36-
// exit(
37-
// (int)$app->runAction('home', $app->getInput()->getCommand(), false, true)
38-
// );
27+
// can also: see './alone-app' file

examples/alone-app

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
#!/usr/env/php
2+
<?php
3+
/**
4+
* only run a controller.
5+
*/
6+
7+
use Inhere\Console\Examples\Controllers\HomeController;
8+
9+
define('BASE_PATH', dirname(__DIR__));
10+
11+
require dirname(__DIR__) . '/test/boot.php';
12+
13+
try {
14+
$input = new \Inhere\Console\IO\Input();
15+
$app = new \Inhere\Console\Application([
16+
'debug' => true,
17+
'rootPath' => BASE_PATH,
18+
], $input);
19+
20+
$app->controller('home', HomeController::class);
21+
$code = $app->runAction('home', $input->getCommand(), false, true);
22+
23+
exit((int)$code);
24+
} catch (\Exception $e) {
25+
$message = \Toolkit\Cli\Color::apply('error', $e->getMessage());
26+
27+
echo sprintf("%s\nFile %s:%d\nTrace:\n%s\n",
28+
$message, $e->getFile(), $e->getLine(), $e->getTraceAsString()
29+
);
30+
}
31+
32+
// can also: see './alone' file

examples/commands.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,4 +44,4 @@
4444
$app->controller(PharController::class);
4545

4646
// add alias for a group command.
47-
$app->addCommandAliases('home:test', 'h-test');
47+
$app->addCommandAliases('home:test', 'h-test');

src/Application.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,11 @@ public function addGroup(string $name, $controller = null, $option = null)
198198

199199
/**
200200
* auto register commands from a dir.
201+
*
202+
* ```php
203+
* $app->registerCommands('SwagPhp\Command', dirname(__DIR__) . '/src/Command');
204+
* ```
205+
*
201206
* @param string $namespace
202207
* @param string $basePath
203208
* @return $this

src/Base/AbstractApplication.php

Lines changed: 36 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88

99
namespace Inhere\Console\Base;
1010

11+
use Inhere\Console\BuiltIn\ErrorHandler;
12+
use Inhere\Console\Face\ErrorHandlerInterface;
1113
use Inhere\Console\IO\Input;
1214
use Inhere\Console\IO\InputInterface;
1315
use Inhere\Console\IO\Output;
@@ -89,6 +91,9 @@ abstract class AbstractApplication implements ApplicationInterface
8991
/** @var array The group commands */
9092
protected $controllers = [];
9193

94+
/** @var ErrorHandlerInterface */
95+
private $errorHandler;
96+
9297
/**
9398
* App constructor.
9499
* @param array $meta
@@ -139,6 +144,10 @@ public static function getInternalOptions(): array
139144

140145
protected function prepareRun()
141146
{
147+
if (!$this->errorHandler) {
148+
$this->errorHandler = new ErrorHandler();
149+
}
150+
142151
// date_default_timezone_set($this->config('timeZone', 'UTC'));
143152
//new AutoCompletion(array_merge($this->getCommandNames(), $this->getControllerNames()));
144153
}
@@ -172,7 +181,7 @@ public function run(bool $exit = true)
172181
$this->handleException($e);
173182
}
174183

175-
$this->meta['_stats']['endTime'] = microtime(1);
184+
$this->meta['_stats']['endTime'] = \microtime(1);
176185

177186
// call 'onAfterRun' service, if it is registered.
178187
$this->fire(self::ON_AFTER_RUN, $this);
@@ -255,7 +264,6 @@ protected function registerErrorHandle()
255264
{
256265
\set_error_handler([$this, 'handleError']);
257266
\set_exception_handler([$this, 'handleException']);
258-
259267
\register_shutdown_function(function () {
260268
if ($e = \error_get_last()) {
261269
$this->handleError($e['type'], $e['message'], $e['file'], $e['line']);
@@ -278,57 +286,15 @@ public function handleError(int $num, string $str, string $file, int $line)
278286
}
279287

280288
/**
281-
* 运行异常处理
289+
* Running exception handling
282290
* @param \Throwable $e
283291
* @throws \InvalidArgumentException
284292
*/
285293
public function handleException($e)
286-
{
287-
$class = \get_class($e);
288-
$this->logError($e);
289-
290-
// open debug, throw exception
291-
if ($this->isDebug()) {
292-
$tpl = <<<ERR
293-
\n<error> Error </error> <mga>%s</mga>
294-
295-
At File <cyan>%s</cyan> line <bold>%d</bold>
296-
Exception $class
297-
<comment>Code View:</comment>\n\n%s
298-
<comment>Code Trace:</comment>\n\n%s\n
299-
ERR;
300-
$line = $e->getLine();
301-
$file = $e->getFile();
302-
$snippet = Highlighter::create()->highlightSnippet(file_get_contents($file), $line, 3, 3);
303-
$message = sprintf(
304-
$tpl,
305-
// $e->getCode(),
306-
$e->getMessage(),
307-
$file,
308-
$line,
309-
// __METHOD__,
310-
$snippet,
311-
\str_replace('):', "):\n -", $e->getTraceAsString())
312-
);
313-
314-
if ($this->meta['hideRootPath'] && ($rootPath = $this->meta['rootPath'])) {
315-
$message = \str_replace($rootPath, '{ROOT}', $message);
316-
}
317-
318-
$this->output->write($message, false);
319-
} else {
320-
// simple output
321-
$this->output->error('An error occurred! MESSAGE: ' . $e->getMessage());
322-
$this->output->write("\nYou can use '--debug' to see error details.");
323-
}
324-
}
325-
326-
/**
327-
* @param \Throwable $e
328-
*/
329-
protected function logError($e)
330294
{
331295
// you can log error on sub class ...
296+
297+
$this->errorHandler->handle($e, $this);
332298
}
333299

334300
/**
@@ -392,7 +358,7 @@ protected function validateName(string $name, bool $isGroup = false)
392358
* @param bool $quit
393359
* @param string $command
394360
*/
395-
public function showHelpInfo($quit = true, string $command = null)
361+
public function showHelpInfo(bool $quit = true, string $command = '')
396362
{
397363
// display help for a special command
398364
if ($command) {
@@ -423,14 +389,14 @@ public function showHelpInfo($quit = true, string $command = null)
423389
*/
424390
public function showVersionInfo($quit = true)
425391
{
426-
$os = PHP_OS;
427-
$date = date('Y.m.d');
392+
$os = \PHP_OS;
393+
$date = \date('Y.m.d');
428394
$logo = '';
429395
$name = $this->getMeta('name', 'Console Application');
430396
$version = $this->getMeta('version', 'Unknown');
431397
$publishAt = $this->getMeta('publishAt', 'Unknown');
432398
$updateAt = $this->getMeta('updateAt', 'Unknown');
433-
$phpVersion = PHP_VERSION;
399+
$phpVersion = \PHP_VERSION;
434400

435401
if ($logoTxt = $this->getLogoText()) {
436402
$logo = Helper::wrapTag($logoTxt, $this->getLogoStyle());
@@ -462,7 +428,7 @@ public function showCommandList($quit = true)
462428
// all console controllers
463429
if ($controllers = $this->controllers) {
464430
\ksort($controllers);
465-
$controllerArr[] = PHP_EOL . '- <bold>Group Commands</bold>';
431+
$controllerArr[] = \PHP_EOL . '- <bold>Group Commands</bold>';
466432
}
467433

468434
foreach ($controllers as $name => $controller) {
@@ -480,7 +446,7 @@ public function showCommandList($quit = true)
480446

481447
// all independent commands, Independent, Single, Alone
482448
if ($commands = $this->commands) {
483-
$commandArr[] = PHP_EOL . '- <bold>Alone Commands</bold>';
449+
$commandArr[] = \PHP_EOL . '- <bold>Alone Commands</bold>';
484450
\ksort($commands);
485451
}
486452

@@ -535,7 +501,7 @@ public function showCommandList($quit = true)
535501
* @param string $default
536502
* @return string|null
537503
*/
538-
public function getCommandMessage($name, $default = null)
504+
public function getCommandMessage(string $name, $default = null)
539505
{
540506
return $this->commandMessages[$name] ?? $default;
541507
}
@@ -873,4 +839,20 @@ public function getCommandMetaValue(string $command, string $key, $default = nul
873839
{
874840
return $this->commandsMeta[$command][$key] ?? $default;
875841
}
842+
843+
/**
844+
* @return ErrorHandlerInterface
845+
*/
846+
public function getErrorHandler(): ErrorHandlerInterface
847+
{
848+
return $this->errorHandler;
849+
}
850+
851+
/**
852+
* @param ErrorHandlerInterface $errorHandler
853+
*/
854+
public function setErrorHandler(ErrorHandlerInterface $errorHandler): void
855+
{
856+
$this->errorHandler = $errorHandler;
857+
}
876858
}

0 commit comments

Comments
 (0)