Completed
Pull Request — master (#132)
by Christian
03:35 queued 01:41
created

OpenWeatherMap::getForecastUVIndex()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9

Duplication

Lines 9
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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