Added some error checking on runSpeedtest()

This commit is contained in:
Henry Whitaker
2020-06-24 23:41:55 +01:00
parent 1bc0b3738d
commit 67a7429baf
2 changed files with 57 additions and 0 deletions

View File

@@ -42,6 +42,16 @@ class SpeedtestCommand extends Command
$results = SpeedtestHelper::runSpeedtest(); $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('Ping: ' . $results->ping . ' ms');
$this->info('Download: ' . $results->download . ' Mbit/s'); $this->info('Download: ' . $results->download . ' Mbit/s');
$this->info('Upload: ' . $results->upload . ' Mbit/s'); $this->info('Upload: ' . $results->upload . ' Mbit/s');

View File

@@ -25,6 +25,11 @@ class SpeedtestHelper {
try { try {
$output = json_decode($output, true, 512, JSON_THROW_ON_ERROR); $output = json_decode($output, true, 512, JSON_THROW_ON_ERROR);
if(!SpeedtestHelper::checkOutputIsComplete($output)) {
return false;
}
$test = Speedtest::create([ $test = Speedtest::create([
'ping' => $output['ping']['latency'], 'ping' => $output['ping']['latency'],
'download' => SpeedtestHelper::convert($output['download']['bandwidth']), 'download' => SpeedtestHelper::convert($output['download']['bandwidth']),
@@ -142,4 +147,46 @@ class SpeedtestHelper {
'unit' => 'Mbit/s' '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;
}
} }