Completed
Pull Request — master (#134)
by Christian
13:33 queued 12:18
created

OpenWeatherMap::parseXML()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 0
cts 0
cp 0
rs 9.6666
c 0
b 0
f 0
cc 4
nc 3
nop 1
crap 20
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 Cmfcmf\OpenWeatherMap\WeatherHistory;
27
use Psr\Cache\CacheItemPoolInterface;
28
use Psr\Http\Client\ClientInterface;
29
use Psr\Http\Message\RequestFactoryInterface;
30
31
/**
32
 * Main class for the OpenWeatherMap-PHP-API. Only use this class.
33
 *
34
 * @api
35
 */
36
class OpenWeatherMap
37
{
38
    /**
39
     * The copyright notice. This is no official text, it was created by
40
     * following the guidelines at http://openweathermap.org/copyright.
41
     *
42
     * @var string $copyright
43
     */
44
    const COPYRIGHT = "Weather data from <a href=\"https://openweathermap.org\">OpenWeatherMap.org</a>";
45
46
    /**
47
     * @var string The basic api url to fetch weather data from.
48
     */
49
    private $weatherUrl = 'https://api.openweathermap.org/data/2.5/weather?';
50
51
    /**
52
     * @var string The basic api url to fetch weather group data from.
53
     */
54
    private $weatherGroupUrl = 'https://api.openweathermap.org/data/2.5/group?';
55
56
    /**
57
     * @var string The basic api url to fetch weekly forecast data from.
58
     */
59
    private $weatherHourlyForecastUrl = 'https://api.openweathermap.org/data/2.5/forecast?';
60
61
    /**
62
     * @var string The basic api url to fetch daily forecast data from.
63
     */
64
    private $weatherDailyForecastUrl = 'https://api.openweathermap.org/data/2.5/forecast/daily?';
65
66
    /**
67
     * @var string The basic api url to fetch history weather data from.
68
     */
69
    private $weatherHistoryUrl = 'https://history.openweathermap.org/data/2.5/history/city?';
70
71
    /**
72
     * @var string The basic api url to fetch uv index data from.
73
     */
74
    private $uvIndexUrl = 'https://api.openweathermap.org/data/2.5/uvi';
75
76
    /**
77
     * @var CacheItemPoolInterface|null $cache The cache to use.
78
     */
79
    private $cache = null;
80
81
    /**
82
     * @var int
83
     */
84
    private $ttl;
85
86
    /**
87
     * @var bool
88
     */
89
    private $wasCached = false;
90
91
    /**
92
     * @var ClientInterface
93
     */
94
    private $httpClient;
95
96
    /**
97
     * @var RequestFactoryInterface
98
     */
99
    private $httpRequestFactory;
100
101
    /**
102
     * @var string
103
     */
104
    private $apiKey = '';
105
106
    /**
107
     * Constructs the OpenWeatherMap object.
108
     *
109
     * @param string                      $apiKey             The OpenWeatherMap API key. Required.
110
     * @param ClientInterface             $httpClient         A PSR-18 compatible HTTP client implementation.
111
     * @param RequestFactoryInterface     $httpRequestFactory A PSR-17 compatbile HTTP request factory implementation.
112
     * @param null|CacheItemPoolInterface $cache              If set to null, caching is disabled. Otherwise this must be
113
     *                                                        a PSR 16-compatible cache instance.
114
     * @param int                         $ttl                How long weather data shall be cached. Defaults to 10 minutes.
115
     *                                                        Only used if $cache is not null.
116
     *
117
     * @api
118
     */
119
    public function __construct($apiKey, $httpClient, $httpRequestFactory, $cache = null, $ttl = 600)
120
    {
121
        if (!is_string($apiKey) || empty($apiKey)) {
122
            throw new \InvalidArgumentException("You must provide an API key.");
123
        }
124
125
        if (!is_numeric($ttl)) {
126
            throw new \InvalidArgumentException('$ttl must be numeric.');
127
        }
128
129
        $this->apiKey = $apiKey;
130
        $this->httpClient = $httpClient;
131
        $this->httpRequestFactory = $httpRequestFactory;
132
        $this->cache = $cache;
133
        $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...
134
    }
135
136
    /**
137
     * Sets the API Key.
138
     *
139
     * @param string $apiKey API key for the OpenWeatherMap account.
140
     *
141
     * @api
142
     */
143
    public function setApiKey($apiKey)
144
    {
145
        $this->apiKey = $apiKey;
146
    }
147
148
    /**
149
     * Returns the API Key.
150
     *
151
     * @return string
152
     *
153
     * @api
154
     */
155
    public function getApiKey()
156
    {
157
        return $this->apiKey;
158
    }
159
160
    /**
161
     * Returns the current weather at the place you specified.
162
     *
163
     * @param array|int|string $query The place to get weather information for. For possible values see below.
164
     * @param string           $units Can be either 'metric' or 'imperial' (default). This affects almost all units returned.
165
     * @param string           $lang  The language to use for descriptions, default is 'en'. For possible values see http://openweathermap.org/current#multi.
166
     * @param string           $appid Your app id, default ''. See http://openweathermap.org/appid for more details.
167
     *
168
     * @throws OpenWeatherMap\Exception  If OpenWeatherMap returns an error.
169
     * @throws \InvalidArgumentException If an argument error occurs.
170
     *
171
     * @return CurrentWeather The weather object.
172
     *
173
     * There are four ways to specify the place to get weather information for:
174
     * - Use the city name: $query must be a string containing the city name.
175
     * - Use the city id: $query must be an integer containing the city id.
176
     * - Use the coordinates: $query must be an associative array containing the 'lat' and 'lon' values.
177
     * - Use the zip code: $query must be a string, prefixed with "zip:"
178
     *
179
     * Zip code may specify country. e.g., "zip:77070" (Houston, TX, US) or "zip:500001,IN" (Hyderabad, India)
180
     *
181
     * @api
182
     */
183
    public function getWeather($query, $units = 'imperial', $lang = 'en', $appid = '')
184
    {
185
        $answer = $this->getRawWeatherData($query, $units, $lang, $appid, 'xml');
186
        $xml = $this->parseXML($answer);
187
188
        return new CurrentWeather($xml, $units);
189
    }
190
191
    /**
192
     * Returns the current weather for a group of city ids.
193
     *
194
     * @param array  $ids   The city ids to get weather information for
195
     * @param string $units Can be either 'metric' or 'imperial' (default). This affects almost all units returned.
196
     * @param string $lang  The language to use for descriptions, default is 'en'. For possible values see http://openweathermap.org/current#multi.
197
     * @param string $appid Your app id, default ''. See http://openweathermap.org/appid for more details.
198
     *
199
     * @throws OpenWeatherMap\Exception  If OpenWeatherMap returns an error.
200
     * @throws \InvalidArgumentException If an argument error occurs.
201
     *
202
     * @return CurrentWeatherGroup
203
     *
204
     * @api
205
     */
206
    public function getWeatherGroup($ids, $units = 'imperial', $lang = 'en', $appid = '')
207
    {
208
        $answer = $this->getRawWeatherGroupData($ids, $units, $lang, $appid);
209
        $json = $this->parseJson($answer);
210
211
        return new CurrentWeatherGroup($json, $units);
0 ignored issues
show
Bug introduced by
It seems like $json defined by $this->parseJson($answer) on line 209 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...
212
    }
213
214
    /**
215
     * Returns the forecast for the place you specified. DANGER: Might return
216
     * fewer results than requested due to a bug in the OpenWeatherMap API!
217
     *
218
     * @param array|int|string $query The place to get weather information for. For possible values see ::getWeather.
219
     * @param string           $units Can be either 'metric' or 'imperial' (default). This affects almost all units returned.
220
     * @param string           $lang  The language to use for descriptions, default is 'en'. For possible values see http://openweathermap.org/current#multi.
221
     * @param string           $appid Your app id, default ''. See http://openweathermap.org/appid for more details.
222
     * @param int              $days  For how much days you want to get a forecast. Default 1, maximum: 16.
223
     *
224
     * @throws OpenWeatherMap\Exception If OpenWeatherMap returns an error.
225
     * @throws \InvalidArgumentException If an argument error occurs.
226
     *
227
     * @return WeatherForecast
228
     *
229
     * @api
230
     */
231
    public function getWeatherForecast($query, $units = 'imperial', $lang = 'en', $appid = '', $days = 1)
232
    {
233
        if ($days <= 5) {
234
            $answer = $this->getRawHourlyForecastData($query, $units, $lang, $appid, 'xml');
235
        } elseif ($days <= 16) {
236
            $answer = $this->getRawDailyForecastData($query, $units, $lang, $appid, 'xml', $days);
237
        } else {
238
            throw new \InvalidArgumentException('Error: forecasts are only available for the next 16 days. $days must be 16 or lower.');
239
        }
240
        $xml = $this->parseXML($answer);
241
242
        return new WeatherForecast($xml, $units, $days);
243
    }
244
245
    /**
246
     * Returns the DAILY forecast for the place you specified. DANGER: Might return
247
     * fewer results than requested due to a bug in the OpenWeatherMap API!
248
     *
249
     * @param array|int|string $query The place to get weather information for. For possible values see ::getWeather.
250
     * @param string           $units Can be either 'metric' or 'imperial' (default). This affects almost all units returned.
251
     * @param string           $lang  The language to use for descriptions, default is 'en'. For possible values see http://openweathermap.org/current#multi.
252
     * @param string           $appid Your app id, default ''. See http://openweathermap.org/appid for more details.
253
     * @param int              $days  For how much days you want to get a forecast. Default 1, maximum: 16.
254
     *
255
     * @throws OpenWeatherMap\Exception If OpenWeatherMap returns an error.
256
     * @throws \InvalidArgumentException If an argument error occurs.
257
     *
258
     * @return WeatherForecast
259
     *
260
     * @api
261
     */
262
    public function getDailyWeatherForecast($query, $units = 'imperial', $lang = 'en', $appid = '', $days = 1)
263
    {
264
        if ($days > 16) {
265
            throw new \InvalidArgumentException('Error: forecasts are only available for the next 16 days. $days must be 16 or lower.');
266
        }
267
268
        $answer = $this->getRawDailyForecastData($query, $units, $lang, $appid, 'xml', $days);
269
        $xml = $this->parseXML($answer);
270
        return new WeatherForecast($xml, $units, $days);
271
    }
272
273
    /**
274
     * Returns the weather history for the place you specified.
275
     *
276
     * @param array|int|string $query      The place to get weather information for. For possible values see ::getWeather.
277
     * @param \DateTime        $start
278
     * @param int              $endOrCount
279
     * @param string           $type       Can either be 'tick', 'hour' or 'day'.
280
     * @param string           $units      Can be either 'metric' or 'imperial' (default). This affects almost all units returned.
281
     * @param string           $lang       The language to use for descriptions, default is 'en'. For possible values see http://openweathermap.org/current#multi.
282
     * @param string           $appid      Your app id, default ''. See http://openweathermap.org/appid for more details.
283
     *
284
     * @throws OpenWeatherMap\Exception  If OpenWeatherMap returns an error.
285
     * @throws \InvalidArgumentException If an argument error occurs.
286
     *
287
     * @return WeatherHistory
288
     *
289
     * @api
290
     */
291
    public function getWeatherHistory($query, \DateTime $start, $endOrCount = 1, $type = 'hour', $units = 'imperial', $lang = 'en', $appid = '')
292
    {
293 View Code Duplication
        if (!in_array($type, array('tick', 'hour', 'day'))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
294
            throw new \InvalidArgumentException('$type must be either "tick", "hour" or "day"');
295
        }
296
297
        $xml = json_decode($this->getRawWeatherHistory($query, $start, $endOrCount, $type, $units, $lang, $appid), true);
298
299
        if ($xml['cod'] != 200) {
300
            throw new OWMException($xml['message'], $xml['cod']);
301
        }
302
303
        return new WeatherHistory($xml, $query);
304
    }
305
306
    /**
307
     * Returns the current uv index at the location you specified.
308
     *
309
     * @param float $lat The location's latitude.
310
     * @param float $lon The location's longitude.
311
     *
312
     * @throws OpenWeatherMap\Exception  If OpenWeatherMap returns an error.
313
     * @throws \InvalidArgumentException If an argument error occurs.
314
     *
315
     * @return UVIndex
316
     *
317
     * @api
318
     */
319
    public function getCurrentUVIndex($lat, $lon)
320
    {
321
        $answer = $this->getRawUVIndexData('current', $lat, $lon);
322
        $json = $this->parseJson($answer);
0 ignored issues
show
Bug introduced by
It seems like $answer defined by $this->getRawUVIndexData('current', $lat, $lon) on line 321 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...
323
324
        return new UVIndex($json);
0 ignored issues
show
Bug introduced by
It seems like $json defined by $this->parseJson($answer) on line 322 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...
325
    }
326
327
    /**
328
     * Returns a forecast of the uv index at the specified location.
329
     * The optional $cnt parameter determines the number of days to forecase.
330
     * The maximum supported number of days is 8.
331
     *
332
     * @param float $lat The location's latitude.
333
     * @param float $lon The location's longitude.
334
     * @param int   $cnt Number of returned days (default to 8).
335
     *
336
     * @throws OpenWeatherMap\Exception  If OpenWeatherMap returns an error.
337
     * @throws \InvalidArgumentException If an argument error occurs.
338
     *
339
     * @return UVIndex[]
340
     *
341
     * @api
342
     */
343 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...
344
    {
345
        $answer = $this->getRawUVIndexData('forecast', $lat, $lon, $cnt);
346
        $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 345 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...
347
348
        return array_map(function ($entry) {
349
            return new UVIndex($entry);
350
        }, $data);
351
    }
352
353
    /**
354
     * Returns the historic uv index at the specified location.
355
     *
356
     * @param float     $lat   The location's latitude.
357
     * @param float     $lon   The location's longitude.
358
     * @param \DateTime $start Starting point of time period.
359
     * @param \DateTime $end   Final point of time period.
360
     *
361
     * @throws OpenWeatherMap\Exception  If OpenWeatherMap returns an error.
362
     * @throws \InvalidArgumentException If an argument error occurs.
363
     *
364
     * @return UVIndex[]
365
     *
366
     * @api
367
     */
368 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...
369
    {
370
        $answer = $this->getRawUVIndexData('historic', $lat, $lon, null, $start, $end);
371
        $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 370 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...
372
373
        return array_map(function ($entry) {
374
            return new UVIndex($entry);
375
        }, $data);
376
    }
377
378
    /**
379
     * Directly returns the xml/json/html string returned by OpenWeatherMap for the current weather.
380
     *
381
     * @param array|int|string $query The place to get weather information for. For possible values see ::getWeather.
382
     * @param string           $units Can be either 'metric' or 'imperial' (default). This affects almost all units returned.
383
     * @param string           $lang  The language to use for descriptions, default is 'en'. For possible values see http://openweathermap.org/current#multi.
384
     * @param string           $appid Your app id, default ''. See http://openweathermap.org/appid for more details.
385
     * @param string           $mode  The format of the data fetched. Possible values are 'json', 'html' and 'xml' (default).
386
     *
387
     * @return string Returns false on failure and the fetched data in the format you specified on success.
388
     *
389
     * Warning: If an error occurs, OpenWeatherMap ALWAYS returns json data.
390
     *
391
     * @api
392
     */
393
    public function getRawWeatherData($query, $units = 'imperial', $lang = 'en', $appid = '', $mode = 'xml')
394
    {
395
        $url = $this->buildUrl($query, $units, $lang, $appid, $mode, $this->weatherUrl);
396
397
        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 395 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...
398
    }
399
400
    /**
401
     * Directly returns the JSON string returned by OpenWeatherMap for the group of current weather.
402
     * Only a JSON response format is supported for this webservice.
403
     *
404
     * @param array  $ids   The city ids to get weather information for
405
     * @param string $units Can be either 'metric' or 'imperial' (default). This affects almost all units returned.
406
     * @param string $lang  The language to use for descriptions, default is 'en'. For possible values see http://openweathermap.org/current#multi.
407
     * @param string $appid Your app id, default ''. See http://openweathermap.org/appid for more details.
408
     *
409
     * @return string Returns false on failure and the fetched data in the format you specified on success.
410
     *
411
     * @api
412
     */
413
    public function getRawWeatherGroupData($ids, $units = 'imperial', $lang = 'en', $appid = '')
414
    {
415
        $url = $this->buildUrl($ids, $units, $lang, $appid, 'json', $this->weatherGroupUrl);
416
417
        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 415 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...
418
    }
419
420
    /**
421
     * Directly returns the xml/json/html string returned by OpenWeatherMap for the hourly forecast.
422
     *
423
     * @param array|int|string $query The place to get weather information for. For possible values see ::getWeather.
424
     * @param string           $units Can be either 'metric' or 'imperial' (default). This affects almost all units returned.
425
     * @param string           $lang  The language to use for descriptions, default is 'en'. For possible values see http://openweathermap.org/current#multi.
426
     * @param string           $appid Your app id, default ''. See http://openweathermap.org/appid for more details.
427
     * @param string           $mode  The format of the data fetched. Possible values are 'json', 'html' and 'xml' (default).
428
     *
429
     * @return string Returns false on failure and the fetched data in the format you specified on success.
430
     *
431
     * Warning: If an error occurs, OpenWeatherMap ALWAYS returns json data.
432
     *
433
     * @api
434
     */
435
    public function getRawHourlyForecastData($query, $units = 'imperial', $lang = 'en', $appid = '', $mode = 'xml')
436
    {
437
        $url = $this->buildUrl($query, $units, $lang, $appid, $mode, $this->weatherHourlyForecastUrl);
438
439
        return $this->cacheOrFetchResult($url);
0 ignored issues
show
Bug introduced by
It seems like $url defined by $this->buildUrl($query, ...atherHourlyForecastUrl) on line 437 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...
440
    }
441
442
    /**
443
     * Directly returns the xml/json/html string returned by OpenWeatherMap for the daily forecast.
444
     *
445
     * @param array|int|string $query The place to get weather information for. For possible values see ::getWeather.
446
     * @param string           $units Can be either 'metric' or 'imperial' (default). This affects almost all units returned.
447
     * @param string           $lang  The language to use for descriptions, default is 'en'. For possible values see http://openweathermap.org/current#multi.
448
     * @param string           $appid Your app id, default ''. See http://openweathermap.org/appid for more details.
449
     * @param string           $mode  The format of the data fetched. Possible values are 'json', 'html' and 'xml' (default)
450
     * @param int              $cnt   How many days of forecast shall be returned? Maximum (and default): 16
451
     *
452
     * @throws \InvalidArgumentException If $cnt is higher than 16.
453
     *
454
     * @return string Returns false on failure and the fetched data in the format you specified on success.
455
     *
456
     * Warning: If an error occurs, OpenWeatherMap ALWAYS returns json data.
457
     *
458
     * @api
459
     */
460
    public function getRawDailyForecastData($query, $units = 'imperial', $lang = 'en', $appid = '', $mode = 'xml', $cnt = 16)
461
    {
462
        if ($cnt > 16) {
463
            throw new \InvalidArgumentException('$cnt must be 16 or lower!');
464
        }
465
        $url = $this->buildUrl($query, $units, $lang, $appid, $mode, $this->weatherDailyForecastUrl) . "&cnt=$cnt";
466
467
        return $this->cacheOrFetchResult($url);
468
    }
469
470
    /**
471
     * Directly returns the json string returned by OpenWeatherMap for the weather history.
472
     *
473
     * @param array|int|string $query      The place to get weather information for. For possible values see ::getWeather.
474
     * @param \DateTime        $start      The \DateTime object of the date to get the first weather information from.
475
     * @param \DateTime|int    $endOrCount Can be either a \DateTime object representing the end of the period to
476
     *                                     receive weather history data for or an integer counting the number of
477
     *                                     reports requested.
478
     * @param string           $type       The period of the weather history requested. Can be either be either "tick",
479
     *                                     "hour" or "day".
480
     * @param string           $units      Can be either 'metric' or 'imperial' (default). This affects almost all units returned.
481
     * @param string           $lang       The language to use for descriptions, default is 'en'. For possible values see http://openweathermap.org/current#multi.
482
     * @param string           $appid      Your app id, default ''. See http://openweathermap.org/appid for more details.
483
     *
484
     * @throws \InvalidArgumentException
485
     *
486
     * @return string Returns false on failure and the fetched data in the format you specified on success.
487
     *
488
     * Warning If an error occurred, OpenWeatherMap ALWAYS returns data in json format.
489
     *
490
     * @api
491
     */
492
    public function getRawWeatherHistory($query, \DateTime $start, $endOrCount = 1, $type = 'hour', $units = 'imperial', $lang = 'en', $appid = '')
493
    {
494 View Code Duplication
        if (!in_array($type, array('tick', 'hour', 'day'))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
495
            throw new \InvalidArgumentException('$type must be either "tick", "hour" or "day"');
496
        }
497
498
        $url = $this->buildUrl($query, $units, $lang, $appid, 'json', $this->weatherHistoryUrl);
499
        $url .= "&type=$type&start={$start->format('U')}";
500
        if ($endOrCount instanceof \DateTime) {
501
            $url .= "&end={$endOrCount->format('U')}";
502
        } elseif (is_numeric($endOrCount) && $endOrCount > 0) {
503
            $url .= "&cnt=$endOrCount";
504
        } else {
505
            throw new \InvalidArgumentException('$endOrCount must be either a \DateTime or a positive integer.');
506
        }
507
508
        return $this->cacheOrFetchResult($url);
509
    }
510
511
    /**
512
     * Directly returns the json string returned by OpenWeatherMap for the UV index data.
513
     *
514
     * @param string    $mode  The type of requested data (['historic', 'forecast', 'current']).
515
     * @param float     $lat   The location's latitude.
516
     * @param float     $lon   The location's longitude.
517
     * @param int       $cnt   Number of returned days (only allowed for 'forecast' data).
518
     * @param \DateTime $start Starting point of time period (only allowed and required for 'historic' data).
519
     * @param \DateTime $end   Final point of time period (only allowed and required for 'historic' data).
520
     *
521
     * @return bool|string Returns the fetched data.
522
     *
523
     * @api
524
     */
525
    public function getRawUVIndexData($mode, $lat, $lon, $cnt = null, $start = null, $end = null)
526
    {
527
        if (!in_array($mode, array('current', 'forecast', 'historic'), true)) {
528
            throw new \InvalidArgumentException("$mode must be one of 'historic', 'forecast', 'current'.");
529
        }
530
        if (!is_float($lat) || !is_float($lon)) {
531
            throw new \InvalidArgumentException('$lat and $lon must be floating point numbers');
532
        }
533
        if (isset($cnt) && (!is_int($cnt) || $cnt > 8 || $cnt < 1)) {
534
            throw new \InvalidArgumentException('$cnt must be an int between 1 and 8');
535
        }
536
        if (isset($start) && !$start instanceof \DateTime) {
537
            throw new \InvalidArgumentException('$start must be an instance of \DateTime');
538
        }
539
        if (isset($end) && !$end instanceof \DateTime) {
540
            throw new \InvalidArgumentException('$end must be an instance of \DateTime');
541
        }
542
        if ($mode === 'current' && (isset($start) || isset($end) || isset($cnt))) {
543
            throw new \InvalidArgumentException('Neither $start, $end, nor $cnt must be set for current data.');
544
        } elseif ($mode === 'forecast' && (isset($start) || isset($end) || !isset($cnt))) {
545
            throw new \InvalidArgumentException('$cnt needs to be set and both $start and $end must not be set for forecast data.');
546
        } elseif ($mode === 'historic' && (!isset($start) || !isset($end) || isset($cnt))) {
547
            throw new \InvalidArgumentException('Both $start and $end need to be set and $cnt must not be set for historic data.');
548
        }
549
550
        $url = $this->buildUVIndexUrl($mode, $lat, $lon, $cnt, $start, $end);
551
        return $this->cacheOrFetchResult($url);
552
    }
553
554
    /**
555
     * Returns whether or not the last result was fetched from the cache.
556
     *
557
     * @return bool true if last result was fetched from cache, false otherwise.
558
     */
559
    public function wasCached()
560
    {
561
        return $this->wasCached;
562
    }
563
564
    /**
565
     * Fetches the result or delivers a cached version of the result.
566
     *
567
     * @param string $url
568
     *
569
     * @return string
570
     */
571
    private function cacheOrFetchResult($url)
572
    {
573
        if ($this->cache !== null) {
574
            $key = str_replace(
575
                ["{", "}", "(", ")", "/", "\\", "@", ":"],
576
                ["_", "_", "_", "_", "_", "_",  "_", "_"],
577
                $url);
578
            $item = $this->cache->getItem($key);
579
            if ($item->isHit()) {
580
                $this->wasCached = true;
581
                return $item->get();
582
            }
583
        }
584
585
        $response = $this->httpClient->sendRequest($this->httpRequestFactory->createRequest("GET", $url));
586
        $result = $response->getBody()->getContents();
587
        if ($response->getStatusCode() !== 200) {
588
            throw new OWMException('OpenWeatherMap returned a response with status code ' . $response->getStatusCode() . ' and the following content '. $result);
589
        }
590
591
        if ($this->cache !== null) {
592
            $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...
593
            $item->expiresAfter($this->ttl);
594
            $this->cache->save($item);
595
        }
596
        $this->wasCached = false;
597
598
        return $result;
599
    }
600
601
    /**
602
     * Build the url to fetch weather data from.
603
     *
604
     * @param        $query
605
     * @param        $units
606
     * @param        $lang
607
     * @param        $appid
608
     * @param        $mode
609
     * @param string $url   The url to prepend.
610
     *
611
     * @return bool|string The fetched url, false on failure.
612
     */
613
    private function buildUrl($query, $units, $lang, $appid, $mode, $url)
614
    {
615
        $queryUrl = $this->buildQueryUrlParameter($query);
616
617
        $url = $url."$queryUrl&units=$units&lang=$lang&mode=$mode&APPID=";
618
        $url .= empty($appid) ? $this->apiKey : $appid;
619
620
        return $url;
621
    }
622
623
    /**
624
     * @param string             $mode          The type of requested data.
625
     * @param float              $lat           The location's latitude.
626
     * @param float              $lon           The location's longitude.
627
     * @param int                $cnt           Number of returned days.
628
     * @param \DateTime          $start         Starting point of time period.
629
     * @param \DateTime          $end           Final point of time period.
630
     *
631
     * @return string
632
     */
633
    private function buildUVIndexUrl($mode, $lat, $lon, $cnt = null, \DateTime $start = null, \DateTime $end = null)
634
    {
635
        $params = array(
636
            'appid' => $this->apiKey,
637
            'lat' => $lat,
638
            'lon' => $lon,
639
        );
640
641
        switch ($mode) {
642
            case 'historic':
643
                $requestMode = '/history';
644
                $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...
645
                $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...
646
                break;
647
            case 'forecast':
648
                $requestMode = '/forecast';
649
                $params['cnt'] = $cnt;
650
                break;
651
            case 'current':
652
                $requestMode = '';
653
                break;
654
            default:
655
                throw new \InvalidArgumentException("Invalid mode $mode for uv index url");
656
        }
657
658
        return sprintf($this->uvIndexUrl . '%s?%s', $requestMode, http_build_query($params));
659
    }
660
661
    /**
662
     * Builds the query string for the url.
663
     *
664
     * @param mixed $query
665
     *
666
     * @return string The built query string for the url.
667
     *
668
     * @throws \InvalidArgumentException If the query parameter is invalid.
669
     */
670
    private function buildQueryUrlParameter($query)
671
    {
672
        switch ($query) {
673
            case is_array($query) && isset($query['lat']) && isset($query['lon']) && is_numeric($query['lat']) && is_numeric($query['lon']):
674
                return "lat={$query['lat']}&lon={$query['lon']}";
675
            case is_array($query) && is_numeric($query[0]):
676
                return 'id='.implode(',', $query);
677
            case is_numeric($query):
678
                return "id=$query";
679
            case is_string($query) && strpos($query, 'zip:') === 0:
680
                $subQuery = str_replace('zip:', '', $query);
681
                return 'zip='.urlencode($subQuery);
682
            case is_string($query):
683
                return 'q='.urlencode($query);
684
            default:
685
                throw new \InvalidArgumentException('Error: $query has the wrong format. See the documentation of OpenWeatherMap::getWeather() to read about valid formats.');
686
        }
687
    }
688
689
    /**
690
     * @param string $answer The content returned by OpenWeatherMap.
691
     *
692
     * @return \SimpleXMLElement
693
     * @throws OWMException If the content isn't valid XML.
694
     */
695
    private function parseXML($answer)
696
    {
697
        // Disable default error handling of SimpleXML (Do not throw E_WARNINGs).
698
        libxml_use_internal_errors(true);
699
        libxml_clear_errors();
700
        try {
701
            return new \SimpleXMLElement($answer);
702
        } catch (\Exception $e) {
703
            // Invalid xml format. This happens in case OpenWeatherMap returns an error.
704
            // OpenWeatherMap always uses json for errors, even if one specifies xml as format.
705
            $error = json_decode($answer, true);
706
            if (isset($error['message'])) {
707
                throw new OWMException($error['message'], isset($error['cod']) ? $error['cod'] : 0);
708
            } else {
709
                throw new OWMException('Unknown fatal error: OpenWeatherMap returned the following json object: ' . $answer);
710
            }
711
        }
712
    }
713
714
    /**
715
     * @param string $answer The content returned by OpenWeatherMap.
716
     *
717
     * @return \stdClass|array
718
     * @throws OWMException If the content isn't valid JSON.
719
     */
720
    private function parseJson($answer)
721
    {
722
        $json = json_decode($answer);
723
        if (json_last_error() !== JSON_ERROR_NONE) {
724
            throw new OWMException('OpenWeatherMap returned an invalid json object. JSON error was: "' .
725
                $this->json_last_error_msg() . '". The retrieved json was: ' . $answer);
726
        }
727
        if (isset($json->message)) {
728
            throw new OWMException('An error occurred: '. $json->message);
729
        }
730
731
        return $json;
732
    }
733
734
    private function json_last_error_msg()
735
    {
736
        if (function_exists('json_last_error_msg')) {
737
            return json_last_error_msg();
738
        }
739
740
        static $ERRORS = array(
741
            JSON_ERROR_NONE => 'No error',
742
            JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
743
            JSON_ERROR_STATE_MISMATCH => 'State mismatch (invalid or malformed JSON)',
744
            JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
745
            JSON_ERROR_SYNTAX => 'Syntax error',
746
            JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded'
747
        );
748
749
        $error = json_last_error();
750
        return isset($ERRORS[$error]) ? $ERRORS[$error] : 'Unknown error';
751
    }
752
}
753