'xml', 'num_of_days' => 5, 'q' => '', # e.g. 48.00,11.00 'key' => '', 'free' => true, ]; public function __construct() { $this->settings = (array)Configure::read('Weather') + $this->settings; } /** * Get weather data - cached. * Provide cache=>false to prevent/clear the cache * * @return array Data or false on failure */ public function get($q, array $options = []) { $options += $this->settings; $options['q'] = urlencode($q); $data = $this->_get('weather.ashx', $options); if (empty($data) || empty($data['data'])) { return false; } return $data['data']; } /** * Get weather conditions - cached. * Provide cache=>false to prevent/clear the cache * * @return array */ public function conditions() { $options = []; $options['format'] = $this->settings['format']; if ($options['format'] === 'json') { $options['format'] = 'xml'; } $conditions = $this->_get('wwoConditionCodes.xml', $options); if (empty($conditions) || empty($conditions['codes']['condition'])) { return []; } return $conditions['codes']['condition']; } //.../feed/weather.ashx?q=Neufahrn&format=json&num_of_days=2&key=598dfbdaeb121715111208 /** * WeatherLib::_get() * * @param mixed $url * @param mixed $options * @return array|false */ protected function _get($url, $options) { if (isset($options['cache'])) { $cache = $options['cache']; unset($options['cache']); } $url = $this->_url($url, $options); if (!empty($cache)) { if (!Cache::isInitialized('data')) { Cache::set('duration', $cache, 'data'); } if ($cacheContent = Cache::read(md5($url), 'data')) { return $cacheContent; } } $Socket = new HttpSocket(['timeout' => 5]); $file = $Socket->get($url); $content = $file->body; if (empty($content)) { return false; } switch ($options['format']) { case 'json': $res = json_decode($content, true); break; case 'xml': $res = Xml::build($content); $res = Xml::toArray($res); break; case 'csv': default: //TODO? $res = []; throw new CakeException('Not implemented yet'); } if (!empty($cache)) { Cache::write(md5($url), $res, 'data'); } if (empty($res)) { return false; } return $res; } /** * @return string Url */ protected function _url($url, $options = []) { $params = []; foreach ($options as $key => $option) { $params[] = $key . '=' . $option; } $params = (!empty($params) ? '?' : '') . implode('&', $params); $domain = $this->settings['free'] ? static::API_URL_FREE : static::API_URL; return $domain . $url . $params; } }