Completed
Push — v3 ( 124845...b1d686 )
by Christian
01:20
created

OpenWeatherMap::getWeatherHistory()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14

Duplication

Lines 3
Ratio 21.43 %

Importance

Changes 0
Metric Value
dl 3
loc 14
rs 9.7998
c 0
b 0
f 0
cc 3
nc 3
nop 7
1
<?php
2
3
/*
4
 * OpenWeatherMap-PHP-API — A PHP API to parse weather data from https://OpenWeatherMap.org.
5
 *
6
 * @license MIT
7
 *
8
 * Please see the LICENSE file distributed with this source code for further
9
 * information regarding copyright and licensing.
10
 *
11
 * Please visit the following links to read about the usage policies and the license of
12
 * OpenWeatherMap data before using this library:
13
 *
14
 * @see https://OpenWeatherMap.org/price
15
 * @see https://OpenWeatherMap.org/terms
16
 * @see https://OpenWeatherMap.org/appid
17
 */
18
19
namespace Cmfcmf;
20
21
use Cmfcmf\OpenWeatherMap\CurrentWeather;
22
use Cmfcmf\OpenWeatherMap\UVIndex;
23
use Cmfcmf\OpenWeatherMap\CurrentWeatherGroup;
24
use Cmfcmf\OpenWeatherMap\Exception as OWMException;
25
use Cmfcmf\OpenWeatherMap\WeatherForecast;
26
use Psr\Cache\CacheItemPoolInterface;
27
use Psr\Http\Client\ClientInterface;
28
use Psr\Http\Message\RequestFactoryInterface;
29
30
/**
31
 * Main class for the OpenWeatherMap-PHP-API. Only use this class.
32
 *
33
 * @api
34
 */
