phpvms/app/Services/Metar/AviationWeather.php

55 lines
1.3 KiB
PHP
Raw Normal View History

<?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
2018-08-27 00:40:04 +08:00
*
* @param $icao
2018-08-27 00:40:04 +08:00
*
* @throws \Exception
* @throws \GuzzleHttp\Exception\GuzzleException
*
* @return string
*/
protected function metar($icao): string
{
$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;
}
}
}