Skip to content

Commit d239115

Browse files
committed
Switch to PSR-6 cache implementation
1 parent cbcde07 commit d239115

File tree

12 files changed

+451
-363
lines changed

12 files changed

+451
-363
lines changed

Cmfcmf/OpenWeatherMap.php

Lines changed: 30 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717

1818
namespace Cmfcmf;
1919

20-
use Cmfcmf\OpenWeatherMap\AbstractCache;
2120
use Cmfcmf\OpenWeatherMap\CurrentWeather;
2221
use Cmfcmf\OpenWeatherMap\UVIndex;
2322
use Cmfcmf\OpenWeatherMap\CurrentWeatherGroup;
@@ -27,6 +26,7 @@
2726
use Cmfcmf\OpenWeatherMap\Fetcher\FileGetContentsFetcher;
2827
use Cmfcmf\OpenWeatherMap\WeatherForecast;
2928
use Cmfcmf\OpenWeatherMap\WeatherHistory;
29+
use Psr\Cache\CacheItemPoolInterface;
3030

3131
/**
3232
* Main class for the OpenWeatherMap-PHP-API. Only use this class.
@@ -74,14 +74,14 @@ class OpenWeatherMap
7474
private $uvIndexUrl = 'https://api.openweathermap.org/data/2.5/uvi';
7575

7676
/**
77-
* @var AbstractCache|bool $cache The cache to use.
77+
* @var CacheItemPoolInterface|null $cache The cache to use.
7878
*/
79-
private $cache = false;
79+
private $cache = null;
8080

8181
/**
8282
* @var int
8383
*/
84-
private $seconds;
84+
private $ttl;
8585

