From 8350b6bd36d3a4bb3a99dfbf67e746f4f815927c Mon Sep 17 00:00:00 2001 From: Fbenas Date: Mon, 7 May 2018 15:02:39 +0100 Subject: Add some simple exception handling for bad inputs --- src/Script/Console.php | 15 ++++++++++----- src/Script/Input.php | 8 ++++++++ src/Script/Output.php | 6 ++++++ 3 files changed, 24 insertions(+), 5 deletions(-) (limited to 'src/Script') diff --git a/src/Script/Console.php b/src/Script/Console.php index e1d7df5..3228750 100644 --- a/src/Script/Console.php +++ b/src/Script/Console.php @@ -5,6 +5,7 @@ namespace App\Script; use App\Model\Vendor; use App\Script\Input; use App\Script\Output; +use Exception; /** * Main application class @@ -44,12 +45,16 @@ class Console */ public function exec() { - $input = new Input; - $vendors = Vendor::loadAll($input->getOption('f')); + $output = new Output; + try { + $input = new Input; + $vendors = Vendor::loadAll($input->getOption('f')); - $vendors->filterByInput($input); + $vendors->filterByInput($input); - $output = new Output; - $output->printCollection($vendors); + $output->printCollection($vendors); + } catch (Exception $e) { + $output->printException($e); + } } } diff --git a/src/Script/Input.php b/src/Script/Input.php index 4e437dd..772bb8c 100644 --- a/src/Script/Input.php +++ b/src/Script/Input.php @@ -63,6 +63,14 @@ class Input if ((array_key_exists('d', $this->options) <=> array_key_exists('t', $this->options)) !== 0) { throw new Exception('Both day and time options (`-d` and `-t`) are required for time based filtering'); } + + if (array_key_exists('c', $this->options) && !is_numeric($this->options['c'])) { + throw new Exception('Value for option `-c` must be an integer'); + } + + if (array_key_exists('l', $this->options) && is_numeric($this->options['l'])) { + throw new Exception('Value for option `-l` must be a string'); + } } /** diff --git a/src/Script/Output.php b/src/Script/Output.php index 8f7a689..e61cff8 100644 --- a/src/Script/Output.php +++ b/src/Script/Output.php @@ -3,6 +3,7 @@ namespace App\Script; use App\Model\Collection; +use Exception; class Output { @@ -20,4 +21,9 @@ class Output echo implode("\n\n", $out) . "\n"; } + + public function printException(Exception $e) + { + echo "An unexpected exception occured:\n" . $e->getMessage() . "\n"; + } } -- cgit v1.2.3