_cachePath = BASE_PATH . '/tmp/geocode/cache'; $this->_logPath = BASE_PATH . '/tmp/geocode/log'; $this->_logFileName = $this->_logPath . '/' . date('Y-m-d') . '.log'; $this->_initPath($this->_cachePath); $this->_initPath($this->_logPath); $frontendOptions = array('automatic_serialization' => true, 'lifetime' => null); $backendOptions = array( 'cache_dir' => $this->_cachePath . '/', 'cache_file_perm' => 0664, ); $this->_cache = Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions); } protected function _initPath($path) { if (!file_exists($path)) { umask(0); if (false === mkdir($path, 0777, true)) { throw new Exception('Can not create path'); } } } public function findAddress($address) { $this->_cache->getBackend()->setOption('file_name_prefix', 'address'); $cacheId = preg_replace('/[^a-zA-Z0-9_]/', '', $address); if (empty($cacheId)) { return false; } if (false !== ($response = $this->_cache->load($cacheId))) { return $response['results']; } $query = array( 'sensor' => json_encode($this->_sensor), 'address' => $address ); $url = $this->_url . '/' . $this->_format . '?' . http_build_query($query); try { $client = new Zend_Http_Client($url); $httpResponse = $client->request(); $body = $httpResponse->getBody(); $response = Zend_Json::decode($body); if (0 === strcasecmp($response['status'], 'OK')) { $this->_cache->save($response, $cacheId); return $response['results']; } else { $this->log('Invalid Response: see detail in file ' . $this->logResponse($httpResponse)); } } catch (Exception $e) { $this->log('Exception: ' . $e->getMessage()); } return false; } public function findAddressLocation($address) { if (false !== ($results = $this->findAddress($address))) { $firstResult = reset($results); return Qs_Array::get($firstResult, 'geometry[location]', false); } return false; } public function log($text) { if (false === ($handle = fopen($this->_logFileName, 'w+'))) { return $this; } fwrite($handle, date('Y-m-d H:i:s') . "\t" . $_SERVER['REMOTE_ADDR'] . "\t" . $text. "\n"); fclose($handle); return $this; } public function logResponse(Zend_Http_Response $httpResponse) { $fileName = $this->_logPath . '/response' . date('H-i:s') . '.log'; $handle = fopen($fileName, 'w+'); fwrite($handle, $httpResponse->getRawBody()); fclose($handle); return basename($fileName); } }