From 67a7429bafc537d838c2aff24736d0044674d33c Mon Sep 17 00:00:00 2001 From: Henry Whitaker Date: Wed, 24 Jun 2020 23:41:55 +0100 Subject: [PATCH] Added some error checking on runSpeedtest() --- app/Console/Commands/SpeedtestCommand.php | 10 +++++ app/Helpers/SpeedtestHelper.php | 47 +++++++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/app/Console/Commands/SpeedtestCommand.php b/app/Console/Commands/SpeedtestCommand.php index e0aaea56..2b914989 100644 --- a/app/Console/Commands/SpeedtestCommand.php +++ b/app/Console/Commands/SpeedtestCommand.php @@ -42,6 +42,16 @@ class SpeedtestCommand extends Command $results = SpeedtestHelper::runSpeedtest(); + if(!is_object($results)) { + $this->error('Something went wrong running the speedtest.'); + exit(); + } + + if(property_exists($results, 'ping') && property_exists($results, 'download') && property_exists($results, 'upload')) { + $this->error('Something went wrong running the speedtest.'); + exit(); + } + $this->info('Ping: ' . $results->ping . ' ms'); $this->info('Download: ' . $results->download . ' Mbit/s'); $this->info('Upload: ' . $results->upload . ' Mbit/s'); diff --git a/app/Helpers/SpeedtestHelper.php b/app/Helpers/SpeedtestHelper.php index ffb1d833..e35a1cb9 100644 --- a/app/Helpers/SpeedtestHelper.php +++ b/app/Helpers/SpeedtestHelper.php @@ -25,6 +25,11 @@ class SpeedtestHelper { try { $output = json_decode($output, true, 512, JSON_THROW_ON_ERROR); + + if(!SpeedtestHelper::checkOutputIsComplete($output)) { + return false; + } + $test = Speedtest::create([ 'ping' => $output['ping']['latency'], 'download' => SpeedtestHelper::convert($output['download']['bandwidth']), @@ -142,4 +147,46 @@ class SpeedtestHelper { 'unit' => 'Mbit/s' ]; } + + /** + * Checks that the speedtest JSON output is complete/valid + * + * @param array $output + * @return boolean + */ + public static function checkOutputIsComplete($output) + { + /** + * Array of indexes that must exist in $output + */ + $checks = [ + 'type' => 'result', + 'download' => [ 'bandwidth' => '*' ], + 'upload' => [ 'bandwidth' => '*' ], + 'ping' => [ 'latency' => '*' ], + 'server' => [ + 'id' => '*', + 'name' => '*', + 'host' => '*', + 'port' => '*' + ], + 'result' => [ + 'url' => '*' + ], + ]; + /** + * Array of indexes that must not exist + */ + $checkMissing = [ + 'type' => 'error' + ]; + + foreach($checks as $key => $value) { + if(!isset($output[$key])) { + return false; + } + } + + return true; + } }