35
class OpenWeatherMap
36
{
37
    /**
38
     * The copyright notice. This is no official text, it was created by
39
     * following the guidelines at http://openweathermap.org/copyright.
40
     *
41
     * @var string $copyright
42
     */
43
    const COPYRIGHT = "Weather data from <a href=\"https://openweathermap.org\">OpenWeatherMap.org</a>";
44
45
    /**
46
     * @var string The basic api url to fetch weather data from.
47
     */
48
    private $weatherUrl = 'https://api.openweathermap.org/data/2.5/weather?';
49
50
    /**
51
     * @var string The basic api url to fetch weather group data from.
52
     */
53
    private $weatherGroupUrl = 'https://api.openweathermap.org/data/2.5/group?';
54
55
    /**
56
     * @var string The basic api url to fetch weekly forecast data from.
57
     */
58
    private $weatherHourlyForecastUrl = 'https://api.openweathermap.org/data/2.5/forecast?';
59
60
    /**
61
     * @var string The basic api url to fetch daily forecast data from.
62
     */
63
    private $weatherDailyForecastUrl = 'https://api.openweathermap.org/data/2.5/forecast/daily?';
64
65
    /**
66
     * @var string The basic api url to fetch uv index data from.
67
     */
68
    private $uvIndexUrl = 'https://api.openweathermap.org/data/2.5/uvi';
69
70
    /**
71
     * @var CacheItemPoolInterface|null $cache The cache to use.
72
     */
73
    private $cache = null;
74
75
    /**
76
     * @var int
77
     */
78
    private $ttl;
79
80
    /**
81
     * @var bool
82
     */
83
    private $wasCached = false;
84
85
    /**
86
     * @var ClientInterface
87
     */
88
    private $httpClient;
89
90
    /**
91
     * @var RequestFactoryInterface
92
     */
93
    private $httpRequestFactory;
94
95
    /**
96
     * @var string
97
     */
98
    private $apiKey = '';
99
100
    /**
101
     * Constructs the OpenWeatherMap object.
102
     *
103
     * @param string                      $apiKey             The OpenWeatherMap API key. Required.
104
     * @param ClientInterface             $httpClient         A PSR-18 compatible HTTP client implementation.
105
     * @param RequestFactoryInterface     $httpRequestFactory A PSR-17 compatbile HTTP request factory implementation.
106
     * @param null|CacheItemPoolInterface $cache              If set to null, caching is disabled. Otherwise this must be
107
     *                                                        a PSR 16-compatible cache instance.
108
     * @param int                         $ttl                How long weather data shall be cached. Defaults to 10 minutes.
109
     *                                                        Only used if $cache is not null.
110
     *
111
     * @api
112
     */
113
    public function __construct($apiKey, $httpClient, $httpRequestFactory, $cache = null, $ttl = 600)
114
    {
115
        if (!is_string($apiKey) || empty($apiKey)) {
116
            throw new \InvalidArgumentException("You must provide an API key.");
117
        }
118
119
        if (!is_numeric($ttl)) {
120
            throw new \InvalidArgumentException('$ttl must be numeric.');
121
        }
122
123
        $this->apiKey = $apiKey;
124
        $this->httpClient = $httpClient;
125
        $this->httpRequestFactory = $httpRequestFactory;
126
        $this->cache = $cache;
127
        $this->ttl = $ttl;
0 ignored issues
show
Documentation Bug introduced by
It seems like $ttl can also be of type double or string. However, the property $ttl is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
128
    }
129
130
    /**
131
     * Sets the API Key.
132
     *
133
     * @param string $apiKey API key for the OpenWeatherMap account.
134
     *
135
     * @api
136
     */
137
    public function setApiKey($apiKey)
138
    {
139
        $this->apiKey = $apiKey;
140
    }
141
142
    /**
143
     * Returns the API Key.
144
     *
145
     * @return string
146
     *
147
     * @api
148
     */
149
    public function getApiKey()
150
    {
151
        return $this->apiKey;
152
    }
153
154
    /**
155
     * Returns the current weather at the place you specified.
156
     *
157
     * @param array|int|string $query The place to get weather information for. For possible values see below.
158
     * @param string           $units Can be either 'metric' or 'imperial' (default). This affects almost all units returned.
159
     * @param string           $lang  The language to use for descriptions, default is 'en'. For possible values see http://openweathermap.org/current#multi.
160
     * @param string           $appid Your app id, default ''. See http://openweathermap.org/appid for more details.
161
     *
162
     * @throws OpenWeatherMap\Exception  If OpenWeatherMap returns an error.
163
     * @throws \InvalidArgumentException If an argument error occurs.
164
     *
165
     * @return CurrentWeather The weather object.
166
     *
167
     * There are four ways to specify the place to get weather information for:
168
     * - Use the city name: $query must be a string containing the city name.
169
     * - Use the city id: $query must be an integer containing the city id.
170
     * - Use the coordinates: $query must be an associative array containing the 'lat' and 'lon' values.
171
     * - Use the zip code: $query must be a string, prefixed with "zip:"
172
     *
173
     * Zip code may specify country. e.g., "zip:77070" (Houston, TX, US) or "zip:500001,IN" (Hyderabad, India)
174
     *
175
     * @api
176
     */
177
    public function getWeather($query, $units = 'imperial', $lang = 'en', $appid = '')
178
    {
179
        $answer = $this->getRawWeatherData($query, $units, $lang, $appid, 'xml');
180
        $xml = $this->parseXML($answer);
181
182
        return new CurrentWeather($xml, $units);
183
    }
184
185
    /**
186
     * Returns the current weather for a group of city ids.
187
     *
188
     * @param array  $ids   The city ids to get weather information for
189
     * @param string $units Can be either 'metric' or 'imperial' (default). This affects almost all units returned.
190
     * @param string $lang  The language to use for descriptions, default is 'en'. For possible values see http://openweathermap.org/current#multi.
191
     * @param string $appid Your app id, default ''. See http://openweathermap.org/appid for more details.
192
     *
193
     * @throws OpenWeatherMap\Exception  If OpenWeatherMap returns an error.
194
     * @throws \InvalidArgumentException If an argument error occurs.
195
     *
196
     * @return CurrentWeatherGroup
197
     *
198
     * @api
199
     */
200
    public function getWeatherGroup($ids, $units = 'imperial', $lang = 'en', $appid = '')
201
    {
202
        $answer = $this->getRawWeatherGroupData($ids, $units, $lang, $appid);
203
        $json = $this->parseJson($answer);
204
205
        return new CurrentWeatherGroup($json, $units);
0 ignored issues
show
Bug introduced by
It seems like $json defined by $this->parseJson($answer) on line 203 can also be of type array; however, Cmfcmf\OpenWeatherMap\Cu...herGroup::__construct() does only seem to accept object<stdClass>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
206
    }
207
208
    /**
209
     * Returns the forecast for the place you specified. DANGER: Might return
210
     * fewer results than requested due to a bug in the OpenWeatherMap API!
211
     *
212
     * @param array|int|string $query The place to get weather information for. For possible values see ::getWeather.
213
     * @param string           $units Can be either 'metric' or 'imperial' (default). This affects almost all units returned.
214
     * @param string           $lang  The language to use for descriptions, default is 'en'. For possible values see http://openweathermap.org/current#multi.
215
     * @param string           $appid Your app id, default ''. See http://openweathermap.org/appid for more details.
216
     * @param int              $days  For how much days you want to get a forecast. Default 1, maximum: 16.
217
     *
218
     * @throws OpenWeatherMap\Exception If OpenWeatherMap returns an error.
219
     * @throws \InvalidArgumentException If an argument error occurs.
220
     *
221
     * @return WeatherForecast
222
     *
223
     * @api
224
     */
225
    public function getWeatherForecast($query, $units = 'imperial', $lang = 'en', $appid = '', $days = 1)
226
    {
227
        if ($days <= 5) {
228
            $answer = $this->getRawHourlyForecastData($query, $units, $lang, $appid, 'xml');
229
        } elseif ($days <= 16) {
230
            $answer = $this->getRawDailyForecastData($query, $units, $lang, $appid, 'xml', $days);
231
        } else {
232
            throw new \InvalidArgumentException('Error: forecasts are only available for the next 16 days. $days must be 16 or lower.');
233
        }
234
        $xml = $this->parseXML($answer);
235
236
        return new WeatherForecast($xml, $units, $days);
237
    }
238
239
    /**
240
     * Returns the DAILY forecast for the place you specified. DANGER: Might return
241
     * fewer results than requested due to a bug in the OpenWeatherMap API!
242
     *
243
     * @param array|int|string $query The place to get weather information for. For possible values see ::getWeather.
244
     * @param string           $units Can be either 'metric' or 'imperial' (default). This affects almost all units returned.
245
     * @param string           $lang  The language to use for descriptions, default is 'en'. For possible values see http://openweathermap.org/current#multi.
246
     * @param string           $appid Your app id, default ''. See http://openweathermap.org/appid for more details.
247
     * @param int              $days  For how much days you want to get a forecast. Default 1, maximum: 16.
248
     *
249
     * @throws OpenWeatherMap\Exception If OpenWeatherMap returns an error.
250
     * @throws \InvalidArgumentException If an argument error occurs.
251
     *
252
     * @return WeatherForecast
253
     *
254
     * @api
255
     */
256
    public function getDailyWeatherForecast($query, $units = 'imperial', $lang = 'en', $appid = '', $days = 1)
257
    {
258
        if ($days > 16) {
259
            throw new \InvalidArgumentException('Error: forecasts are only available for the next 16 days. $days must be 16 or lower.');
260
        }
261
262
        $answer = $this->getRawDailyForecastData($query, $units, $lang, $appid, 'xml', $days);
263
        $xml = $this->parseXML($answer);
264
        return new WeatherForecast($xml, $units, $days);
265
    }
266
267
    /**
268
     * Returns the current uv index at the location you specified.
269
     *
270
     * @param float $lat The location's latitude.
271
     * @param float $lon The location's longitude.
272
     *
273
     * @throws OpenWeatherMap\Exception  If OpenWeatherMap returns an error.
274
     * @throws \InvalidArgumentException If an argument error occurs.
275
     *
276
     * @return UVIndex
277
     *
278
     * @api
279
     */
280
    public function getCurrentUVIndex($lat, $lon)
281
    {
282
        $answer = $this->getRawUVIndexData('current', $lat, $lon);
283
        $json = $this->parseJson($answer);
0 ignored issues
show
Bug introduced by
It seems like $answer defined by $this->getRawUVIndexData('current', $lat, $lon) on line 282 can also be of type boolean; however, Cmfcmf\OpenWeatherMap::parseJson() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
284
285
        return new UVIndex($json);
0 ignored issues
show
Bug introduced by
It seems like $json defined by $this->parseJson($answer) on line 283 can also be of type array; however, Cmfcmf\OpenWeatherMap\UVIndex::__construct() does only seem to accept object, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
286
    }
287
288
    /**
289
     * Returns a forecast of the uv index at the specified location.
290
     * The optional $cnt parameter determines the number of days to forecase.
291
     * The maximum supported number of days is 8.
292
     *
293
     * @param float $lat The location's latitude.
294
     * @param float $lon The location's longitude.
295
     * @param int   $cnt Number of returned days (default to 8).
296
     *
297
     * @throws OpenWeatherMap\Exception  If OpenWeatherMap returns an error.
298
     * @throws \InvalidArgumentException If an argument error occurs.
299
     *
300
     * @return UVIndex[]
301
     *
302
     * @api
303
     */
304 View Code Duplication
    public function getForecastUVIndex($lat, $lon, $cnt = 8)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
305
    {
306
        $answer = $this->getRawUVIndexData('forecast', $lat, $lon, $cnt);
307
        $data = $this->parseJson($answer);
0 ignored issues
show
Bug introduced by
It seems like $answer defined by $this->getRawUVIndexData...ast', $lat, $lon, $cnt) on line 306 can also be of type boolean; however, Cmfcmf\OpenWeatherMap::parseJson() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
308
309
        return array_map(function ($entry) {
310
            return new UVIndex($entry);
311
        }, $data);
312
    }
313
314
    /**
315
     * Returns the historic uv index at the specified location.
316
     *
317
     * @param float     $lat   The location's latitude.
318
     * @param float     $lon   The location's longitude.
319
     * @param \DateTime $start Starting point of time period.
320
     * @param \DateTime $end   Final point of time period.
321
     *
322
     * @throws OpenWeatherMap\Exception  If OpenWeatherMap returns an error.
323
     * @throws \InvalidArgumentException If an argument error occurs.
324
     *
325
     * @return UVIndex[]
326
     *
327
     * @api
328
     */
329 View Code Duplication
    public function getHistoricUVIndex($lat, $lon, $start, $end)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
330
    {
331
        $answer = $this->getRawUVIndexData('historic', $lat, $lon, null, $start, $end);
332
        $data = $this->parseJson($answer);
0 ignored issues
show
Bug introduced by
It seems like $answer defined by $this->getRawUVIndexData...on, null, $start, $end) on line 331 can also be of type boolean; however, Cmfcmf\OpenWeatherMap::parseJson() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
333
334
        return array_map(function ($entry) {
335
            return new UVIndex($entry);
336
        }, $data);
337
    }
