From e117ff830d3f9a36727e59bd4b75f463dd320041 Mon Sep 17 00:00:00 2001 From: Basuke Suzuki Date: Fri, 21 Apr 2017 00:26:44 -0700 Subject: [PATCH] added DebugMiddleware --- Clim/App.php | 20 +++++++++-- Clim/Middleware/DebugMiddleware.php | 52 +++++++++++++++++++++++++++++ composer.json | 4 ++- examples/hello.php | 9 +++-- 4 files changed, 80 insertions(+), 5 deletions(-) create mode 100644 Clim/Middleware/DebugMiddleware.php diff --git a/Clim/App.php b/Clim/App.php index 1e6d9c7..288af0f 100644 --- a/Clim/App.php +++ b/Clim/App.php @@ -17,6 +17,9 @@ class App /** @var Spec */ private $spec; + /** @var bool */ + private $handle_errors = true; + /** * Constructor of Clim\App * @param ContainerInterface|array|null $container @@ -146,13 +149,26 @@ public function run() $context = $this->runner()->run(array_slice($argv, 1)); return $context; } catch (Exception $e) { - $this->handleException($e); + if ($this->handle_errors) { + $this->handleException($e); + } else { + throw $e; + } } catch (Throwable $e) { - $this->handlePhpError($e); + if ($this->handle_errors) { + $this->handlePhpError($e); + } else { + throw $e; + } } return null; } + public function disableErrorHandling() + { + $this->handle_errors = false; + } + /** * Call relevant handler from the Container if needed. If it doesn't exist, * then just print error diff --git a/Clim/Middleware/DebugMiddleware.php b/Clim/Middleware/DebugMiddleware.php new file mode 100644 index 0000000..aaba426 --- /dev/null +++ b/Clim/Middleware/DebugMiddleware.php @@ -0,0 +1,52 @@ +display_error = $setting['display_error'] ?: true; + $this->error_reporting_level = $setting['error_reporting_level'] ?: E_ALL; + } + + public function __invoke(Context $context, callable $next) + { + $app = $context->getApp(); + + $display_error = $this->display_error; + $error_reporting_level = $this->error_reporting_level; + + $app->opt('-d|--debug', function () use ( + $app, + $display_error, + $error_reporting_level + ) { + $app->disableErrorHandling(); + + Debug::enable($error_reporting_level, $display_error); + }); + + return $next($context); + } +} \ No newline at end of file diff --git a/composer.json b/composer.json index 6767ca6..5113838 100644 --- a/composer.json +++ b/composer.json @@ -23,7 +23,9 @@ } }, "require-dev": { - "codeception/codeception": "^2.2" + "codeception/codeception": "^2.2", + "symfony/debug": "^3.2", + "symfony/var-dumper": "^3.2" }, "scripts": { "test": [ diff --git a/examples/hello.php b/examples/hello.php index 7dd507a..228eefc 100644 --- a/examples/hello.php +++ b/examples/hello.php @@ -1,8 +1,11 @@ opt('-u|--upper'); $app->arg('name')->default('unknown'); @@ -12,7 +15,9 @@ if ($opts['u']) $name = strtoupper($name); - echo "Welcome, {$name}\n"; + echo "Welcome, {$name} {$unknown}\n"; // <-- this will invoke notice. }); +$app->add(DebugMiddleware::class); + $app->run();