Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
"php": ">=8.1",
"myclabs/deep-copy": "^1.13",
"programmatordev/php-api-sdk": "^2.0",
"programmatordev/yet-another-php-validator": "^1.3",
"symfony/options-resolver": "^6.4|^7.3"
},
"require-dev": {
Expand Down
41 changes: 6 additions & 35 deletions docs/04-error-handling.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
# Error Handling

- [API Errors](#api-errors)
- [Validation Errors](#validation-errors)

## API Errors

To handle API response errors, multiple exceptions are provided. You can see all available in the following example:
Expand All @@ -15,13 +12,9 @@ use ProgrammatorDev\OpenWeatherMap\Exception\UnauthorizedException;
use ProgrammatorDev\OpenWeatherMap\Exception\UnexpectedErrorException;

try {
$location = $api->geocoding()->getByZipCode('1000-001', 'pt');
$coordinate = $location->getCoordinate();
// ...

$weather = $api->oneCall()->getWeather(
$coordinate->getLatitude(),
$coordinate->getLongitude()
);
$weather = $api->oneCall()->getWeather($latitude, $longitude);
}
// bad request to the API
catch (BadRequestException $exception) {
Expand All @@ -33,7 +26,7 @@ catch (UnauthorizedException $exception) {
echo $exception->getCode(); // 401
echo $exception->getMessage();
}
// resource not found
// resource not found,
// for example, when trying to get a location with a zip code that does not exist
catch (NotFoundException $exception) {
echo $exception->getCode(); // 404
Expand All @@ -57,35 +50,13 @@ To catch all API errors with a single exception, `ApiErrorException` is availabl
use ProgrammatorDev\OpenWeatherMap\Exception\ApiErrorException;

try {
$location = $api->geocoding()->getByZipCode('1000-001', 'pt');
$coordinate = $location->getCoordinate();

$weather = $api->oneCall()->getWeather(
$coordinate->getLatitude(),
$coordinate->getLongitude()
);
// ...

$weather = $api->oneCall()->getWeather($latitude, $longitude);
}
// catches all API response errors
catch (ApiErrorException $exception) {
echo $exception->getCode();
echo $exception->getMessage();
}
```

## Validation Errors

To catch invalid input data (like an out of range coordinate, blank location name, etc.), the `ValidationException` is available:

```php
use ProgrammatorDev\Validator\Exception\ValidationException;

try {
// an invalid latitude value is given
$weather = $api->weather()->getCurrent(999, 50);
}
catch (ValidationException $exception) {
// should print:
// The latitude value should be between -90 and 90, 999 given.
echo $exception->getMessage();
}
```
2 changes: 1 addition & 1 deletion src/Entity/Icon.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ class Icon
public function __construct(array $data)
{
$this->id = $data['icon'];
$this->url = \sprintf('https://openweathermap.org/img/wn/%s@4x.png', $this->id);
$this->url = sprintf('https://openweathermap.org/img/wn/%s@4x.png', $this->id);
}

public function getId(): string
Expand Down
4 changes: 2 additions & 2 deletions src/OpenWeatherMap.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ private function configureApi(): void

// if there was a response with an error status code
if ($statusCode >= 400) {
$error = \json_decode($response->getBody()->getContents(), true);
$error = json_decode($response->getBody()->getContents(), true);

match ($statusCode) {
400 => throw new BadRequestException($error),
Expand All @@ -101,7 +101,7 @@ private function configureApi(): void
$this->addResponseContentsListener(function(ResponseContentsEvent $event) {
// decode json string response into an array
$contents = $event->getContents();
$contents = \json_decode($contents, true);
$contents = json_decode($contents, true);

$event->setContents($contents);
});
Expand Down
11 changes: 0 additions & 11 deletions src/Resource/AirPollutionResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,17 @@
use ProgrammatorDev\Api\Method;
use ProgrammatorDev\OpenWeatherMap\Entity\AirPollution\AirPollution;
use ProgrammatorDev\OpenWeatherMap\Entity\AirPollution\AirPollutionCollection;
use ProgrammatorDev\Validator\Exception\ValidationException;
use Psr\Http\Client\ClientExceptionInterface;

class AirPollutionResource extends Resource
{
/**
* Get access to current air pollution data
*
* @throws ValidationException
* @throws ClientExceptionInterface
*/
public function getCurrent(float $latitude, float $longitude): AirPollution
{
$this->validateCoordinate($latitude, $longitude);

$data = $this->api->request(
method: Method::GET,
path: '/data/2.5/air_pollution',
Expand All @@ -35,13 +31,10 @@ public function getCurrent(float $latitude, float $longitude): AirPollution
/**
* Get access to air pollution forecast data per hour
*
* @throws ValidationException
* @throws ClientExceptionInterface
*/
public function getForecast(float $latitude, float $longitude): AirPollutionCollection
{
$this->validateCoordinate($latitude, $longitude);

$data = $this->api->request(
method: Method::GET,
path: '/data/2.5/air_pollution/forecast',
Expand All @@ -57,7 +50,6 @@ public function getForecast(float $latitude, float $longitude): AirPollutionColl
/**
* Get access to historical air pollution data per hour between two dates
*
* @throws ValidationException
* @throws ClientExceptionInterface
*/
public function getHistory(
Expand All @@ -67,9 +59,6 @@ public function getHistory(
\DateTimeInterface $endDate
): AirPollutionCollection
{
$this->validateCoordinate($latitude, $longitude);
$this->validateDateOrder($startDate, $endDate);

$utcTimezone = new \DateTimeZone('UTC');

$data = $this->api->request(
Expand Down
17 changes: 2 additions & 15 deletions src/Resource/GeocodingResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
use ProgrammatorDev\OpenWeatherMap\Entity\Geocoding\ZipLocation;
use ProgrammatorDev\OpenWeatherMap\Entity\Location;
use ProgrammatorDev\OpenWeatherMap\Util\EntityTrait;
use ProgrammatorDev\Validator\Exception\ValidationException;
use Psr\Http\Client\ClientExceptionInterface;

class GeocodingResource extends Resource
Expand All @@ -19,14 +18,10 @@ class GeocodingResource extends Resource
* Get geographical coordinates (latitude, longitude) by using the name of the location (city name or area name)
*
* @return Location[]
* @throws ValidationException
* @throws ClientExceptionInterface
*/
public function getByLocationName(string $locationName, int $numResults = self::NUM_RESULTS): array
{
$this->validateQuery($locationName, 'locationName');
$this->validatePositive($numResults, 'numResults');

$data = $this->api->request(
method: Method::GET,
path: '/geo/1.0/direct',
Expand All @@ -42,16 +37,12 @@ public function getByLocationName(string $locationName, int $numResults = self::
/**
* Get geographical coordinates (latitude, longitude) by using the zip/postal code
*
* @throws ValidationException
* @throws ClientExceptionInterface
*/
public function getByZipCode(string $zipCode, string $countryCode): ZipLocation
{
$this->validateQuery($zipCode, 'zipCode');
$this->validateCountryCode($countryCode);

$data = $this->api->request(
method: 'GET',
method: Method::GET,
path: '/geo/1.0/zip',
query: [
'zip' => \sprintf('%s,%s', $zipCode, $countryCode)
Expand All @@ -62,17 +53,13 @@ public function getByZipCode(string $zipCode, string $countryCode): ZipLocation
}

/**
* Get name of the location (city name or area name) by using geographical coordinates (latitude, longitude)
* Get the name of the location (city name or area name) by using geographical coordinates (latitude, longitude)
*
* @return Location[]
* @throws ValidationException
* @throws ClientExceptionInterface
*/
public function getByCoordinate(float $latitude, float $longitude, int $numResults = self::NUM_RESULTS): array
{
$this->validateCoordinate($latitude, $longitude);
$this->validatePositive($numResults, 'numResults');

$data = $this->api->request(
method: Method::GET,
path: '/geo/1.0/reverse',
Expand Down
10 changes: 0 additions & 10 deletions src/Resource/OneCallResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
use ProgrammatorDev\OpenWeatherMap\Entity\OneCall\WeatherSummary;
use ProgrammatorDev\OpenWeatherMap\Resource\Util\LanguageTrait;
use ProgrammatorDev\OpenWeatherMap\Resource\Util\UnitSystemTrait;
use ProgrammatorDev\Validator\Exception\ValidationException;
use Psr\Http\Client\ClientExceptionInterface;

class OneCallResource extends Resource
Expand All @@ -20,13 +19,10 @@ class OneCallResource extends Resource
* Get access to current weather, minute forecast for 1 hour, hourly forecast for 48 hours,
* daily forecast for 8 days and government weather alerts
*
* @throws ValidationException
* @throws ClientExceptionInterface
*/
public function getWeather(float $latitude, float $longitude): Weather
{
$this->validateCoordinate($latitude, $longitude);

$data = $this->api->request(
method: Method::GET,
path: '/data/3.0/onecall',
Expand All @@ -42,13 +38,10 @@ public function getWeather(float $latitude, float $longitude): Weather
/**
* Get access to weather data for any datetime
*
* @throws ValidationException
* @throws ClientExceptionInterface
*/
public function getWeatherByDate(float $latitude, float $longitude, \DateTimeInterface $dateTime): WeatherMoment
{
$this->validateCoordinate($latitude, $longitude);

$utcTimezone = new \DateTimeZone('UTC');

$data = $this->api->request(
Expand All @@ -67,13 +60,10 @@ public function getWeatherByDate(float $latitude, float $longitude, \DateTimeInt
/**
* Get access to aggregated weather data for a particular date
*
* @throws ValidationException
* @throws ClientExceptionInterface
*/
public function getWeatherSummaryByDate(float $latitude, float $longitude, \DateTimeInterface $date): WeatherSummary
{
$this->validateCoordinate($latitude, $longitude);

$data = $this->api->request(
method: Method::GET,
path: '/data/3.0/onecall/day_summary',
Expand Down
2 changes: 0 additions & 2 deletions src/Resource/Resource.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,10 @@

use ProgrammatorDev\OpenWeatherMap\OpenWeatherMap;
use ProgrammatorDev\OpenWeatherMap\Resource\Util\CacheTrait;
use ProgrammatorDev\OpenWeatherMap\Resource\Util\ValidationTrait;

class Resource
{
use CacheTrait;
use ValidationTrait;

public function __construct(protected OpenWeatherMap $api) {}
}
8 changes: 0 additions & 8 deletions src/Resource/Util/UnitSystemTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,12 @@

namespace ProgrammatorDev\OpenWeatherMap\Resource\Util;

use ProgrammatorDev\Validator\Exception\ValidationException;
use function DeepCopy\deep_copy;

trait UnitSystemTrait
{
use ValidationTrait;

/**
* @throws ValidationException
*/
public function withUnitSystem(string $unitSystem): static
{
$this->validateUnitSystem($unitSystem);

$clone = deep_copy($this, true);
$clone->api->addQueryDefault('units', $unitSystem);

Expand Down
71 changes: 0 additions & 71 deletions src/Resource/Util/ValidationTrait.php

This file was deleted.

Loading