338
339
    /**
340
     * Directly returns the xml/json/html string returned by OpenWeatherMap for the current weather.
341
     *
342
     * @param array|int|string $query The place to get weather information for. For possible values see ::getWeather.
343
     * @param string           $units Can be either 'metric' or 'imperial' (default). This affects almost all units returned.
344
     * @param string           $lang  The language to use for descriptions, default is 'en'. For possible values see http://openweathermap.org/current#multi.
345
     * @param string           $appid Your app id, default ''. See http://openweathermap.org/appid for more details.
346
     * @param string           $mode  The format of the data fetched. Possible values are 'json', 'html' and 'xml' (default).
347
     *
348
     * @return string Returns false on failure and the fetched data in the format you specified on success.
349
     *
350
     * Warning: If an error occurs, OpenWeatherMap ALWAYS returns json data.
351
     *
352
     * @api
353
     */
354
    public function getRawWeatherData($query, $units = 'imperial', $lang = 'en', $appid = '', $mode = 'xml')
355
    {
356
        $url = $this->buildUrl($query, $units, $lang, $appid, $mode, $this->weatherUrl);
357
358
        return $this->cacheOrFetchResult($url);
0 ignored issues
show
Bug introduced by
It seems like $url defined by $this->buildUrl($query, ...ode, $this->weatherUrl) on line 356 can also be of type boolean; however, Cmfcmf\OpenWeatherMap::cacheOrFetchResult() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
359
    }
