Created
January 17, 2014 09:24
-
-
Save saturnxxi/8470554 to your computer and use it in GitHub Desktop.
NetipProvider for Geocoder library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace My\Bundle\Utils\Geo; | |
use Geocoder\Exception\NoResultException; | |
use Geocoder\Exception\UnsupportedException; | |
use Geocoder\Provider\AbstractProvider; | |
use Geocoder\Provider\ProviderInterface; | |
class NetipProvider extends AbstractProvider implements ProviderInterface | |
{ | |
/** | |
* @var string | |
*/ | |
const NETIP_ENDPOINT_URL = 'http://www.netip.de/search?query=%s'; | |
/** | |
* {@inheritDoc} | |
*/ | |
public function getGeocodedData($address) | |
{ | |
if (!filter_var($address, FILTER_VALIDATE_IP)) { | |
throw new UnsupportedException('The Netip does not support street addresses.'); | |
} | |
if (in_array($address, array('127.0.0.1', '::1'))) { | |
return array($this->getLocalhostDefaults()); | |
} | |
$query = sprintf(self::NETIP_ENDPOINT_URL, $address); | |
return $this->executeQuery($query); | |
} | |
/** | |
* {@inheritDoc} | |
*/ | |
public function getReversedData(array $coordinates) | |
{ | |
throw new UnsupportedException('The NetipProvider is not able to do reverse geocoding.'); | |
} | |
/** | |
* {@inheritDoc} | |
*/ | |
public function getName() | |
{ | |
return 'netip'; | |
} | |
protected function executeQuery($query) | |
{ | |
$content = $this->getAdapter()->getContent($query); | |
if (null === $content || '' === $content) { | |
throw new NoResultException(sprintf('Could not execute query %s', $query)); | |
} | |
$patterns['country'] = '#Country: (.*?) #i'; | |
$patterns['city'] = '#City: (.*?)<br#i'; | |
$patterns['latitude'] = '#var latitude = (.*?);#i'; | |
$patterns['longitude'] = '#var longitude = (.*?);#i'; | |
$data = array(); | |
foreach ($patterns as $key => $pattern) { | |
$data[$key] = preg_match($pattern, $content, $value) && !empty($value[1]) ? $value[1] : 'false'; | |
} | |
$data = array_filter($data); | |
if (empty($data) || !isset($data['latitude']) || !isset($data['longitude'])) { | |
throw new NoResultException(sprintf('Could not find data for query %s', $query)); | |
} | |
return array(array_merge($this->getDefaults(), $data)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment