From 8963f29c46aad828d081ea0210136093fd25c4d6 Mon Sep 17 00:00:00 2001 From: BJ Hansen Date: Tue, 2 Jul 2024 21:47:54 -0500 Subject: [PATCH] Added a new Exception for Cache failures; added new methods to the main Api class and to the Alert class --- src/Api.php | 21 +++++++++++++++++---- src/Exceptions/CacheException.php | 10 ++++++++++ src/Features/Alert.php | 19 +++++++++++++++++++ 3 files changed, 46 insertions(+), 4 deletions(-) create mode 100644 src/Exceptions/CacheException.php diff --git a/src/Api.php b/src/Api.php index 1ea7da7..ed4cf49 100644 --- a/src/Api.php +++ b/src/Api.php @@ -9,6 +9,7 @@ use NWS\Features\ObservationStation; use NWS\Exceptions\InvalidRequestException; use NWS\Exceptions\ApiNotOkException; +use NWS\Exceptions\CacheException; use DateTimeZone; class Api @@ -26,17 +27,28 @@ class Api public function __construct(string $domain, string $email) { // derive our user agent for the API requests - $this->user_agent = "($domain, $email)"; + $this->setUserAgent($domain, $email); // build up our HTTP client for making requests to the API $this->client = new HttpClient([ 'http_errors' => false, 'headers' => [ - 'User-Agent' => $this->user_agent + 'User-Agent' => $this->getUserAgent() ] ]); } + public function getUserAgent(): string + { + return $this->user_agent; + } + + public function setUserAgent(string $domain, string $email): self + { + $this->user_agent = "({$domain}, {$email})"; + return $this; + } + public function getCacheLifetime(): int { return $this->cache_lifetime; @@ -78,13 +90,13 @@ public function setBaseUrl(string $base_url): self return $this; } - public function clearCache(): bool|self + public function clearCache(): self { if($this->cache->clear()) { return $this; } - return false; + throw new CacheException("Failed to clear the cache!"); } public function setTimezone(string $timezone): self @@ -101,6 +113,7 @@ public function getTimezone(): DateTimeZone public function get($url): object|bool { // the user did not opt to use the cache + // so make a direct request to the URL if(!$this->cache) { $http_request = $this->client->get($url); $http_response_code = $http_request->getStatusCode(); diff --git a/src/Exceptions/CacheException.php b/src/Exceptions/CacheException.php new file mode 100644 index 0000000..fc68535 --- /dev/null +++ b/src/Exceptions/CacheException.php @@ -0,0 +1,10 @@ +properties_instruction(); } + public function affectedZones(): Collection + { + $return = []; + + $zones = $this->properties_affectedZones(); + foreach($zones as $zone_url) { + $return[] = new ForecastZone($this->api->get($zone_url), $this->api); + } + + return collect($return); + } + + public function affectedZone(int $i = 0): ForecastZone + { + $zone = $this->properties_affectedZones()[$i]; + return new ForecastZone($this->api->get($zone), $this->api); + } + public function response(): AlertResponse { return AlertResponse::fromName($this->properties_response());