360
361
    /**
362
     * Directly returns the JSON string returned by OpenWeatherMap for the group of current weather.
363
     * Only a JSON response format is supported for this webservice.
364
     *
365
     * @param array  $ids   The city ids to get weather information for
366
     * @param string $units Can be either 'metric' or 'imperial' (default). This affects almost all units returned.
367
     * @param string $lang  The language to use for descriptions, default is 'en'. For possible values see http://openweathermap.org/current#multi.
368
     * @param string $appid Your app id, default ''. See http://openweathermap.org/appid for more details.
369
     *
370
     * @return string Returns false on failure and the fetched data in the format you specified on success.
371
     *
372
     * @api
373
     */
374
    public function getRawWeatherGroupData($ids, $units = 'imperial', $lang = 'en', $appid = '')
375
    {
376
        $url = $this->buildUrl($ids, $units, $lang, $appid, 'json', $this->weatherGroupUrl);
377
378
        return $this->cacheOrFetchResult($url);
0 ignored issues
show
Bug introduced by
It seems like $url defined by $this->buildUrl($ids, $u...$this->weatherGroupUrl) on line 376 can also be of type boolean; however, Cmfcmf\OpenWeatherMap::cacheOrFetchResult() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
379
    }
380
381
    /**
382
     * Directly returns the xml/json/html string returned by OpenWeatherMap for the hourly forecast.
383
     *
384
     * @param array|int|string $query The place to get weather information for. For possible values see ::getWeather.
385
     * @param string           $units Can be either 'metric' or 'imperial' (default). This affects almost all units returned.
386
     * @param string           $lang  The language to use for descriptions, default is 'en'. For possible values see http://openweathermap.org/current#multi.
387
     * @param string           $appid Your app id, default ''. See http://openweathermap.org/appid for more details.
388
     * @param string           $mode  The format of the data fetched. Possible values are 'json', 'html' and 'xml' (default).
389
     *
390
     * @return string Returns false on failure and the fetched data in the format you specified on success.
391
     *
392
     * Warning: If an error occurs, OpenWeatherMap ALWAYS returns json data.
393
     *
394
     * @api
395
     */
