Completed
Push — v3 ( d2b0fb...99929a )
by Christian
04:44 queued 03:26
created

OpenWeatherMap::getHistoricUVIndex()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9

Duplication

Lines 9
Ratio 100 %

Importance

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