3434class OpenWeatherMap
3535{
3636 /**
37- * @var string $weatherUrl The basic api url to fetch weather data from.
37+ * @var string The basic api url to fetch weather data from.
3838 */
39- private $ weatherUrl = " http://api.openweathermap.org/data/2.5/weather? " ;
39+ private $ weatherUrl = ' http://api.openweathermap.org/data/2.5/weather? ' ;
4040
4141 /**
42- * @var string $url The basic api url to fetch weekly forecast data from.
42+ * @var string The basic api url to fetch weekly forecast data from.
4343 */
44- private $ weatherHourlyForecastUrl = " http://api.openweathermap.org/data/2.5/forecast? " ;
44+ private $ weatherHourlyForecastUrl = ' http://api.openweathermap.org/data/2.5/forecast? ' ;
4545
4646 /**
47- * @var string $url The basic api url to fetch daily forecast data from.
47+ * @var string The basic api url to fetch daily forecast data from.
4848 */
49- private $ weatherDailyForecastUrl = " http://api.openweathermap.org/data/2.5/forecast/daily? " ;
49+ private $ weatherDailyForecastUrl = ' http://api.openweathermap.org/data/2.5/forecast/daily? ' ;
5050
5151 /**
52- * @var string $url The basic api url to fetch history weather data from.
52+ * @var string The basic api url to fetch history weather data from.
5353 */
54- private $ weatherHistoryUrl = " http://api.openweathermap.org/data/2.5/history/city? " ;
54+ private $ weatherHistoryUrl = ' http://api.openweathermap.org/data/2.5/history/city? ' ;
5555
5656 /**
5757 * The copyright notice. This is no official text, this hint was created regarding to http://openweathermap.org/copyright.
5858 *
59- * @var string $copyright
59+ * @var string
6060 */
61- const COPYRIGHT = " Weather data from <a href= \ "http://www.openweathermap.org \ ">OpenWeatherMap.org</a> " ;
61+ const COPYRIGHT = ' Weather data from <a href="http://www.openweathermap.org">OpenWeatherMap.org</a> ' ;
6262
6363 /**
64- * @var \Cmfcmf\OpenWeatherMap\AbstractCache|bool $cacheClass The cache class.
64+ * @var \Cmfcmf\OpenWeatherMap\AbstractCache|bool The cache class.
6565 */
6666 private $ cacheClass = false ;
6767
@@ -74,16 +74,21 @@ class OpenWeatherMap
7474 * @var bool
7575 */
7676 private $ wasCached = false ;
77-
77+
7878 /**
7979 * @var FetcherInterface The url fetcher.
8080 */
81-
8281 private $ fetcher ;
8382
83+ /**
84+ * @var string
85+ */
86+ private $ apiKey = '' ;
87+
8488 /**
8589 * Constructs the OpenWeatherMap object.
8690 *
91+ * @param null|string $appid The API key. Defaults to null.
8792 * @param null|FetcherInterface $fetcher The interface to fetch the data from OpenWeatherMap. Defaults to
8893 * CurlFetcher() if cURL is available. Otherwise defaults to
8994 * FileGetContentsFetcher() using 'file_get_contents()'.
@@ -92,15 +97,16 @@ class OpenWeatherMap
9297 * @param int $seconds How long weather data shall be cached. Default 10 minutes.
9398 *
9499 * @throws \Exception If $cache is neither false nor a valid callable extending Cmfcmf\OpenWeatherMap\Util\Cache.
100+ *
95101 * @api
96102 */
97103 public function __construct ($ fetcher = null , $ cacheClass = false , $ seconds = 600 )
98104 {
99105 if ($ cacheClass !== false && !($ cacheClass instanceof AbstractCache)) {
100- throw new \Exception (" The cache class must implement the FetcherInterface! " );
106+ throw new \Exception (' The cache class must implement the FetcherInterface! ' );
101107 }
102108 if (!is_numeric ($ seconds )) {
103- throw new \Exception ("\ $seconds must be numeric. " );
109+ throw new \Exception (' $seconds must be numeric. ' );
104110 }
105111 if (!isset ($ fetcher )) {
106112 $ fetcher = (function_exists ('curl_version ' )) ? new CurlFetcher () : new FileGetContentsFetcher ();
@@ -114,6 +120,30 @@ public function __construct($fetcher = null, $cacheClass = false, $seconds = 600
114120 $ this ->fetcher = $ fetcher ;
115121 }
116122
123+ /**
124+ * Sets the API Key.
125+ *
126+ * @param string API key for the OpenWeatherMap account making the connection.
127+ *
128+ * @api
129+ */
130+ public function setApiKey ($ appid )
131+ {
132+ $ this ->apiKey = $ appid ;
133+ }
134+
135+ /**
136+ * Returns the API Key.
137+ *
138+ * @return string
139+ *
140+ * @api
141+ */
142+ public function getApiKey ()
143+ {
144+ return $ this ->apiKey ;
145+ }
146+
117147 /**
118148 * Returns the current weather at the place you specified as an object.
119149 *
@@ -122,7 +152,7 @@ public function __construct($fetcher = null, $cacheClass = false, $seconds = 600
122152 * @param string $lang The language to use for descriptions, default is 'en'. For possible values see below.
123153 * @param string $appid Your app id, default ''. See http://openweathermap.org/appid for more details.
124154 *
125- * @throws OpenWeatherMap\Exception If OpenWeatherMap returns an error.
155+ * @throws OpenWeatherMap\Exception If OpenWeatherMap returns an error.
126156 * @throws \InvalidArgumentException If an argument error occurs.
127157 *
128158 * @return CurrentWeather The weather object.
@@ -170,7 +200,7 @@ public function getWeather($query, $units = 'imperial', $lang = 'en', $appid = '
170200 if (isset ($ error ['message ' ])) {
171201 throw new OWMException ($ error ['message ' ], $ error ['cod ' ]);
172202 } else {
173- throw new OWMException ('Unknown fatal error: OpenWeatherMap returned the following json object: ' . $ answer );
203+ throw new OWMException ('Unknown fatal error: OpenWeatherMap returned the following json object: ' . $ answer );
174204 }
175205 }
176206
@@ -186,7 +216,7 @@ public function getWeather($query, $units = 'imperial', $lang = 'en', $appid = '
186216 * @param string $appid Your app id, default ''. See http://openweathermap.org/appid for more details.
187217 * @param int $days For how much days you want to get a forecast. Default 1, maximum: 16.
188218 *
189- * @throws OpenWeatherMap\Exception If OpenWeatherMap returns an error.
219+ * @throws OpenWeatherMap\Exception If OpenWeatherMap returns an error.
190220 * @throws \InvalidArgumentException If an argument error occurs.
191221 *
192222 * @return WeatherForecast The WeatherForecast object.
@@ -240,7 +270,7 @@ public function getWeatherForecast($query, $units = 'imperial', $lang = 'en', $a
240270 if (isset ($ error ['message ' ])) {
241271 throw new OWMException ($ error ['message ' ], $ error ['cod ' ]);
242272 } else {
243- throw new OWMException ('Unknown fatal error: OpenWeatherMap returned the following json object: ' . $ answer );
273+ throw new OWMException ('Unknown fatal error: OpenWeatherMap returned the following json object: ' . $ answer );
244274 }
245275 }
246276
@@ -250,15 +280,15 @@ public function getWeatherForecast($query, $units = 'imperial', $lang = 'en', $a
250280 /**
251281 * Returns the weather history for the place you specified as an object.
252282 *
253- * @param array|int|string $query The place to get weather information for. For possible values see below.
283+ * @param array|int|string $query The place to get weather information for. For possible values see below.
254284 * @param \DateTime $start
255285 * @param int $endOrCount
256286 * @param string $type
257- * @param string $units Can be either 'metric' or 'imperial' (default). This affects almost all units returned.
258- * @param string $lang The language to use for descriptions, default is 'en'. For possible values see below.
259- * @param string $appid Your app id, default ''. See http://openweathermap.org/appid for more details.
287+ * @param string $units Can be either 'metric' or 'imperial' (default). This affects almost all units returned.
288+ * @param string $lang The language to use for descriptions, default is 'en'. For possible values see below.
289+ * @param string $appid Your app id, default ''. See http://openweathermap.org/appid for more details.
260290 *
261- * @throws OpenWeatherMap\Exception If OpenWeatherMap returns an error.
291+ * @throws OpenWeatherMap\Exception If OpenWeatherMap returns an error.
262292 * @throws \InvalidArgumentException If an argument error occurs.
263293 *
264294 * @return WeatherHistory The WeatherHistory object.
@@ -295,7 +325,7 @@ public function getWeatherHistory($query, \DateTime $start, $endOrCount = 1, $ty
295325 throw new \InvalidArgumentException ('$type must be either "tick", "hour" or "day" ' );
296326 }
297327
298- $ xml = json_decode ($ this ->getRawWeatherHistory ($ query , $ start , $ endOrCount , $ type , $ units , $ lang , $ appid ), true );
328+ $ xml = json_decode ($ this ->getRawWeatherHistory ($ query , $ start , $ endOrCount , $ type , $ units , $ lang , empty ( $ appid ) ? $ this -> apiKey : $ appid ), true );
299329
300330 if ($ xml ['cod ' ] != 200 ) {
301331 throw new OWMException ($ xml ['message ' ], $ xml ['cod ' ]);
@@ -415,6 +445,7 @@ public function getRawHourlyForecastData($query, $units = 'imperial', $lang = 'e
415445 * @param int $cnt How many days of forecast shall be returned? Maximum (and default): 16
416446 *
417447 * @throws \InvalidArgumentException If $cnt is higher than 16.
448+ *
418449 * @return string Returns false on failure and the fetched data in the format you specified on success.
419450 *
420451 * Warning If an error occurred, OpenWeatherMap returns data in json format ALWAYS
@@ -450,24 +481,24 @@ public function getRawDailyForecastData($query, $units = 'imperial', $lang = 'en
450481 if ($ cnt > 16 ) {
451482 throw new \InvalidArgumentException ('$cnt must be 16 or below! ' );
452483 }
453- $ url = $ this ->buildUrl ($ query , $ units , $ lang , $ appid , $ mode , $ this ->weatherDailyForecastUrl ) . "&cnt= $ cnt " ;
484+ $ url = $ this ->buildUrl ($ query , $ units , $ lang , $ appid , $ mode , $ this ->weatherDailyForecastUrl ). "&cnt= $ cnt " ;
454485
455486 return $ this ->cacheOrFetchResult ($ url );
456487 }
457488
458489 /**
459490 * Directly returns the xml/json/html string returned by OpenWeatherMap for the daily forecast.
460491 *
461- * @param array|int|string $query The place to get weather information for. For possible values see below.
462- * @param \DateTime $start The \DateTime object of the date to get the first weather information from.
463- * @param \DateTime|int $endOrCount Can be either a \DateTime object representing the end of the period to
464- * receive weather history data for or an integer counting the number of
465- * reports requested.
466- * @param string $type The period of the weather history requested. Can be either be either "tick",
467- * "hour" or "day".
468- * @param string $units Can be either 'metric' or 'imperial' (default). This affects almost all units returned.
469- * @param string $lang The language to use for descriptions, default is 'en'. For possible values see below.
470- * @param string $appid Your app id, default ''. See http://openweathermap.org/appid for more details.
492+ * @param array|int|string $query The place to get weather information for. For possible values see below.
493+ * @param \DateTime $start The \DateTime object of the date to get the first weather information from.
494+ * @param \DateTime|int $endOrCount Can be either a \DateTime object representing the end of the period to
495+ * receive weather history data for or an integer counting the number of
496+ * reports requested.
497+ * @param string $type The period of the weather history requested. Can be either be either "tick",
498+ * "hour" or "day".
499+ * @param string $units Can be either 'metric' or 'imperial' (default). This affects almost all units returned.
500+ * @param string $lang The language to use for descriptions, default is 'en'. For possible values see below.
501+ * @param string $appid Your app id, default ''. See http://openweathermap.org/appid for more details.
471502 *
472503 * @throws \InvalidArgumentException
473504 *
@@ -507,7 +538,7 @@ public function getRawWeatherHistory($query, \DateTime $start, $endOrCount = 1,
507538 throw new \InvalidArgumentException ('$type must be either "tick", "hour" or "day" ' );
508539 }
509540
510- $ queryUrl = $ this ->weatherHistoryUrl . $ this ->buildQueryUrlParameter ($ query ) . "&start= {$ start ->format ('U ' )}" ;
541+ $ queryUrl = $ this ->weatherHistoryUrl . $ this ->buildQueryUrlParameter ($ query ). "&start= {$ start ->format ('U ' )}" ;
511542
512543 if ($ endOrCount instanceof \DateTime) {
513544 $ queryUrl .= "&end= {$ endOrCount ->format ('U ' )}" ;
@@ -516,11 +547,9 @@ public function getRawWeatherHistory($query, \DateTime $start, $endOrCount = 1,
516547 } else {
517548 throw new \InvalidArgumentException ('$endOrCount must be either a \DateTime or a positive integer. ' );
518549 }
519- $ queryUrl .= "&type= $ type&units= $ units&lang= $ lang " ;
550+ $ queryUrl .= "&type= $ type&units= $ units&lang= $ lang&APPID= " ;
520551
521- if (!empty ($ appid )) {
522- $ queryUrl .= "&APPID= $ appid " ;
523- }
552+ $ queryUrl .= empty ($ appid ) ? $ this ->apiKey : $ appid ;
524553
525554 return $ this ->cacheOrFetchResult ($ queryUrl );
526555 }
@@ -540,9 +569,10 @@ private function cacheOrFetchResult($url)
540569 /** @var \Cmfcmf\OpenWeatherMap\AbstractCache $cache */
541570 $ cache = $ this ->cacheClass ;
542571 $ cache ->setSeconds ($ this ->seconds );
543- $ this ->wasCached = false ;
572+ $ this ->wasCached = false ;
544573 if ($ cache ->isCached ($ url )) {
545- $ this ->wasCached =true ;
574+ $ this ->wasCached = true ;
575+
546576 return $ cache ->getCached ($ url );
547577 }
548578 $ result = $ this ->fetcher ->fetch ($ url );
@@ -562,7 +592,7 @@ private function cacheOrFetchResult($url)
562592 * @param $lang
563593 * @param $appid
564594 * @param $mode
565- * @param string $url The url to prepend.
595+ * @param string $url The url to prepend.
566596 *
567597 * @return bool|string The fetched url, false on failure.
568598 *
@@ -572,10 +602,8 @@ private function buildUrl($query, $units, $lang, $appid, $mode, $url)
572602 {
573603 $ queryUrl = $ this ->buildQueryUrlParameter ($ query );
574604
575- $ url = $ url . "$ queryUrl&units= $ units&lang= $ lang&mode= $ mode " ;
576- if (!empty ($ appid )) {
577- $ url .= "&APPID= $ appid " ;
578- }
605+ $ url = $ url ."$ queryUrl&units= $ units&lang= $ lang&mode= $ mode&APPID= " ;
606+ $ url .= empty ($ appid ) ? $ this ->apiKey : $ appid ;
579607
580608 return $ url ;
581609 }
@@ -586,24 +614,25 @@ private function buildUrl($query, $units, $lang, $appid, $mode, $url)
586614 * @param $query
587615 *
588616 * @return string The built query string for the url.
617+ *
589618 * @throws \InvalidArgumentException If the query parameter is invalid.
590619 *
591620 * @internal
592621 */
593622 private function buildQueryUrlParameter ($ query )
594623 {
595624 switch ($ query ) {
596- case ( is_array ($ query ) && isset ($ query ['lat ' ]) && isset ($ query ['lon ' ]) && is_numeric ($ query ['lat ' ]) && is_numeric ($ query ['lon ' ]) ):
625+ case is_array ($ query ) && isset ($ query ['lat ' ]) && isset ($ query ['lon ' ]) && is_numeric ($ query ['lat ' ]) && is_numeric ($ query ['lon ' ]):
597626 return "lat= {$ query ['lat ' ]}&lon= {$ query ['lon ' ]}" ;
598- case ( is_numeric ($ query) ):
627+ case is_numeric ($ query ):
599628 return "id= $ query " ;
600- case ( is_string ($ query) ):
601- return " q= " . urlencode ($ query );
629+ case is_string ($ query ):
630+ return ' q= ' . urlencode ($ query );
602631 default :
603632 throw new \InvalidArgumentException ('Error: $query has the wrong format. See the documentation of OpenWeatherMap::getRawData() to read about valid formats. ' );
604633 }
605634 }
606-
635+
607636 /**
608637 * Returns whether or not the last result was fetched from the cache.
609638 *
@@ -613,4 +642,4 @@ public function wasCached()
613642 {
614643 return $ this ->wasCached ;
615644 }
616- }
645+ }
0 commit comments