396
    public function getRawHourlyForecastData($query, $units = 'imperial', $lang = 'en', $appid = '', $mode = 'xml')
397
    {
398
        $url = $this->buildUrl($query, $units, $lang, $appid, $mode, $this->weatherHourlyForecastUrl);
399
400
        return $this->cacheOrFetchResult($url);
0 ignored issues
show
Bug introduced by
It seems like $url defined by $this->buildUrl($query, ...atherHourlyForecastUrl) on line 398 can also be of type boolean; however, Cmfcmf\OpenWeatherMap::cacheOrFetchResult() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
401
    }
402
403
    /**
404
     * Directly returns the xml/json/html string returned by OpenWeatherMap for the daily forecast.
405
     *
406
     * @param array|int|string $query The place to get weather information for. For possible values see ::getWeather.
407
     * @param string           $units Can be either 'metric' or 'imperial' (default). This affects almost all units returned.
408
     * @param string           $lang  The language to use for descriptions, default is 'en'. For possible values see http://openweathermap.org/current#multi.
409
     * @param string           $appid Your app id, default ''. See http://openweathermap.org/appid for more details.
410
     * @param string           $mode  The format of the data fetched. Possible values are 'json', 'html' and 'xml' (default)
411
     * @param int              $cnt   How many days of forecast shall be returned? Maximum (and default): 16
412
     *
413
     * @throws \InvalidArgumentException If $cnt is higher than 16.
414
     *
415
     * @return string Returns false on failure and the fetched data in the format you specified on success.
416
     *
417
     * Warning: If an error occurs, OpenWeatherMap ALWAYS returns json data.
418
     *
419
     * @api
420
     */
421
    public function getRawDailyForecastData($query, $units = 'imperial', $lang = 'en', $appid = '', $mode = 'xml', $cnt = 16)
422
    {
423
        if ($cnt > 16) {
424
            throw new \InvalidArgumentException('$cnt must be 16 or lower!');
425
        }
426
        $url = $this->buildUrl($query, $units, $lang, $appid, $mode, $this->weatherDailyForecastUrl) . "&cnt=$cnt";
427
428
        return $this->cacheOrFetchResult($url);
429
    }
430
431
    /**
432
     * Directly returns the json string returned by OpenWeatherMap for the UV index data.
433
     *
434
     * @param string    $mode  The type of requested data (['historic', 'forecast', 'current']).
435
     * @param float     $lat   The location's latitude.
436
     * @param float     $lon   The location's longitude.
437
     * @param int       $cnt   Number of returned days (only allowed for 'forecast' data).
438
     * @param \DateTime $start Starting point of time period (only allowed and required for 'historic' data).
439
     * @param \DateTime $end   Final point of time period (only allowed and required for 'historic' data).
440
     *
441
     * @return bool|string Returns the fetched data.
442
     *
443
     * @api
444
     */
445
    public function getRawUVIndexData($mode, $lat, $lon, $cnt = null, $start = null, $end = null)
