Skip to content
Merged

1.x #49

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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ $openWeatherMap = new OpenWeatherMap(
);

// Get current weather by coordinate (latitude, longitude)
$currentWeather = $openWeatherMap->weather->getCurrent(50, 50);
$currentWeather = $openWeatherMap->weather()->getCurrent(50, 50);
// Show current temperature
echo $currentWeather->getTemperature();
```
Expand Down
2 changes: 1 addition & 1 deletion docs/01-usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ $openWeatherMap = new OpenWeatherMap(
);

// Get current weather by coordinate (latitude, longitude)
$currentWeather = $openWeatherMap->weather->getCurrent(50, 50);
$currentWeather = $openWeatherMap->weather()->getCurrent(50, 50);
// Show current temperature
echo $currentWeather->getTemperature();
```
14 changes: 7 additions & 7 deletions docs/02-configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ It is possible to change the cache duration per request:

```php
// Response will be cached for 1 hour
$currentWeather = $openWeatherMap->weather
$currentWeather = $openWeatherMap->weather()
->withCacheTtl(3600)
->getCurrent(50, 50);
```
Expand Down Expand Up @@ -244,20 +244,20 @@ $openWeatherMap = new OpenWeatherMap(

// Using applicationKey as an example,
// but getters and setters are available for all options
$openWeatherMap->config->getApplicationKey();
$openWeatherMap->config->setApplicationKey('newappkey');
$openWeatherMap->config()->getApplicationKey();
$openWeatherMap->config()->setApplicationKey('newappkey');
```

Just take into account that any change will affect any subsequent request globally:

```php
// Using default 'metric' unit system
$openWeatherMap->weather->getCurrent(50, 50);
$openWeatherMap->weather()->getCurrent(50, 50);

// Set new unit system
$openWeatherMap->config->setUnitSystem(UnitSystem::IMPERIAL);
$openWeatherMap->config()->setUnitSystem(UnitSystem::IMPERIAL);

// Using 'imperial' unit system
$openWeatherMap->weather->getCurrent(50, 50);
$openWeatherMap->weather->getForecast(50, 50);
$openWeatherMap->weather()->getCurrent(50, 50);
$openWeatherMap->weather()->getForecast(50, 50);
```
28 changes: 14 additions & 14 deletions docs/03-supported-apis.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ Get current and forecast (minutely, hourly and daily) weather data.
Returns a [`OneCall`](05-objects.md#onecall) object:

```php
$weather = $openWeatherMap->oneCall->getWeather(50, 50);
$weather = $openWeatherMap->oneCall()->getWeather(50, 50);

echo $weather->getCurrent()->getTemperature();
```
Expand All @@ -52,7 +52,7 @@ Get weather data from a single moment in the past.
Returns a [`WeatherLocation`](05-objects.md#weatherlocation) object:

```php
$weather = $openWeatherMap->oneCall->getHistoryMoment(50, 50, new \DateTime('2023-01-01 12:00:00'));
$weather = $openWeatherMap->oneCall()->getHistoryMoment(50, 50, new \DateTime('2023-01-01 12:00:00'));

echo $weather->getTemperature();
```
Expand All @@ -68,7 +68,7 @@ Get aggregated weather data from a single day in the past.
Returns a [`WeatherAggregate`](05-objects.md#weatheraggregate) object:

```php
$weather = $openWeatherMap->oneCall->getHistoryAggregate(50, 50, new \DateTime('1985-07-19'));
$weather = $openWeatherMap->oneCall()->getHistoryAggregate(50, 50, new \DateTime('1985-07-19'));

echo $weather->getTemperature();
```
Expand All @@ -86,7 +86,7 @@ Get current weather data.
Returns a [`WeatherLocation`](05-objects.md#weatherlocation-1) object:

```php
$weather = $openWeatherMap->weather->getCurrent(50, 50);
$weather = $openWeatherMap->weather()->getCurrent(50, 50);

echo $weather->getTemperature();
```
Expand All @@ -104,7 +104,7 @@ Returns a [`WeatherLocationList`](05-objects.md#weatherlocationlist) object:
```php
// Since it returns 3-hour steps,
// passing 8 as the numResults means it will return results for the next 24 hours
$weatherForecast = $openWeatherMap->weather->getForecast(50, 50, 8);
$weatherForecast = $openWeatherMap->weather()->getForecast(50, 50, 8);

foreach ($weatherForecast->getList() as $weather) {
echo $weather->getDateTime()->format('Y-m-d H:i:s');
Expand All @@ -125,7 +125,7 @@ Get current air pollution data.
Returns a [`AirPollutionLocation`](05-objects.md#airpollutionlocation) object:

```php
$airPollution = $openWeatherMap->airPollution->getCurrent(50, 50);
$airPollution = $openWeatherMap->airPollution()->getCurrent(50, 50);

echo $airPollution->getAirQuality()->getQualitativeName();
echo $airPollution->getCarbonMonoxide();
Expand All @@ -142,7 +142,7 @@ Get air pollution forecast data per 1-hour for the next 24 hours.
Returns a [`AirPollutionLocationList`](05-objects.md#airpollutionlocationlist) object:

```php
$airPollutionForecast = $openWeatherMap->airPollution->getForecast(50, 50);
$airPollutionForecast = $openWeatherMap->airPollution()->getForecast(50, 50);

foreach ($airPollutionForecast->getList() as $airPollution) {
echo $airPollution->getDateTime()->format('Y-m-d H:i:s');
Expand All @@ -164,7 +164,7 @@ Returns a [`AirPollutionLocationList`](05-objects.md#airpollutionlocationlist) o
```php
$startDate = new \DateTime('-7 days'); // 7 days ago
$endDate = new \DateTime('-6 days'); // 6 days ago
$airPollutionHistory = $openWeatherMap->airPollution->getHistory(50, 50, $startDate, $endDate);
$airPollutionHistory = $openWeatherMap->airPollution()->getHistory(50, 50, $startDate, $endDate);

foreach ($airPollutionHistory->getList() as $airPollution) {
echo $airPollution->getDateTime()->format('Y-m-d H:i:s');
Expand All @@ -189,7 +189,7 @@ Get locations data by location name.
Returns an array of [`Location`](05-objects.md#location) objects:

```php
$locations = $openWeatherMap->geocoding->getByLocationName('lisbon');
$locations = $openWeatherMap->geocoding()->getByLocationName('lisbon');

foreach ($locations as $location) {
echo $location->getName();
Expand All @@ -208,7 +208,7 @@ Get location data by zip/post code.
Returns a [`ZipCodeLocation`](05-objects.md#zipcodelocation) object:

```php
$location = $openWeatherMap->geocoding->getByZipCode('1000-001', 'pt');
$location = $openWeatherMap->geocoding()->getByZipCode('1000-001', 'pt');

echo $location->getName();
```
Expand All @@ -227,7 +227,7 @@ Get locations data by coordinate.
Returns an array of [`Location`](05-objects.md#location) objects:

```php
$locations = $openWeatherMap->geocoding->getByCoordinate(50, 50);
$locations = $openWeatherMap->geocoding()->getByCoordinate(50, 50);

foreach ($locations as $location) {
echo $location->getName();
Expand All @@ -251,7 +251,7 @@ Only available for [`OneCall`](#one-call) and [`Weather`](#weather) APIs.
use ProgrammatorDev\OpenWeatherMap\UnitSystem\UnitSystem;

// Uses 'imperial' unit system for this request alone
$openWeatherMap->weather
$openWeatherMap->weather()
->withUnitSystem(UnitSystem::IMPERIAL)
->getCurrent(50, 50);
```
Expand All @@ -270,7 +270,7 @@ Only available for [`OneCall`](#one-call) and [`Weather`](#weather) APIs.
use ProgrammatorDev\OpenWeatherMap\Language\Language

// Uses 'pt' language for this request alone
$openWeatherMap->weather
$openWeatherMap->weather()
->withLanguage(Language::PORTUGUESE)
->getCurrent(50, 50);
```
Expand All @@ -296,7 +296,7 @@ Available for all APIs if `cache` is enabled in the [configuration](02-configura
use ProgrammatorDev\OpenWeatherMap\Language\Language

// Cache will be saved for 1 hour for this request alone
$openWeatherMap->weather
$openWeatherMap->weather()
->withCacheTtl(3600)
->getCurrent(50, 50);
```
10 changes: 5 additions & 5 deletions docs/04-error-handling.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ use ProgrammatorDev\OpenWeatherMap\Exception\UnauthorizedException;
use ProgrammatorDev\OpenWeatherMap\Exception\UnexpectedErrorException;

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

$weather = $openWeatherMap->oneCall->getWeather(
$weather = $openWeatherMap->oneCall()->getWeather(
$location->getCoordinate()->getLatitude(),
$location->getCoordinate()->getLongitude()
);
Expand Down Expand Up @@ -57,9 +57,9 @@ To catch all API errors with a single exception, `ApiErrorException` is availabl
use ProgrammatorDev\OpenWeatherMap\Exception\ApiErrorException;

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

$weather = $openWeatherMap->oneCall->getWeather(
$weather = $openWeatherMap->oneCall()->getWeather(
$location->getCoordinate()->getLatitude(),
$location->getCoordinate()->getLongitude()
);
Expand All @@ -80,7 +80,7 @@ use ProgrammatorDev\YetAnotherPhpValidator\Exception\ValidationException;

try {
// An invalid latitude value is given
$weather = $openWeatherMap->weather->getCurrent(999, 50);
$weather = $openWeatherMap->weather()->getCurrent(999, 50);
}
catch (ValidationException $exception) {
// Should print:
Expand Down
7 changes: 7 additions & 0 deletions src/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@

class Config
{
private string $baseUrl = 'https://api.openweathermap.org';

private array $options;

public function __construct(array $options = [])
Expand Down Expand Up @@ -50,6 +52,11 @@ private function resolveOptions(array $options): array
return $resolver->resolve($options);
}

public function getBaseUrl(): string
{
return $this->baseUrl;
}

public function getApplicationKey(): string
{
return $this->options['applicationKey'];
Expand Down
27 changes: 11 additions & 16 deletions src/Endpoint/AbstractEndpoint.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
use Http\Client\Common\Plugin\LoggerPlugin;
use Http\Client\Exception;
use ProgrammatorDev\OpenWeatherMap\Config;
use ProgrammatorDev\OpenWeatherMap\Endpoint\Util\WithCacheTtlTrait;
use ProgrammatorDev\OpenWeatherMap\Endpoint\Util\CacheTtlTrait;
use ProgrammatorDev\OpenWeatherMap\Entity\Error;
use ProgrammatorDev\OpenWeatherMap\Exception\BadRequestException;
use ProgrammatorDev\OpenWeatherMap\Exception\NotFoundException;
Expand All @@ -20,12 +20,11 @@
use Psr\Cache\CacheItemPoolInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\UriInterface;
use Psr\Log\LoggerInterface;

class AbstractEndpoint
{
use WithCacheTtlTrait;
use CacheTtlTrait;

private Config $config;

Expand All @@ -43,7 +42,7 @@ class AbstractEndpoint

public function __construct(protected OpenWeatherMap $api)
{
$this->config = $this->api->config;
$this->config = $this->api->config();

$this->httpClientBuilder = $this->config->getHttpClientBuilder();
$this->cache = $this->config->getCache();
Expand All @@ -62,7 +61,7 @@ public function __construct(protected OpenWeatherMap $api)
*/
protected function sendRequest(
string $method,
UriInterface|string $baseUrl,
string $path,
array $query = [],
array $headers = [],
StreamInterface|string $body = null
Expand All @@ -72,13 +71,13 @@ protected function sendRequest(

$response = $this->httpClientBuilder->getHttpClient()->send(
$method,
$this->buildUrl($baseUrl, $query),
$this->buildUrl($path, $query),
$headers,
$body
);

if (($statusCode = $response->getStatusCode()) >= 400) {
$this->handleResponseErrors($response, $statusCode);
if ($response->getStatusCode() >= 400) {
$this->handleResponseErrors($response);
}

return ResponseMediator::toArray($response);
Expand Down Expand Up @@ -113,13 +112,13 @@ private function configurePlugins(): void
* @throws UnauthorizedException
* @throws BadRequestException
*/
private function handleResponseErrors(ResponseInterface $response, int $statusCode): void
private function handleResponseErrors(ResponseInterface $response): void
{
$error = new Error(
ResponseMediator::toArray($response)
);

match ($statusCode) {
match ($response->getStatusCode()) {
400 => throw new BadRequestException($error),
401 => throw new UnauthorizedException($error),
404 => throw new NotFoundException($error),
Expand All @@ -128,17 +127,13 @@ private function handleResponseErrors(ResponseInterface $response, int $statusCo
};
}

private function buildUrl(UriInterface|string $baseUrl, array $query): string
private function buildUrl(string $path, array $query): string
{
if ($baseUrl instanceof UriInterface) {
$baseUrl = (string) $baseUrl;
}

// Add application key to all requests
$query = $query + [
'appid' => $this->config->getApplicationKey()
];

return \sprintf('%s?%s', $baseUrl, http_build_query($query));
return \sprintf('%s%s?%s', $this->config->getBaseUrl(), $path, http_build_query($query));
}
}
12 changes: 3 additions & 9 deletions src/Endpoint/AirPollutionEndpoint.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,6 @@

class AirPollutionEndpoint extends AbstractEndpoint
{
private string $urlAirPollution = 'https://api.openweathermap.org/data/2.5/air_pollution';

private string $urlAirPollutionForecast = 'https://api.openweathermap.org/data/2.5/air_pollution/forecast';

private string $urlAirPollutionHistory = 'https://api.openweathermap.org/data/2.5/air_pollution/history';

/**
* @throws Exception
* @throws BadRequestException
Expand All @@ -37,7 +31,7 @@ public function getCurrent(float $latitude, float $longitude): AirPollutionLocat

$data = $this->sendRequest(
method: 'GET',
baseUrl: $this->urlAirPollution,
path: '/data/2.5/air_pollution',
query: [
'lat' => $latitude,
'lon' => $longitude
Expand All @@ -63,7 +57,7 @@ public function getForecast(float $latitude, float $longitude): AirPollutionLoca

$data = $this->sendRequest(
method: 'GET',
baseUrl: $this->urlAirPollutionForecast,
path: '/data/2.5/air_pollution/forecast',
query: [
'lat' => $latitude,
'lon' => $longitude
Expand Down Expand Up @@ -98,7 +92,7 @@ public function getHistory(

$data = $this->sendRequest(
method: 'GET',
baseUrl: $this->urlAirPollutionHistory,
path: '/data/2.5/air_pollution/history',
query: [
'lat' => $latitude,
'lon' => $longitude,
Expand Down
Loading