8686
/**
8787
* @var bool
@@ -101,41 +101,36 @@ class OpenWeatherMap
101101
/**
102102
* Constructs the OpenWeatherMap object.
103103
*
104-
* @param string $apiKey The OpenWeatherMap API key. Required.
105-
* @param null|FetcherInterface $fetcher The interface to fetch the data from OpenWeatherMap. Defaults to
106-
* CurlFetcher() if cURL is available. Otherwise defaults to
107-
* FileGetContentsFetcher() using 'file_get_contents()'.
108-
* @param bool|string $cache If set to false, caching is disabled. Otherwise this must be a class
109-
* extending AbstractCache. Defaults to false.
110-
* @param int $seconds How long weather data shall be cached. Default 10 minutes.
111-
*
112-
* @throws \Exception If $cache is neither false nor a valid callable extending Cmfcmf\OpenWeatherMap\Util\Cache.
104+
* @param string $apiKey The OpenWeatherMap API key. Required.
105+
* @param null|FetcherInterface $fetcher The interface to fetch the data from OpenWeatherMap. Defaults to
106+
* CurlFetcher() if cURL is available. Otherwise defaults to
107+
* FileGetContentsFetcher() using 'file_get_contents()'.
108+
* @param null|CacheItemPoolInterface $cache If set to null, caching is disabled. Otherwise this must be
109+
* a PSR 16-compatible cache instance.
110+
* @param int $ttl How long weather data shall be cached. Defaults to 10 minutes.
111+
* Only used if $cache is not null.
113112
*
114113
* @api
115114
*/
116-
public function __construct($apiKey, $fetcher = null, $cache = false, $seconds = 600)
115+
public function __construct($apiKey, $fetcher = null, $cache = null, $ttl = 600)
117116
{
118117
if (!is_string($apiKey) || empty($apiKey)) {
119118
throw new \InvalidArgumentException("You must provide an API key.");
120119
}
121120

122-
$this->apiKey = $apiKey;
123-
124-
if ($cache !== false && !($cache instanceof AbstractCache)) {
125-
throw new \InvalidArgumentException('The cache class must implement the FetcherInterface!');
121+
if ($cache !== null && !($cache instanceof CacheItemPoolInterface)) {
122+
throw new \InvalidArgumentException('The cache class must implement the \Psr\Cache\CacheItemPoolInterface!');
126123
}
127-
if (!is_numeric($seconds)) {
124+
if (!is_numeric($ttl)) {
128125
throw new \InvalidArgumentException('$seconds must be numeric.');
129126
}
130127
if (!isset($fetcher)) {
131128
$fetcher = (function_exists('curl_version')) ? new CurlFetcher() : new FileGetContentsFetcher();
132129
}
133-
if ($seconds == 0) {
134-
$cache = false;
135-
}
136130

131+
$this->apiKey = $apiKey;
137132
$this->cache = $cache;
138-
$this->seconds = $seconds;
133+
$this->ttl = $ttl;
139134
$this->fetcher = $fetcher;
140135
}
141136

@@ -576,18 +571,21 @@ public function wasCached()
576571
*/
577572
private function cacheOrFetchResult($url)
578573
{
579-
if ($this->cache !== false) {
580-
/** @var AbstractCache $cache */
581-
$cache = $this->cache;
582-
$cache->setSeconds($this->seconds);
583-
584-
if ($cache->isCached($url)) {
574+
if ($this->cache !== null) {
575+
$key = str_replace(
576+
["{", "}", "(", ")", "/", "\\", "@", ":"],
577+
["_", "_", "_", "_", "_", "_", "_", "_"],
578+
$url);
579+
$item = $this->cache->getItem($key);
580+
if ($item->isHit()) {
585581
$this->wasCached = true;
586-
return $cache->getCached($url);
582+
return $item->get();
587583
}
588584

589585
$result = $this->fetcher->fetch($url);
590-
$cache->setCached($url, $result);
586+
$item->set($result);
587+
$item->expiresAfter($this->ttl);
588+
$this->cache->save($item);
591589
} else {
592590
$result = $this->fetcher->fetch($url);
593591
}
@@ -712,7 +710,7 @@ private function parseXML($answer)
712710
/**
713711
* @param string $answer The content returned by OpenWeatherMap.
714712
*
715-
* @return \stdClass
713+
* @return \stdClass|array
716714
* @throws OWMException If the content isn't valid JSON.
717715
*/
718716
private function parseJson($answer)

Cmfcmf/OpenWeatherMap/AbstractCache.php

Lines changed: 0 additions & 69 deletions
This file was deleted.

Examples/Cache.php

Lines changed: 0 additions & 108 deletions
This file was deleted.

Examples/CurrentWeather.php

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,8 @@
3232
// Units (can be 'metric' or 'imperial' [default]):
3333
$units = 'metric';
3434

35-
// Get OpenWeatherMap object. Don't use caching (take a look into Example_Cache.php to see how it works).
36-
$owm = new OpenWeatherMap();
37-
$owm->setApiKey($myApiKey);
35+
// Get OpenWeatherMap object
36+
$owm = new OpenWeatherMap($myApiKey);
3837

3938
// Example 1: Get current temperature in Berlin.
4039
$weather = $owm->getWeather('Berlin', $units, $lang);

Examples/UVIndex.php

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
* @see http://openweathermap.org/appid
1616
*/
1717
use Cmfcmf\OpenWeatherMap;
18-
use Cmfcmf\OpenWeatherMap\Exception as OWMException;
1918

2019
require_once __DIR__ . '/bootstrap.php';
2120

@@ -33,8 +32,7 @@
3332
$units = 'metric';
3433

3534
// Get OpenWeatherMap object. Don't use caching (take a look into Example_Cache.php to see how it works).
36-
$owm = new OpenWeatherMap();
37-
$owm->setApiKey($myApiKey);
35+
$owm = new OpenWeatherMap($myApiKey);
3836

3937
// Example 1: Get current uv index in Berlin.
4038
$uvIndex = $owm->getCurrentUVIndex(52.520008, 13.404954);

README.md

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
OpenWeatherMap PHP API
22
======================
3-
A php API to retrieve and parse global weather data from
3+
A php API to retrieve and parse global weather data from
44
[OpenWeatherMap.org](http://www.OpenWeatherMap.org).
55
This library aims to normalise the provided data and remove some inconsistencies.
66
This library is neither maintained by OpenWeatherMap nor their official PHP API.
@@ -37,8 +37,7 @@ $lang = 'de';
3737
// Units (can be 'metric' or 'imperial' [default]):
3838
$units = 'metric';
3939

40-
// Create OpenWeatherMap object.
41-
// Don't use caching (take a look into Examples/Cache.php to see how it works).
40+
// Create OpenWeatherMap object.
4241
$owm = new OpenWeatherMap('YOUR-API-KEY');
4342

4443
try {
@@ -52,24 +51,24 @@ try {
5251
echo $weather->temperature;
5352
```
5453

55-
For more example code and instructions on how to use this library, please take
56-
a look into the `Examples` folder. Make sure to get an API Key from
54+
For more example code and instructions on how to use this library, please take
55+
a look into the `Examples` folder. Make sure to get an API Key from
5756
http://home.openweathermap.org/ and put it into `Examples/ApiKey.ini`.
57+
5858
- `CurrentWeather.php` Shows how to receive the current weather.
5959
- `WeatherForecast.php` Shows how to receive weather forecasts.
6060
- `WeatherHistory.php` Shows how to receive weather history.
6161
- `UVIndex.php` Shows how to receive uv index data.
62-
- `Cache.php` Shows how to implement and use a cache.
6362

6463
Contributing
6564
============
66-
I'm happy about every **pull request** or **issue** you find and open to help
65+
I'm happy about every **pull request** or **issue** you find and open to help
6766
make this API **more awesome**.
6867

6968
## Vagrant
7069

7170
You can use [Vagrant](https://vagrantup.com) to kick-start your development.
72-
Simply run `vagrant up` and `vagrant ssh` to start a PHP VM with all
71+
Simply run `vagrant up` and `vagrant ssh` to start a PHP VM with all
7372
dependencies included.
7473

7574
## Docker
@@ -95,7 +94,7 @@ License
9594
MIT — Please see the [LICENSE file](https://github.com/Cmfcmf/OpenWeatherMap-PHP-Api/blob/master/LICENSE)
9695
distributed with this source code for further information regarding copyright and licensing.
9796

98-
**Please check out the following official links to read about the terms, pricing
97+
**Please check out the following official links to read about the terms, pricing
9998
and license of OpenWeatherMap before using the service:**
10099
- [OpenWeatherMap.org/terms](http://OpenWeatherMap.org/terms)
101100
- [OpenWeatherMap.org/appid](http://OpenWeatherMap.org/appid)

0 commit comments

Comments
 (0)