446
    {
447
        if (!in_array($mode, array('current', 'forecast', 'historic'), true)) {
448
            throw new \InvalidArgumentException("$mode must be one of 'historic', 'forecast', 'current'.");
449
        }
450
        if (!is_float($lat) || !is_float($lon)) {
451
            throw new \InvalidArgumentException('$lat and $lon must be floating point numbers');
452
        }
453
        if (isset($cnt) && (!is_int($cnt) || $cnt > 8 || $cnt < 1)) {
454
            throw new \InvalidArgumentException('$cnt must be an int between 1 and 8');
455
        }
456
        if (isset($start) && !$start instanceof \DateTime) {
457
            throw new \InvalidArgumentException('$start must be an instance of \DateTime');
458
        }
459
        if (isset($end) && !$end instanceof \DateTime) {
460
            throw new \InvalidArgumentException('$end must be an instance of \DateTime');
461
        }
462
        if ($mode === 'current' && (isset($start) || isset($end) || isset($cnt))) {
463
            throw new \InvalidArgumentException('Neither $start, $end, nor $cnt must be set for current data.');
464
        } elseif ($mode === 'forecast' && (isset($start) || isset($end) || !isset($cnt))) {
465
            throw new \InvalidArgumentException('$cnt needs to be set and both $start and $end must not be set for forecast data.');
466
        } elseif ($mode === 'historic' && (!isset($start) || !isset($end) || isset($cnt))) {
467
            throw new \InvalidArgumentException('Both $start and $end need to be set and $cnt must not be set for historic data.');
468
        }
469
470
        $url = $this->buildUVIndexUrl($mode, $lat, $lon, $cnt, $start, $end);
471
        return $this->cacheOrFetchResult($url);
472
    }
473
474
    /**
475
     * Returns whether or not the last result was fetched from the cache.
476
     *
477
     * @return bool true if last result was fetched from cache, false otherwise.
478
     */
479
    public function wasCached()
480
    {
481
        return $this->wasCached;
482
    }
483
484
    /**
485
     * Fetches the result or delivers a cached version of the result.
486
     *
487
     * @param string $url
488
     *
489
     * @return string
490
     */
491
    private function cacheOrFetchResult($url)
492
    {
493
        if ($this->cache !== null) {
494
            $key = str_replace(
495
                ["{", "}", "(", ")", "/", "\\", "@", ":"],
496
                ["_", "_", "_", "_", "_", "_",  "_", "_"],
497
                $url);
498
            $item = $this->cache->getItem($key);
499
            if ($item->isHit()) {
500
                $this->wasCached = true;
501
                return $item->get();
502
            }
503
        }
504
505
        $response = $this->httpClient->sendRequest($this->httpRequestFactory->createRequest("GET", $url));
506
        $result = $response->getBody()->getContents();
507
        if ($response->getStatusCode() !== 200) {
508
            throw new OWMException('OpenWeatherMap returned a response with status code ' . $response->getStatusCode() . ' and the following content '. $result);
509
        }
510
511
        if ($this->cache !== null) {
512
            $item->set($result);
0 ignored issues
show
Bug introduced by
The variable $item does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
513
            $item->expiresAfter($this->ttl);
514
            $this->cache->save($item);
515
        }
516
        $this->wasCached = false;
517
518
        return $result;
519
    }
520
521
    /**
522
     * Build the url to fetch weather data from.
523
     *
524
     * @param        $query
525
     * @param        $units
526
     * @param        $lang
527
     * @param        $appid
528
     * @param        $mode
529
     * @param string $url   The url to prepend.
530
     *
531
     * @return bool|string The fetched url, false on failure.
532
     */
533
    private function buildUrl($query, $units, $lang, $appid, $mode, $url)
534
    {
535
        $queryUrl = $this->buildQueryUrlParameter($query);
536
537
        $url = $url."$queryUrl&units=$units&lang=$lang&mode=$mode&APPID=";
538
        $url .= empty($appid) ? $this->apiKey : $appid;
539
540
        return $url;
541
    }
542
543
    /**
544
     * @param string             $mode          The type of requested data.
545
     * @param float              $lat           The location's latitude.
546
     * @param float              $lon           The location's longitude.
547
     * @param int                $cnt           Number of returned days.
548
     * @param \DateTime          $start         Starting point of time period.
549
     * @param \DateTime          $end           Final point of time period.
550
     *
551
     * @return string
552
     */
553
    private function buildUVIndexUrl($mode, $lat, $lon, $cnt = null, \DateTime $start = null, \DateTime $end = null)
