phpvms/app/Services/Metar/AviationWeather.php
Nabeel S 47be7507f0
Fix/metar reading (#354)
* Account for empty ICAO; added tests

* Fix null returns

* Fix typo in volume units display

* Add version field for bug report template

* Some more changes to the bug report template
2019-08-08 17:41:53 -04:00

59 lines
1.4 KiB
PHP

<?php
namespace App\Services\Metar;
use App\Contracts\Metar;
use App\Support\HttpClient;
use Illuminate\Support\Facades\Log;
/**
* Return the raw METAR string from the NOAA Aviation Weather Service
*/
class AviationWeather extends Metar
{
private const METAR_URL =
'https://www.aviationweather.gov/adds/dataserver_current/httpparam?'
.'dataSource=metars&requestType=retrieve&format=xml&hoursBeforeNow=3'
.'&mostRecent=true&fields=raw_text&stationString=';
private $httpClient;
public function __construct(HttpClient $httpClient)
{
$this->httpClient = $httpClient;
}
/**
* Implement the METAR - Return the string
*
* @param $icao
*
* @throws \Exception
* @throws \GuzzleHttp\Exception\GuzzleException
*
* @return string
*/
protected function metar($icao): string
{
if ($icao === '') {
return '';
}
$url = static::METAR_URL.$icao;
try {
$res = $this->httpClient->get($url, []);
$xml = simplexml_load_string($res);
if (\count($xml->data->METAR->raw_text) === 0) {
return '';
}
return $xml->data->METAR->raw_text->__toString();
} catch (\Exception $e) {
Log::error('Error reading METAR: '.$e->getMessage());
throw $e;
}
}
}