Skip to content
Merged

1.x #42

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 composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "programmatordev/openweathermap-php-api",
"description": "OpenWeatherMap PHP library that provides convenient access to the OpenWeatherMap API",
"type": "library",
"keywords": ["OpenWeatherMap", "API", "PHP", "SDK", "PSR-18", "PSR-17", "PSR-6", "PSR-3"],
"keywords": ["OpenWeatherMap", "API", "PHP", "PHP8", "SDK", "PSR-18", "PSR-17", "PSR-6", "PSR-3"],
"license": "MIT",
"authors": [
{
Expand Down
10 changes: 8 additions & 2 deletions docs/03-supported-apis.md
Original file line number Diff line number Diff line change
Expand Up @@ -278,10 +278,16 @@ $openWeatherMap->getWeather()
#### `withCacheTtl`

```php
withCacheTtl(?int $time): self
withCacheTtl(int $seconds): self
```

Makes a request and saves into cache with the provided time duration value (in seconds).
Makes a request and saves into cache for the provided duration in seconds.

If `0` seconds is provided, the request will not be cached.

> **Note**
> Setting cache to `0` seconds will **not** invalidate any existing cache.

Check the [Cache TTL](02-configuration.md#cache-ttl) section for more information regarding default values.

Available for all APIs if `cache` is enabled in the [configuration](02-configuration.md#cache).
Expand Down
2 changes: 1 addition & 1 deletion docs/05-objects.md
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@

### AirPollutionLocationList

`getCoordinate()`: `float`
`getCoordinate()`: [`Coordinate`](#coordinate)

`getList()`: [`AirPollution[]`](#airpollution)

Expand Down
15 changes: 9 additions & 6 deletions src/Endpoint/AbstractEndpoint.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ class AbstractEndpoint

protected string $language;

protected ?int $cacheTtl = 60 * 10; // 10 minutes
protected int $cacheTtl = 60 * 10; // 10 minutes

public function __construct(protected OpenWeatherMap $api)
{
Expand Down Expand Up @@ -70,8 +70,12 @@ protected function sendRequest(
{
$this->configurePlugins();

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

if (($statusCode = $response->getStatusCode()) >= 400) {
$this->handleResponseErrors($response, $statusCode);
Expand All @@ -84,14 +88,13 @@ private function configurePlugins(): void
{
// Plugin order is important
// CachePlugin should come first, otherwise the LoggerPlugin will log requests even if they are cached

if ($this->cache !== null) {
$this->httpClientBuilder->addPlugin(
new CachePlugin($this->cache, $this->httpClientBuilder->getStreamFactory(), [
'default_ttl' => $this->cacheTtl,
'cache_lifetime' => 0,
'cache_listeners' => ($this->logger !== null)
? [new LoggerCacheListener($this->logger)]
: []
'cache_listeners' => ($this->logger !== null) ? [new LoggerCacheListener($this->logger)] : []
])
);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Endpoint/GeocodingEndpoint.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class GeocodingEndpoint extends AbstractEndpoint

private string $urlGeocodingReverse = 'https://api.openweathermap.org/geo/1.0/reverse';

protected ?int $cacheTtl = 60 * 60 * 24 * 30; // 30 days
protected int $cacheTtl = 60 * 60 * 24 * 30; // 30 days

/**
* @return Location[]
Expand Down
6 changes: 3 additions & 3 deletions src/Endpoint/Util/WithCacheTtlTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@

trait WithCacheTtlTrait
{
public function withCacheTtl(?int $time): static
public function withCacheTtl(int $seconds): static
{
$clone = clone $this;
$clone->cacheTtl = $time;
$clone->cacheTtl = $seconds;

return $clone;
}

public function getCacheTtl(): ?int
public function getCacheTtl(): int
{
return $this->cacheTtl;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Test/AbstractTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ protected function setUp(): void
$this->mockHttpClient = new Client();
}

protected function getApi(): OpenWeatherMap
protected function givenApi(): OpenWeatherMap
{
return new OpenWeatherMap(
new Config([
Expand Down
52 changes: 52 additions & 0 deletions tests/AbstractEndpointTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

namespace ProgrammatorDev\OpenWeatherMap\Test;

use Nyholm\Psr7\Response;
use ProgrammatorDev\OpenWeatherMap\Endpoint\AbstractEndpoint;
use ProgrammatorDev\OpenWeatherMap\OpenWeatherMap;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Log\LoggerInterface;

class AbstractEndpointTest extends AbstractTest
{
public function testAbstractEndpointWithCache()
{
$this->mockHttpClient->addResponse(
new Response(body: '[]')
);

$cache = $this->createMock(CacheItemPoolInterface::class);
$cache->expects($this->once())->method('save');

$api = $this->givenApi();
$api->getConfig()->setCache($cache);

$this->mockSendRequest($api);
}

public function testAbstractEndpointWithLogger()
{
$this->mockHttpClient->addResponse(
new Response(body: '[]')
);

$logger = $this->createMock(LoggerInterface::class);
$logger->expects($this->atLeastOnce())->method('info');

$api = $this->givenApi();
$api->getConfig()->setLogger($logger);

$this->mockSendRequest($api);
}

private function mockSendRequest(OpenWeatherMap $api): void
{
// Using ReflectionClass to be able to call the *protected* sendRequest method
// (otherwise it would not be possible)
$endpoint = new AbstractEndpoint($api);
$reflectionClass = new \ReflectionClass($endpoint);
$sendRequest = $reflectionClass->getMethod('sendRequest');
$sendRequest->invokeArgs($endpoint, ['GET', 'https://mock.test']);
}
}
49 changes: 33 additions & 16 deletions tests/AirPollutionEndpointTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,18 @@

use Nyholm\Psr7\Response;
use PHPUnit\Framework\Attributes\DataProviderExternal;
use ProgrammatorDev\OpenWeatherMap\Endpoint\AirPollutionEndpoint;
use ProgrammatorDev\OpenWeatherMap\Entity\AirPollution\AirPollution;
use ProgrammatorDev\OpenWeatherMap\Entity\AirPollution\AirPollutionLocationList;
use ProgrammatorDev\OpenWeatherMap\Entity\AirPollution\AirQuality;
use ProgrammatorDev\OpenWeatherMap\Entity\AirPollution\AirPollutionLocation;
use ProgrammatorDev\OpenWeatherMap\Entity\Coordinate;
use ProgrammatorDev\OpenWeatherMap\Entity\Location;
use ProgrammatorDev\OpenWeatherMap\Test\DataProvider\InvalidParamDataProvider;

class AirPollutionEndpointTest extends AbstractTest
{
// --- CURRENT ---

public function testAirPollutionGetCurrent()
{
$this->mockHttpClient->addResponse(
Expand All @@ -23,17 +25,19 @@ public function testAirPollutionGetCurrent()
)
);

$response = $this->getApi()->getAirPollution()->getCurrent(38.7077507, -9.1365919);
$response = $this->givenApi()->getAirPollution()->getCurrent(50, 50);
$this->assertCurrentResponse($response);
}

#[DataProviderExternal(InvalidParamDataProvider::class, 'provideInvalidCoordinateData')]
public function testAirPollutionGetCurrentWithInvalidCoordinate(float $latitude, float $longitude, string $expectedException)
{
$this->expectException($expectedException);
$this->getApi()->getAirPollution()->getCurrent($latitude, $longitude);
$this->givenApi()->getAirPollution()->getCurrent($latitude, $longitude);
}

// --- FORECAST ---

public function testAirPollutionGetForecast()
{
$this->mockHttpClient->addResponse(
Expand All @@ -43,17 +47,19 @@ public function testAirPollutionGetForecast()
)
);

$response = $this->getApi()->getAirPollution()->getForecast(38.7077507, -9.1365919);
$response = $this->givenApi()->getAirPollution()->getForecast(50, 50);
$this->assertForecastResponse($response);
}

#[DataProviderExternal(InvalidParamDataProvider::class, 'provideInvalidCoordinateData')]
public function testAirPollutionGetForecastWithInvalidCoordinate(float $latitude, float $longitude, string $expectedException)
{
$this->expectException($expectedException);
$this->getApi()->getAirPollution()->getForecast($latitude, $longitude);
$this->givenApi()->getAirPollution()->getForecast($latitude, $longitude);
}

// --- HISTORY ---

public function testAirPollutionGetHistory()
{
$this->mockHttpClient->addResponse(
Expand All @@ -65,9 +71,9 @@ public function testAirPollutionGetHistory()

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

$response = $this->getApi()->getAirPollution()->getHistory(
38.7077507,
-9.1365919,
$response = $this->givenApi()->getAirPollution()->getHistory(
50,
50,
new \DateTimeImmutable('-5 days', $utcTimezone),
new \DateTimeImmutable('-4 days', $utcTimezone)
);
Expand All @@ -82,7 +88,7 @@ public function testAirPollutionGetHistoryWithInvalidCoordinate(float $latitude,
$startDate = new \DateTimeImmutable('-5 days');
$endDate = new \DateTimeImmutable('-4 days');

$this->getApi()->getAirPollution()->getHistory($latitude, $longitude, $startDate, $endDate);
$this->givenApi()->getAirPollution()->getHistory($latitude, $longitude, $startDate, $endDate);
}

#[DataProviderExternal(InvalidParamDataProvider::class, 'provideInvalidPastDateData')]
Expand All @@ -92,9 +98,9 @@ public function testAirPollutionGetHistoryWithInvalidPastStartDate(
)
{
$this->expectException($expectedException);
$this->getApi()->getAirPollution()->getHistory(
38.7077507,
-9.1365919,
$this->givenApi()->getAirPollution()->getHistory(
50,
50,
$startDate,
new \DateTimeImmutable('-5 days', new \DateTimeZone('UTC'))
);
Expand All @@ -107,9 +113,9 @@ public function testAirPollutionGetHistoryWithInvalidPastEndDate(
)
{
$this->expectException($expectedException);
$this->getApi()->getAirPollution()->getHistory(
38.7077507,
-9.1365919,
$this->givenApi()->getAirPollution()->getHistory(
50,
50,
new \DateTimeImmutable('-5 days', new \DateTimeZone('UTC')),
$endDate
);
Expand All @@ -123,9 +129,20 @@ public function testAirPollutionGetHistoryWithInvalidDateRange(
)
{
$this->expectException($expectedException);
$this->getApi()->getAirPollution()->getHistory(38.7077507, -9.1365919, $startDate, $endDate);
$this->givenApi()->getAirPollution()->getHistory(50, 50, $startDate, $endDate);
}

// --- ASSERT METHODS EXIST ---

public function testAirPollutionMethodsExist()
{
$this->assertSame(false, method_exists(AirPollutionEndpoint::class, 'withUnitSystem'));
$this->assertSame(false, method_exists(AirPollutionEndpoint::class, 'withLanguage'));
$this->assertSame(true, method_exists(AirPollutionEndpoint::class, 'withCacheTtl'));
}

// --- ASSERT RESPONSES ---

private function assertCurrentResponse(AirPollutionLocation $response): void
{
$this->assertInstanceOf(AirPollutionLocation::class, $response);
Expand Down
2 changes: 1 addition & 1 deletion tests/ApiErrorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public function testApiError(int $statusCode, string $expectedException)
);

$this->expectException($expectedException);
$this->getApi()->getWeather()->getCurrent(38.7077507, -9.1365919);
$this->givenApi()->getWeather()->getCurrent(38.7077507, -9.1365919);
}

public static function provideApiErrorData(): \Generator
Expand Down
10 changes: 4 additions & 6 deletions tests/ConfigTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

namespace ProgrammatorDev\OpenWeatherMap\Test;

use Monolog\Logger;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\DataProviderExternal;
use ProgrammatorDev\OpenWeatherMap\Config;
Expand All @@ -11,7 +10,6 @@
use ProgrammatorDev\YetAnotherPhpValidator\Exception\ValidationException;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
use Symfony\Component\OptionsResolver\Exception\MissingOptionsException;

Expand Down Expand Up @@ -45,8 +43,8 @@ public function testConfigWithOptions()
'unitSystem' => 'imperial',
'language' => 'pt',
'httpClientBuilder' => new HttpClientBuilder(),
'cache' => new FilesystemAdapter(),
'logger' => new Logger('test')
'cache' => $this->createMock(CacheItemPoolInterface::class),
'logger' => $this->createMock(LoggerInterface::class)
]);

$this->assertSame('newtestappkey', $config->getApplicationKey());
Expand Down Expand Up @@ -139,13 +137,13 @@ public function testConfigSetHttpClientBuilder()

public function testConfigSetCache()
{
$this->config->setCache(new FilesystemAdapter());
$this->config->setCache($this->createMock(CacheItemPoolInterface::class));
$this->assertInstanceOf(CacheItemPoolInterface::class, $this->config->getCache());
}

public function testConfigSetLogger()
{
$this->config->setLogger(new Logger('test'));
$this->config->setLogger($this->createMock(LoggerInterface::class));
$this->assertInstanceOf(LoggerInterface::class, $this->config->getLogger());
}
}
Loading