Skip to content

Instantly share code, notes, and snippets.

@saturnxxi
Created January 17, 2014 09:24
Show Gist options
  • Save saturnxxi/8470554 to your computer and use it in GitHub Desktop.
Save saturnxxi/8470554 to your computer and use it in GitHub Desktop.
NetipProvider for Geocoder library
<?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: (.*?)&nbsp;#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