From f742dbc06dcb79aef07a2a5ef546eebb07abc01f Mon Sep 17 00:00:00 2001 From: BJ Hansen Date: Fri, 21 Jun 2024 14:11:29 -0500 Subject: [PATCH] readme update; new helper function package addition; new API method added to make sure the API endpoint is OK --- composer.json | 3 ++- readme.md | 7 +++++++ src/Api.php | 13 ++++++++++++- src/functions.php | 13 ------------- 4 files changed, 21 insertions(+), 15 deletions(-) diff --git a/composer.json b/composer.json index 3f449a9..159a104 100644 --- a/composer.json +++ b/composer.json @@ -25,6 +25,7 @@ "guzzlehttp/guzzle": "^7.8", "nesbot/carbon": "^3.2", "phpfastcache/phpfastcache": "^9.2", - "illuminate/collections": "^11.6" + "illuminate/collections": "^11.6", + "laravel/helpers": "^1.7" } } diff --git a/readme.md b/readme.md index fdbb0fe..7741728 100644 --- a/readme.md +++ b/readme.md @@ -41,6 +41,13 @@ $api->useCache(); // $api->setCacheLifetime(3600); // seconds that the cached data should persist +/* +** You can make sure that the API's status returns OK before allowing any +** requests to be made. An exception will be thrown if the API status is not OK. +*/ +$api->ensureApiIsOk(); + + /* ** We can set a timezone for the entire API callstack. ** All datetime objects will be converted to this timestamp. diff --git a/src/Api.php b/src/Api.php index daad074..1ea7da7 100644 --- a/src/Api.php +++ b/src/Api.php @@ -8,6 +8,7 @@ use NWS\Features\ForecastOffice; use NWS\Features\ObservationStation; use NWS\Exceptions\InvalidRequestException; +use NWS\Exceptions\ApiNotOkException; use DateTimeZone; class Api @@ -114,7 +115,7 @@ public function get($url): object|bool } // key-ify the request URL to use as the unique ID in our cache - $key = urlencode($url); + $key = str_slug($url); // if there is a value in the cache for the given URL, return the cached data if($this->cache->has($key)) { @@ -151,6 +152,16 @@ public function ok(): bool return strtolower($this->status()) == "ok"; } + public function ensureApiIsOk(): self + { + if(!$this->ok()) { + $status = $this->status(); + throw new ApiNotOkException("NWS API is not OK: {$status}"); + } + + return $this; + } + public function getLocation(float $lat = null, float $lon = null, string $observation_station = null, string $forecast_office = null): Point|ObservationStation|ForecastOffice { if($lat && $lon) { diff --git a/src/functions.php b/src/functions.php index 7da36a6..b04df1b 100644 --- a/src/functions.php +++ b/src/functions.php @@ -1,18 +1,5 @@ true, - 'false' => false, - 'null' => null, - default => $env - }; - - return $env; -} - function stripos_array($haystack, $needles) { foreach($needles as $needle) { if(($res = stripos($haystack, $needle)) !== false) {