554
    {
555
        $params = array(
556
            'appid' => $this->apiKey,
557
            'lat' => $lat,
558
            'lon' => $lon,
559
        );
560
561
        switch ($mode) {
562
            case 'historic':
563
                $requestMode = '/history';
564
                $params['start'] = $start->format('U');
0 ignored issues
show
Bug introduced by
It seems like $start is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
565
                $params['end'] = $end->format('U');
0 ignored issues
show
Bug introduced by
It seems like $end is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
566
                break;
567
            case 'forecast':
568
                $requestMode = '/forecast';
569
                $params['cnt'] = $cnt;
570
                break;
571
            case 'current':
572
                $requestMode = '';
573
                break;
574
            default:
575
                throw new \InvalidArgumentException("Invalid mode $mode for uv index url");
576
        }
577
578
        return sprintf($this->uvIndexUrl . '%s?%s', $requestMode, http_build_query($params));
579
    }
580
581
    /**
582
     * Builds the query string for the url.
583
     *
584
     * @param mixed $query
585
     *
586
     * @return string The built query string for the url.
587
     *
588
     * @throws \InvalidArgumentException If the query parameter is invalid.
589
     */
590
    private function buildQueryUrlParameter($query)
591
    {
592
        switch ($query) {
593
            case is_array($query) && isset($query['lat']) && isset($query['lon']) && is_numeric($query['lat']) && is_numeric($query['lon']):
594
                return "lat={$query['lat']}&lon={$query['lon']}";
595
            case is_array($query) && is_numeric($query[0]):
596
                return 'id='.implode(',', $query);
597
            case is_numeric($query):
598
                return "id=$query";
599
            case is_string($query) && strpos($query, 'zip:') === 0:
600
                $subQuery = str_replace('zip:', '', $query);
601
                return 'zip='.urlencode($subQuery);
602
            case is_string($query):
603
                return 'q='.urlencode($query);
604
            default:
605
                throw new \InvalidArgumentException('Error: $query has the wrong format. See the documentation of OpenWeatherMap::getWeather() to read about valid formats.');
606
        }
607
    }
608
609
    /**
610
     * @param string $answer The content returned by OpenWeatherMap.
611
     *
612
     * @return \SimpleXMLElement
613
     * @throws OWMException If the content isn't valid XML.
614
     */
615
    private function parseXML($answer)
616
    {
617
        // Disable default error handling of SimpleXML (Do not throw E_WARNINGs).
618
        libxml_use_internal_errors(true);
619
        libxml_clear_errors();
620
        try {
621
            return new \SimpleXMLElement($answer);
622
        } catch (\Exception $e) {
623
            // Invalid xml format. This happens in case OpenWeatherMap returns an error.
624
            // OpenWeatherMap always uses json for errors, even if one specifies xml as format.
625
            $error = json_decode($answer, true);
626
            if (isset($error['message'])) {
627
                throw new OWMException($error['message'], isset($error['cod']) ? $error['cod'] : 0);
628
            } else {
629
                throw new OWMException('Unknown fatal error: OpenWeatherMap returned the following json object: ' . $answer);
630
            }
631
        }
632
    }
633
634
    /**
635
     * @param string $answer The content returned by OpenWeatherMap.
636
     *
637
     * @return \stdClass|array
638
     * @throws OWMException If the content isn't valid JSON.
639
     */
640
    private function parseJson($answer)
641
    {
642
        $json = json_decode($answer);
643
        if (json_last_error() !== JSON_ERROR_NONE) {
644
            throw new OWMException('OpenWeatherMap returned an invalid json object. JSON error was: "' .
645
                $this->json_last_error_msg() . '". The retrieved json was: ' . $answer);
646
        }
647
        if (isset($json->message)) {
648
            throw new OWMException('An error occurred: '. $json->message);
649
        }
650
651
        return $json;
652
    }
653
654
    private function json_last_error_msg()
655
    {
656
        if (function_exists('json_last_error_msg')) {
657
            return json_last_error_msg();
658
        }
659
660
        static $ERRORS = array(
661
            JSON_ERROR_NONE => 'No error',
662
            JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
663
            JSON_ERROR_STATE_MISMATCH => 'State mismatch (invalid or malformed JSON)',
664
            JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
665
            JSON_ERROR_SYNTAX => 'Syntax error',
666
            JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded'
667
        );
668
669
        $error = json_last_error();
670
        return isset($ERRORS[$error]) ? $ERRORS[$error] : 'Unknown error';
671
    }
672
}
673