From 6a8a65dfed991dc10f13b7eafb6adfd7fed3f6f8 Mon Sep 17 00:00:00 2001 From: William DURAND Date: Sat, 14 Dec 2013 13:26:17 +0100 Subject: [PATCH 001/235] Add doctrine/cache as dev requirement --- composer.json | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/composer.json b/composer.json index d4da78f6..c3e0d559 100644 --- a/composer.json +++ b/composer.json @@ -12,12 +12,13 @@ ], "require": { "symfony/framework-bundle": "~2.0", - "willdurand/geocoder": "~1.0", + "willdurand/geocoder": "~2.3", "symfony/console": "~2.0" }, "require-dev": { "symfony/yaml": "~2.0", - "maxromanovsky/php-maxmind-geoip": "~1.12" + "maxromanovsky/php-maxmind-geoip": "~1.12", + "doctrine/cache": "~1.3" }, "autoload": { "psr-0": { "Bazinga\\Bundle\\GeocoderBundle": "" } @@ -25,7 +26,7 @@ "target-dir": "Bazinga/Bundle/GeocoderBundle", "extra": { "branch-alias": { - "dev-master": "1.5-dev" + "dev-master": "2.0-dev" } } } From 1920222cb522396a355d2c297be5cdd0ae938198 Mon Sep 17 00:00:00 2001 From: William DURAND Date: Sat, 14 Dec 2013 13:44:06 +0100 Subject: [PATCH 002/235] Fix CacheProvider --- Provider/CacheProvider.php | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/Provider/CacheProvider.php b/Provider/CacheProvider.php index 710dbeed..b3e4806d 100644 --- a/Provider/CacheProvider.php +++ b/Provider/CacheProvider.php @@ -10,6 +10,7 @@ namespace Bazinga\Bundle\GeocoderBundle\Provider; +use Geocoder\Geocoder; use Geocoder\Provider\ProviderInterface; use Doctrine\Common\Cache\Cache; @@ -19,12 +20,12 @@ class CacheProvider implements ProviderInterface { /** - * @var \Doctrine\Common\Cache\Cache + * @var Cache */ private $cache; /** - * @var \Geocoder\Provider\ProviderInterface + * @var ProviderInterface */ private $provider; @@ -38,6 +39,11 @@ class CacheProvider implements ProviderInterface */ private $locale; + /** + * @var integer + */ + private $maxResults = Geocoder::MAX_RESULTS; + /** * Constructor * @@ -48,10 +54,10 @@ class CacheProvider implements ProviderInterface */ public function __construct(Cache $cache, ProviderInterface $provider, $lifetime = 0, $locale = null) { - $this->cache = $cache; + $this->cache = $cache; $this->provider = $provider; $this->lifetime = $lifetime; - $this->locale = $locale; + $this->locale = $locale; } /** @@ -95,4 +101,14 @@ public function getName() { return 'cache'; } + + /** + * {@inheritDoc} + */ + public function setMaxResults($maxResults) + { + $this->maxResults = $maxResults; + + return $this; + } } From ed408bb1a4b85a9e173a2d13b525c7ecdcfe773f Mon Sep 17 00:00:00 2001 From: Antoine Corcy Date: Sat, 14 Dec 2013 13:48:03 +0100 Subject: [PATCH 003/235] removes yahoo provider --- DependencyInjection/BazingaGeocoderExtension.php | 9 --------- DependencyInjection/Configuration.php | 8 -------- .../DependencyInjection/BazingaGeocoderExtensionTest.php | 1 - Tests/DependencyInjection/Fixtures/config.yml | 3 --- 4 files changed, 21 deletions(-) diff --git a/DependencyInjection/BazingaGeocoderExtension.php b/DependencyInjection/BazingaGeocoderExtension.php index 1fd4ba89..5ea7cd3a 100644 --- a/DependencyInjection/BazingaGeocoderExtension.php +++ b/DependencyInjection/BazingaGeocoderExtension.php @@ -75,15 +75,6 @@ public function load(array $configs, ContainerBuilder $container) $this->addProvider('ip_info_db', array($ipInfoDbParams['api_key'])); } - if (isset($config['providers']['yahoo'])) { - $yahooParams = $config['providers']['yahoo']; - - $this->addProvider('yahoo', array( - $yahooParams['api_key'], - $yahooParams['locale'], - )); - } - if (isset($config['providers']['cloudmade'])) { $cloudMadeParams = $config['providers']['cloudmade']; diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index e1b22969..64c2095d 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -90,14 +90,6 @@ public function getConfigTreeBuilder() ->end() ->end() ->end() - ->arrayNode('yahoo') - ->children() - ->scalarNode('api_key') - ->isRequired()->cannotBeEmpty() - ->end() - ->scalarNode('locale')->defaultNull()->end() - ->end() - ->end() ->arrayNode('cloudmade') ->children() ->scalarNode('api_key') diff --git a/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php b/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php index cf55a2be..e531596a 100644 --- a/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php +++ b/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php @@ -51,7 +51,6 @@ public function testLoad() 'bing_maps' => 'Geocoder\\Provider\\BingMapsProvider', 'cache' => 'Bazinga\\Bundle\\GeocoderBundle\\Provider\\CacheProvider', 'ip_info_db' => 'Geocoder\\Provider\\IpInfoDbProvider', - 'yahoo' => 'Geocoder\\Provider\\YahooProvider', 'cloudmade' => 'Geocoder\\Provider\\CloudMadeProvider', 'google_maps' => 'Geocoder\\Provider\\GoogleMapsProvider', 'google_maps_business' => 'Geocoder\\Provider\\GoogleMapsBusinessProvider', diff --git a/Tests/DependencyInjection/Fixtures/config.yml b/Tests/DependencyInjection/Fixtures/config.yml index c4d2ce5d..3d22f1ef 100644 --- a/Tests/DependencyInjection/Fixtures/config.yml +++ b/Tests/DependencyInjection/Fixtures/config.yml @@ -15,9 +15,6 @@ bazinga_geocoder: lifetime: 86400 ip_info_db: api_key: 123 - yahoo: - api_key: 123 - locale: en_US cloudmade: api_key: 123 google_maps: From 6b9b959f3afde972f45ce34ac762c16aa533fcf8 Mon Sep 17 00:00:00 2001 From: Antoine Corcy Date: Sat, 14 Dec 2013 13:54:31 +0100 Subject: [PATCH 004/235] fix openstreetmap provider --- DependencyInjection/BazingaGeocoderExtension.php | 6 +++--- DependencyInjection/Configuration.php | 2 +- Resources/config/services.xml | 2 +- Tests/DependencyInjection/BazingaGeocoderExtensionTest.php | 2 +- Tests/DependencyInjection/Fixtures/config.yml | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/DependencyInjection/BazingaGeocoderExtension.php b/DependencyInjection/BazingaGeocoderExtension.php index 5ea7cd3a..975b79dc 100644 --- a/DependencyInjection/BazingaGeocoderExtension.php +++ b/DependencyInjection/BazingaGeocoderExtension.php @@ -103,10 +103,10 @@ public function load(array $configs, ContainerBuilder $container) )); } - if (isset($config['providers']['openstreetmaps'])) { - $openstreetMapsParams = $config['providers']['openstreetmaps']; + if (isset($config['providers']['openstreetmap'])) { + $openstreetMapsParams = $config['providers']['openstreetmap']; - $this->addProvider('openstreetmaps', array($openstreetMapsParams['locale'])); + $this->addProvider('openstreetmap', array($openstreetMapsParams['locale'])); } if (isset($config['providers']['geoip'])) { diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 64c2095d..8152523a 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -113,7 +113,7 @@ public function getConfigTreeBuilder() ->booleanNode('use_ssl')->defaultFalse()->end() ->end() ->end() - ->arrayNode('openstreetmaps') + ->arrayNode('openstreetmap') ->children() ->scalarNode('locale')->defaultNull()->end() ->end() diff --git a/Resources/config/services.xml b/Resources/config/services.xml index fbc13869..c2f28512 100644 --- a/Resources/config/services.xml +++ b/Resources/config/services.xml @@ -15,7 +15,7 @@ Geocoder\Provider\IpInfoDbProvider Geocoder\Provider\YahooProvider Geocoder\Provider\CloudMadeProvider - Geocoder\Provider\OpenStreetMapsProvider + Geocoder\Provider\OpenStreetMapProvider Geocoder\Provider\GeoipProvider Geocoder\Provider\MapQuestProvider Geocoder\Provider\OIORestProvider diff --git a/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php b/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php index e531596a..06be8ff4 100644 --- a/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php +++ b/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php @@ -54,7 +54,7 @@ public function testLoad() 'cloudmade' => 'Geocoder\\Provider\\CloudMadeProvider', 'google_maps' => 'Geocoder\\Provider\\GoogleMapsProvider', 'google_maps_business' => 'Geocoder\\Provider\\GoogleMapsBusinessProvider', - 'openstreetmaps' => 'Geocoder\\Provider\\OpenStreetMapsProvider', + 'openstreetmap' => 'Geocoder\\Provider\\OpenStreetMapProvider', 'host_ip' => 'Geocoder\\Provider\\HostIpProvider', 'free_geo_ip' => 'Geocoder\\Provider\\FreeGeoIpProvider', 'map_quest' => 'Geocoder\\Provider\\MapQuestProvider', diff --git a/Tests/DependencyInjection/Fixtures/config.yml b/Tests/DependencyInjection/Fixtures/config.yml index 3d22f1ef..6d1c15d4 100644 --- a/Tests/DependencyInjection/Fixtures/config.yml +++ b/Tests/DependencyInjection/Fixtures/config.yml @@ -25,7 +25,7 @@ bazinga_geocoder: api_key: 123 locale: en_US region: en_US - openstreetmaps: + openstreetmap: locale: en_US host_ip: ~ # geoip: ~ From 499cbd335bbf1eb6bbaa991e043d32e6854db2c9 Mon Sep 17 00:00:00 2001 From: William DURAND Date: Sat, 14 Dec 2013 14:05:13 +0100 Subject: [PATCH 005/235] Update documentation --- Resources/doc/index.md | 31 +++++++++++++++---------------- 1 file changed, 15 insertions(+), 16 deletions(-) diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 432b91bf..7d437e32 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -22,14 +22,16 @@ to your `composer.json` file: Register the bundle in `app/AppKernel.php`: - // app/AppKernel.php - public function registerBundles() - { - return array( - // ... - new Bazinga\Bundle\GeocoderBundle\BazingaGeocoderBundle(), - ); - } +```php +// app/AppKernel.php +public function registerBundles() +{ + return array( + // ... + new Bazinga\Bundle\GeocoderBundle\BazingaGeocoderBundle(), + ); +} +``` Enable the bundle's configuration in `app/config/config.yml`: @@ -73,7 +75,7 @@ information in your development environment, for instance: // Retrieve information from the current user (by its IP address) $result = $this->container ->get('bazinga_geocoder.geocoder') - ->using('yahoo') + ->using('google_maps') ->geocode($request->server->get('REMOTE_ADDR')); // Find the 5 nearest objects (15km) from the current user. @@ -173,7 +175,7 @@ __Configuration example:__ services: acme_cache_adapter: - class: "Doctrine\Common\Cache\ApcCache" + class: "Doctrine\\Common\\Cache\\ApcCache" bazinga_geocoder: providers: @@ -183,8 +185,8 @@ bazinga_geocoder: google_maps: ~ ``` -> Tip: If you want to configure the cache adapter, -> we recommend the [liip/doctrine-cache-bundle](https://github.com/liip/LiipDoctrineCacheBundle.git). +> **Tip:** If you want to configure the cache adapter, +> we recommend the [liip/doctrine-cache-bundle](https://github.com/liip/LiipDoctrineCacheBundle). ### Symfony2 Profiler Integration @@ -226,9 +228,6 @@ bazinga_geocoder: lifetime: 86400 ip_info_db: api_key: ~ # Required - yahoo: - api_key: ~ # Required - locale: ~ cloudmade: api_key: ~ # Required google_maps: @@ -240,7 +239,7 @@ bazinga_geocoder: api_key: ~ region: ~ use_ssl: false - openstreetmaps: + openstreetmap: locale: ~ host_ip: [] geoip: [] From 1533d976af79157cc3165a5cb61710ae5e8cc198 Mon Sep 17 00:00:00 2001 From: William DURAND Date: Sat, 14 Dec 2013 14:13:26 +0100 Subject: [PATCH 006/235] Add note on the readme about versions --- README.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index a4e3c1f2..1ef03295 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,10 @@ Status](https://secure.travis-ci.org/geocoder-php/BazingaGeocoderBundle.png)](ht Integration of the [**Geocoder**](http://github.com/geocoder-php/Geocoder) library into Symfony2. +**Important:** this bundle is developed in sync with [Geocoder's +repository](http://github.com/geocoder-php/Geocoder). If you are using Geocoder +`1.x`, you need to use the `~1.5` releases of the bundle (or lower). + Documentation ------------- @@ -15,7 +19,8 @@ For documentation, see: Resources/doc/ -[Read the documentation](https://github.com/geocoder-php/BazingaGeocoderBundle/blob/master/Resources/doc/index.md) +[Read the +documentation](https://github.com/geocoder-php/BazingaGeocoderBundle/blob/master/Resources/doc/index.md) Contributing From 9f9a2c260660db40d34b077cc534f28b5cbd9183 Mon Sep 17 00:00:00 2001 From: YvanL Date: Wed, 11 Dec 2013 07:37:32 +0100 Subject: [PATCH 007/235] ApiKey Required for MapQuest provider Changes related to : https://github.com/geocoder-php/Geocoder/pull/276 --- DependencyInjection/BazingaGeocoderExtension.php | 4 +++- DependencyInjection/Configuration.php | 8 +++++++- Resources/doc/index.md | 3 ++- Tests/DependencyInjection/Fixtures/config.yml | 3 ++- 4 files changed, 14 insertions(+), 4 deletions(-) diff --git a/DependencyInjection/BazingaGeocoderExtension.php b/DependencyInjection/BazingaGeocoderExtension.php index 1fd4ba89..bbd63c7d 100644 --- a/DependencyInjection/BazingaGeocoderExtension.php +++ b/DependencyInjection/BazingaGeocoderExtension.php @@ -123,7 +123,9 @@ public function load(array $configs, ContainerBuilder $container) } if (isset($config['providers']['mapquest'])) { - $this->addProvider('mapquest'); + $mapquestParams = $config['providers']['mapquest']; + + $this->addProvider('mapquest', array($mapquestParams['api_key'])); } if (isset($config['providers']['oiorest'])) { diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index e96e4f1a..aacf1eb9 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -129,7 +129,13 @@ public function getConfigTreeBuilder() ->arrayNode('host_ip')->end() ->arrayNode('geoip')->end() ->arrayNode('free_geo_ip')->end() - ->arrayNode('mapquest')->end() + ->arrayNode('mapquest') + ->children() + ->scalarNode('api_key') + ->isRequired()->cannotBeEmpty() + ->end() + ->end() + ->end() ->arrayNode('oiorest')->end() ->arrayNode('geocoder_ca')->end() ->arrayNode('geocoder_us')->end() diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 432b91bf..16e15f55 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -245,7 +245,8 @@ bazinga_geocoder: host_ip: [] geoip: [] free_geo_ip: [] - mapquest: [] + mapquest: + api_key: ~ # Required oiorest: [] geocoder_ca: [] geocoder_us: [] diff --git a/Tests/DependencyInjection/Fixtures/config.yml b/Tests/DependencyInjection/Fixtures/config.yml index c4d2ce5d..f004e525 100644 --- a/Tests/DependencyInjection/Fixtures/config.yml +++ b/Tests/DependencyInjection/Fixtures/config.yml @@ -33,7 +33,8 @@ bazinga_geocoder: host_ip: ~ # geoip: ~ free_geo_ip: ~ - mapquest: ~ + mapquest: + api_key: 123 oiorest: ~ geocoder_ca: ~ geocoder_us: ~ From f24f6993cb38be7f9ca3b49e568a19ac844df44e Mon Sep 17 00:00:00 2001 From: William DURAND Date: Sat, 14 Dec 2013 15:17:27 +0100 Subject: [PATCH 008/235] cs --- DependencyInjection/BazingaGeocoderExtension.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DependencyInjection/BazingaGeocoderExtension.php b/DependencyInjection/BazingaGeocoderExtension.php index ad7ea00a..1171f5f5 100644 --- a/DependencyInjection/BazingaGeocoderExtension.php +++ b/DependencyInjection/BazingaGeocoderExtension.php @@ -115,7 +115,7 @@ public function load(array $configs, ContainerBuilder $container) if (isset($config['providers']['mapquest'])) { $mapquestParams = $config['providers']['mapquest']; - + $this->addProvider('mapquest', array($mapquestParams['api_key'])); } From 27477574d7cd6a165118fb0f53a1448b7bf59133 Mon Sep 17 00:00:00 2001 From: William DURAND Date: Sat, 14 Dec 2013 22:18:23 +0100 Subject: [PATCH 009/235] [doc] fix links --- Resources/doc/index.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 9d4110a0..8aadddcd 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -1,7 +1,7 @@ BazingaGeocoderBundle ===================== -Integration of the [**Geocoder**](http://github.com/willdurand/Geocoder) library +Integration of the [**Geocoder**](http://github.com/geocoder-php/Geocoder) library into Symfony2. @@ -196,7 +196,7 @@ check number of queries executed by each provider, total execution time and geocoding results. ![Example -Toolbar](https://raw.github.com/willdurand/BazingaGeocoderBundle/master/Resources/doc/toolbar.png) +Toolbar](https://raw.github.com/geocoder-php/BazingaGeocoderBundle/master/Resources/doc/toolbar.png) Reference Configuration From d930e8d4d3c75b9c30d2b56dfc0e31f6ad95c3c7 Mon Sep 17 00:00:00 2001 From: William DURAND Date: Sat, 14 Dec 2013 22:19:51 +0100 Subject: [PATCH 010/235] [doc] fix code snippets --- Resources/doc/index.md | 1 - 1 file changed, 1 deletion(-) diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 8aadddcd..f987b24c 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -172,7 +172,6 @@ __Configuration example:__ ```yaml # app/config/config*.yml - services: acme_cache_adapter: class: "Doctrine\\Common\\Cache\\ApcCache" From ed12b9c1b1d2bd164e9c0dad63d83a64b9409cd0 Mon Sep 17 00:00:00 2001 From: Markus Bachmann Date: Tue, 27 Aug 2013 21:46:53 +0200 Subject: [PATCH 011/235] Add Doctrine mapping support --- .travis.yml | 8 +- Doctrine/ORM/GeocoderListener.php | 78 +++++++++++++ Mapping/Annotations/Address.php | 13 +++ Mapping/Annotations/Geocodeable.php | 12 ++ Mapping/Annotations/Latitude.php | 12 ++ Mapping/Annotations/Longitude.php | 12 ++ Mapping/ClassMetadata.php | 24 ++++ Mapping/Driver/AnnotationDriver.php | 57 +++++++++ Mapping/Driver/DriverInterface.php | 13 +++ Mapping/Exception/MappingException.php | 10 ++ Resources/doc/index.md | 5 +- Tests/Doctrine/ORM/GeocoderListenerTest.php | 108 ++++++++++++++++++ Tests/Mapping/Driver/AnnotationDriverTest.php | 81 +++++++++++++ Tests/bootstrap.php | 4 +- composer.json | 3 +- 15 files changed, 434 insertions(+), 6 deletions(-) create mode 100644 Doctrine/ORM/GeocoderListener.php create mode 100644 Mapping/Annotations/Address.php create mode 100644 Mapping/Annotations/Geocodeable.php create mode 100644 Mapping/Annotations/Latitude.php create mode 100644 Mapping/Annotations/Longitude.php create mode 100644 Mapping/ClassMetadata.php create mode 100644 Mapping/Driver/AnnotationDriver.php create mode 100644 Mapping/Driver/DriverInterface.php create mode 100644 Mapping/Exception/MappingException.php create mode 100644 Tests/Doctrine/ORM/GeocoderListenerTest.php create mode 100644 Tests/Mapping/Driver/AnnotationDriverTest.php diff --git a/.travis.yml b/.travis.yml index 0dc45af3..50fe9b9a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,6 +10,7 @@ env: - SYMFONY_VERSION=2.1.* - SYMFONY_VERSION=2.2.* - SYMFONY_VERSION=2.3.* + - SYMFONY_VERSION=2.4.* - SYMFONY_VERSION=dev-master matrix: @@ -18,8 +19,9 @@ matrix: before_script: - - curl -s http://getcomposer.org/installer | php - - php composer.phar require symfony/framework-bundle:${SYMFONY_VERSION} --no-update - - php composer.phar update + - composer require symfony/framework-bundle:${SYMFONY_VERSION} --no-update + # This command must be run with `--prefer-source`, otherwise the `Doctrine\Tests\OrmTestCase` class + # won't be found. + - composer update --prefer-source script: phpunit --coverage-text diff --git a/Doctrine/ORM/GeocoderListener.php b/Doctrine/ORM/GeocoderListener.php new file mode 100644 index 00000000..57ddd304 --- /dev/null +++ b/Doctrine/ORM/GeocoderListener.php @@ -0,0 +1,78 @@ + + */ +class GeocoderListener implements EventSubscriber +{ + private $driver; + + private $geocoder; + + public function __construct(Geocoder $geocoder, DriverInterface $driver) + { + $this->driver = $driver; + $this->geocoder = $geocoder; + } + + /** + * {@inheritDoc} + */ + public function getSubscribedEvents() + { + return array( + Events::onFlush + ); + } + + public function onFlush(OnFlushEventArgs $args) + { + $em = $args->getEntityManager(); + $uow = $em->getUnitOfWork(); + + foreach ($uow->getScheduledEntityInsertions() as $entity) { + if (!$this->driver->isGeocodeable($entity)) { + continue; + } + + $this->geocodeEntity($entity); + + $uow->recomputeSingleEntityChangeSet( + $em->getClassMetadata(get_class($entity)), + $entity + ); + } + + foreach ($uow->getScheduledEntityUpdates() as $entity) { + if (!$this->driver->isGeocodeable($entity)) { + continue; + } + + $this->geocodeEntity($entity); + + $uow->recomputeSingleEntityChangeSet( + $em->getClassMetadata(get_class($entity)), + $entity + ); + } + } + + private function geocodeEntity($entity) + { + $metadata = $this->driver->loadMetadataFromObject($entity); + $address = $metadata->addressProperty->getValue($entity); + $result = $this->geocoder->geocode($address); + + $metadata->latitudeProperty->setValue($entity, $result['latitude']); + $metadata->longitudeProperty->setValue($entity, $result['longitude']); + } +} diff --git a/Mapping/Annotations/Address.php b/Mapping/Annotations/Address.php new file mode 100644 index 00000000..c2b36cf4 --- /dev/null +++ b/Mapping/Annotations/Address.php @@ -0,0 +1,13 @@ + + * + * @Annotation + */ +class Address +{ + +} diff --git a/Mapping/Annotations/Geocodeable.php b/Mapping/Annotations/Geocodeable.php new file mode 100644 index 00000000..a616d089 --- /dev/null +++ b/Mapping/Annotations/Geocodeable.php @@ -0,0 +1,12 @@ + + * + * @Annotation + */ +class Geocodeable +{ +} diff --git a/Mapping/Annotations/Latitude.php b/Mapping/Annotations/Latitude.php new file mode 100644 index 00000000..d8b6a200 --- /dev/null +++ b/Mapping/Annotations/Latitude.php @@ -0,0 +1,12 @@ + + * + * @Annotation + */ +class Latitude +{ +} diff --git a/Mapping/Annotations/Longitude.php b/Mapping/Annotations/Longitude.php new file mode 100644 index 00000000..3c8bf106 --- /dev/null +++ b/Mapping/Annotations/Longitude.php @@ -0,0 +1,12 @@ + + * + * @Annotation + */ +class Longitude +{ +} diff --git a/Mapping/ClassMetadata.php b/Mapping/ClassMetadata.php new file mode 100644 index 00000000..915df02f --- /dev/null +++ b/Mapping/ClassMetadata.php @@ -0,0 +1,24 @@ + + */ +class ClassMetadata +{ + /** + * @var \ReflectionProperty + */ + public $addressProperty; + + /** + * @var \ReflectionProperty + */ + public $latitudeProperty; + + /** + * @var \ReflectionProperty + */ + public $longitudeProperty; +} diff --git a/Mapping/Driver/AnnotationDriver.php b/Mapping/Driver/AnnotationDriver.php new file mode 100644 index 00000000..ff5422c3 --- /dev/null +++ b/Mapping/Driver/AnnotationDriver.php @@ -0,0 +1,57 @@ + + */ +class AnnotationDriver implements DriverInterface +{ + private $reader; + + public function __construct(Reader $reader) + { + $this->reader = $reader; + } + + public function isGeocodeable($object) + { + $reflection = new \ReflectionObject($object); + + return !!$this->reader->getClassAnnotation($reflection, 'Bazinga\\Bundle\\GeocoderBundle\\Mapping\\Annotations\\Geocodeable'); + } + + public function loadMetadataFromObject($object) + { + $reflection = new \ReflectionObject($object); + if (!$annotation = $this->reader->getClassAnnotation($reflection, 'Bazinga\\Bundle\\GeocoderBundle\\Mapping\\Annotations\\Geocodeable')) { + throw new Exception\MappingException(sprintf( + 'The class %s is not geocodeable', get_class($object) + )); + } + + $metadata = new ClassMetadata(); + + foreach ($reflection->getProperties() as $property) { + foreach ($this->reader->getPropertyAnnotations($property) as $annotation) { + if ($annotation instanceof Annotations\Latitude) { + $property->setAccessible(true); + $metadata->latitudeProperty = $property; + } elseif ($annotation instanceof Annotations\Longitude) { + $property->setAccessible(true); + $metadata->longitudeProperty = $property; + } elseif ($annotation instanceof Annotations\Address) { + $property->setAccessible(true); + $metadata->addressProperty = $property; + } + } + } + + return $metadata; + } +} diff --git a/Mapping/Driver/DriverInterface.php b/Mapping/Driver/DriverInterface.php new file mode 100644 index 00000000..fb5e60fc --- /dev/null +++ b/Mapping/Driver/DriverInterface.php @@ -0,0 +1,13 @@ + + */ + +namespace Bazinga\Bundle\GeocoderBundle\Mapping\Driver; + +interface DriverInterface +{ + public function isGeocodeable($object); + + public function loadMetadataFromObject($object); +} diff --git a/Mapping/Exception/MappingException.php b/Mapping/Exception/MappingException.php new file mode 100644 index 00000000..7923af71 --- /dev/null +++ b/Mapping/Exception/MappingException.php @@ -0,0 +1,10 @@ + + */ +class MappingException extends \Exception +{ +} diff --git a/Resources/doc/index.md b/Resources/doc/index.md index f987b24c..1258f079 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -272,7 +272,10 @@ Testing Setup the test suite using [Composer](http://getcomposer.org/): - $ composer install --dev + $ composer install --dev --prefer-source + +**Important:** this command must be run with `--prefer-source`, otherwise the +`Doctrine\Tests\OrmTestCase` class won't be found. Run it using PHPUnit: diff --git a/Tests/Doctrine/ORM/GeocoderListenerTest.php b/Tests/Doctrine/ORM/GeocoderListenerTest.php new file mode 100644 index 00000000..2bbe1d24 --- /dev/null +++ b/Tests/Doctrine/ORM/GeocoderListenerTest.php @@ -0,0 +1,108 @@ + + */ +class GeocoderListenerTest extends OrmTestCase +{ + /** + * @var EntityManager + */ + private $em; + + protected function setUp() + { + AnnotationRegistry::registerLoader('class_exists'); + + $conn = DriverManager::getConnection(array( + 'driver' => 'pdo_sqlite', + 'memory' => true, + )); + + $this->em = $this->_getTestEntityManager($conn); + + $reader = new SimpleAnnotationReader(); + $reader->addNamespace('Bazinga\Bundle\GeocoderBundle\Mapping\Annotations'); + $reader->addNamespace('Doctrine\ORM\Mapping'); + + $driver = new AnnotationDriver($reader); + + $geocoder = new Geocoder(); + $geocoder->registerProvider(new GoogleMapsProvider(new CurlHttpAdapter())); + + $this->listener = new GeocoderListener($geocoder, $driver); + + $this->em->getEventManager()->addEventSubscriber($this->listener); + + $sm = new SchemaTool($this->em); + $sm->createSchema(array( + $this->em->getClassMetadata('Bazinga\Bundle\GeocoderBundle\Tests\Doctrine\ORM\Dummy') + )); + } + + public function testPersist() + { + $dummy = new Dummy(); + $dummy->address = 'Berlin, Germany'; + + $this->em->persist($dummy); + $this->em->flush(); + + $this->assertNotNull($dummy->latitude); + $this->assertNotNull($dummy->longitude); + + $clone = clone $dummy; + $dummy->address = 'Paris, France'; + + $this->em->persist($dummy); + $this->em->flush(); + + $this->assertNotEquals($clone->latitude, $dummy->latitude); + $this->assertNotEquals($clone->longitude, $dummy->longitude); + } +} + +/** + * @Geocodeable + * @Entity + */ +class Dummy +{ + /** + * @Id @GeneratedValue + * @Column(type="integer") + */ + public $id; + + /** + * @Latitude + * @Column + */ + public $latitude; + + /** + * @Longitude + * @Column + */ + public $longitude; + + /** + * @Address + * @Column + */ + public $address; +} diff --git a/Tests/Mapping/Driver/AnnotationDriverTest.php b/Tests/Mapping/Driver/AnnotationDriverTest.php new file mode 100644 index 00000000..5178b8a5 --- /dev/null +++ b/Tests/Mapping/Driver/AnnotationDriverTest.php @@ -0,0 +1,81 @@ + + */ +class AnnotationDriverTest extends \PHPUnit_Framework_TestCase +{ + /** + * @var AnnotationDriver + */ + private $driver; + + /** + * @var Reader + */ + private $reader; + + protected function setUp() + { + AnnotationRegistry::registerLoader('class_exists'); + + $this->reader = new SimpleAnnotationReader; + $this->reader->addNamespace('Bazinga\Bundle\GeocoderBundle\Mapping\Annotations'); + + $this->driver = new AnnotationDriver($this->reader); + } + + public function testLoadMetadata() + { + $obj = new Dummy(); + $metadata = $this->driver->loadMetadataFromObject($obj); + + $this->assertInstanceOf('ReflectionProperty', $metadata->addressProperty); + $this->assertInstanceOf('ReflectionProperty', $metadata->latitudeProperty); + $this->assertInstanceOf('ReflectionProperty', $metadata->longitudeProperty); + } + + /** + * @expectedException Bazinga\Bundle\GeocoderBundle\Mapping\Exception\MappingException + */ + public function testLoadMetadataFromWrongObject() + { + $this->driver->loadMetadataFromObject(new Dummy2); + } + + public function testIsGeocodable() + { + $this->assertTrue($this->driver->isGeocodeable(new Dummy())); + } +} + +/** + * @Geocodeable + */ +class Dummy +{ + /** + * @Latitude + */ + public $latitude; + + /** + * @Longitude + */ + public $longitude; + + /** + * @Address + */ + public $address; +} + +class Dummy2 +{} diff --git a/Tests/bootstrap.php b/Tests/bootstrap.php index 8493ff33..48b06b1c 100644 --- a/Tests/bootstrap.php +++ b/Tests/bootstrap.php @@ -1,6 +1,6 @@ add('Doctrine\Tests', __DIR__.'/../vendor/doctrine/orm/tests'); diff --git a/composer.json b/composer.json index c3e0d559..d4105a93 100644 --- a/composer.json +++ b/composer.json @@ -18,7 +18,8 @@ "require-dev": { "symfony/yaml": "~2.0", "maxromanovsky/php-maxmind-geoip": "~1.12", - "doctrine/cache": "~1.3" + "doctrine/cache": "~1.3", + "doctrine/orm": "~2.3" }, "autoload": { "psr-0": { "Bazinga\\Bundle\\GeocoderBundle": "" } From 6580f96b9005abcecc1c97976f7ae4c4a2215f1a Mon Sep 17 00:00:00 2001 From: William DURAND Date: Tue, 31 Dec 2013 17:38:02 +0100 Subject: [PATCH 012/235] Require Symfony 2.1 and above --- .travis.yml | 1 - composer.json | 6 +++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 50fe9b9a..1519fa81 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,7 +6,6 @@ php: - 5.5 env: - - SYMFONY_VERSION=2.0.7 - SYMFONY_VERSION=2.1.* - SYMFONY_VERSION=2.2.* - SYMFONY_VERSION=2.3.* diff --git a/composer.json b/composer.json index d4105a93..c6556dd5 100644 --- a/composer.json +++ b/composer.json @@ -11,12 +11,12 @@ } ], "require": { - "symfony/framework-bundle": "~2.0", + "symfony/framework-bundle": "~2.1", "willdurand/geocoder": "~2.3", - "symfony/console": "~2.0" + "symfony/console": "~2.1" }, "require-dev": { - "symfony/yaml": "~2.0", + "symfony/yaml": "~2.1", "maxromanovsky/php-maxmind-geoip": "~1.12", "doctrine/cache": "~1.3", "doctrine/orm": "~2.3" From 9dbd39946c270ee0603084efff7ff2c66aa699ce Mon Sep 17 00:00:00 2001 From: William Durand Date: Thu, 16 Jan 2014 11:58:33 +0100 Subject: [PATCH 013/235] Add note about how to register providers --- Resources/doc/index.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 1258f079..4465160a 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -117,6 +117,20 @@ bazinga_geocoder: priority: 128 ``` +### Registering Your Own Providers + +If you want to use your own provider in your application, create a service, +and tag it as `bazinga_geocoder.provider`: + +```xml + + + +``` + +The bundle will automatically register it, into the `bazinga_geocoder.geocoder` +service. + ### Dumpers If you need to dump your geocoded data to a specific format, you can use the From 11c1e1cd3704e0dfcb96ef7eedef6c0b293d374a Mon Sep 17 00:00:00 2001 From: William Durand Date: Thu, 16 Jan 2014 12:01:47 +0100 Subject: [PATCH 014/235] Typo --- Resources/doc/index.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 4465160a..385e0712 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -128,8 +128,8 @@ and tag it as `bazinga_geocoder.provider`: ``` -The bundle will automatically register it, into the `bazinga_geocoder.geocoder` -service. +The bundle will automatically register your provider into the +`bazinga_geocoder.geocoder` service. ### Dumpers From 425e3a72bbd744a94b108d57b8b3d33ff4752eb9 Mon Sep 17 00:00:00 2001 From: William DURAND Date: Thu, 16 Jan 2014 15:11:49 +0100 Subject: [PATCH 015/235] Fix inconsistencies PHPDoc Tag names Documentation CS --- .../BazingaGeocoderExtension.php | 49 ++++++++++++++----- .../Compiler/AddDumperPass.php | 2 +- .../Compiler/AddProvidersPass.php | 13 +++-- DependencyInjection/Compiler/LoggablePass.php | 5 +- Doctrine/ORM/GeocoderListener.php | 6 +-- Geocoder/LoggableGeocoder.php | 8 +-- Logger/GeocoderLogger.php | 18 +++---- Resources/config/services.xml | 10 ++-- Resources/doc/index.md | 8 ++- .../BazingaGeocoderExtensionTest.php | 1 + .../Compiler/AddDumperPassTest.php | 2 +- 11 files changed, 70 insertions(+), 52 deletions(-) diff --git a/DependencyInjection/BazingaGeocoderExtension.php b/DependencyInjection/BazingaGeocoderExtension.php index 1171f5f5..b1c488db 100644 --- a/DependencyInjection/BazingaGeocoderExtension.php +++ b/DependencyInjection/BazingaGeocoderExtension.php @@ -72,13 +72,17 @@ public function load(array $configs, ContainerBuilder $container) if (isset($config['providers']['ip_info_db'])) { $ipInfoDbParams = $config['providers']['ip_info_db']; - $this->addProvider('ip_info_db', array($ipInfoDbParams['api_key'])); + $this->addProvider('ip_info_db', array( + $ipInfoDbParams['api_key'] + )); } if (isset($config['providers']['cloudmade'])) { $cloudMadeParams = $config['providers']['cloudmade']; - $this->addProvider('cloudmade', array($cloudMadeParams['api_key'])); + $this->addProvider('cloudmade', array( + $cloudMadeParams['api_key'] + )); } if (isset($config['providers']['google_maps'])) { @@ -106,7 +110,9 @@ public function load(array $configs, ContainerBuilder $container) if (isset($config['providers']['openstreetmap'])) { $openstreetMapsParams = $config['providers']['openstreetmap']; - $this->addProvider('openstreetmap', array($openstreetMapsParams['locale'])); + $this->addProvider('openstreetmap', array( + $openstreetMapsParams['locale'] + )); } if (isset($config['providers']['geoip'])) { @@ -114,9 +120,11 @@ public function load(array $configs, ContainerBuilder $container) } if (isset($config['providers']['mapquest'])) { - $mapquestParams = $config['providers']['mapquest']; + $mapQuestParams = $config['providers']['mapquest']; - $this->addProvider('mapquest', array($mapquestParams['api_key'])); + $this->addProvider('mapquest', array( + $mapQuestParams['api_key'] + )); } if (isset($config['providers']['oiorest'])) { @@ -134,7 +142,9 @@ public function load(array $configs, ContainerBuilder $container) if (isset($config['providers']['ign_openls'])) { $ignOpenlsParams = $config['providers']['ign_openls']; - $this->addProvider('ign_openls', array($ignOpenlsParams['api_key'])); + $this->addProvider('ign_openls', array( + $ignOpenlsParams['api_key'] + )); } if (isset($config['providers']['data_science_toolkit'])) { @@ -144,11 +154,18 @@ public function load(array $configs, ContainerBuilder $container) if (isset($config['providers']['yandex'])) { $yandexParams = $config['providers']['yandex']; - $this->addProvider('yandex', array($yandexParams['locale'], $yandexParams['toponym'])); + $this->addProvider('yandex', array( + $yandexParams['locale'], + $yandexParams['toponym'] + )); } if (isset($config['providers']['geo_ips'])) { - $this->addProvider('geo_ips', array($config['providers']['geo_ips']['api_key'])); + $geoIpsParams = $config['providers']['geo_ips']; + + $this->addProvider('geo_ips', array( + $geoIpsParams['api_key'] + )); } if (isset($config['providers']['geo_plugin'])) { @@ -158,15 +175,19 @@ public function load(array $configs, ContainerBuilder $container) if (isset($config['providers']['maxmind'])) { $maxmindParams = $config['providers']['maxmind']; - $this->addProvider('maxmind', array($maxmindParams['api_key'])); + $this->addProvider('maxmind', array( + $maxmindParams['api_key'] + )); } if (isset($config['providers']['maxmind_binary'])) { + $maxmindBinaryParams = $config['providers']['maxmind_binary']; + $provider = new Definition( '%bazinga_geocoder.geocoder.provider.maxmind_binary.class%', array( - $config['providers']['maxmind_binary']['binary_file'], - $config['providers']['maxmind_binary']['open_flag'], + $maxmindBinaryParams['binary_file'], + $maxmindBinaryParams['open_flag'], ) ); @@ -174,7 +195,7 @@ public function load(array $configs, ContainerBuilder $container) ->setPublic(false) ->addTag('bazinga_geocoder.provider'); - $this->container->setDefinition('bazinga_geocoder.provider.maxmind_binary', $provider); + $container->setDefinition('bazinga_geocoder.provider.maxmind_binary', $provider); } if (isset($config['providers']['cache'])) { @@ -212,7 +233,9 @@ public function load(array $configs, ContainerBuilder $container) if (isset($config['providers']['chain']['providers'])) { foreach ($config['providers']['chain']['providers'] as $name) { if ($this->container->hasDefinition('bazinga_geocoder.provider.'.$name)) { - $chainProvider->addMethodCall('addProvider', array($this->container->getDefinition('bazinga_geocoder.provider.'.$name))); + $chainProvider->addMethodCall('addProvider', array( + $this->container->getDefinition('bazinga_geocoder.provider.'.$name) + )); } } } diff --git a/DependencyInjection/Compiler/AddDumperPass.php b/DependencyInjection/Compiler/AddDumperPass.php index 0f7afcb1..6e7b3f1b 100644 --- a/DependencyInjection/Compiler/AddDumperPass.php +++ b/DependencyInjection/Compiler/AddDumperPass.php @@ -30,7 +30,7 @@ public function process(ContainerBuilder $container) $manager = $container->findDefinition('bazinga_geocoder.dumper_manager'); $dumpers = array(); - foreach ($container->findTaggedServiceIds('geocoder.dumper') as $id => $attributes) { + foreach ($container->findTaggedServiceIds('bazinga_geocoder.dumper') as $id => $attributes) { if (!isset($attributes[0]['alias'])) { throw new \RuntimeException(sprintf('No alias for service "%s" provided. Please set a alias!', $id)); } diff --git a/DependencyInjection/Compiler/AddProvidersPass.php b/DependencyInjection/Compiler/AddProvidersPass.php index 3a522617..83597f83 100644 --- a/DependencyInjection/Compiler/AddProvidersPass.php +++ b/DependencyInjection/Compiler/AddProvidersPass.php @@ -25,9 +25,10 @@ class AddProvidersPass implements CompilerPassInterface protected $container; /** - * Get all providers based on their tag ('geocoder.provider') and register them. + * Get all providers based on their tag (`bazinga_geocoder.provider`) and + * register them. * - * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container The container. + * @param ContainerBuilder $container */ public function process(ContainerBuilder $container) { @@ -35,16 +36,14 @@ public function process(ContainerBuilder $container) return; } - $this->container = $container; - $array = array(); - foreach ($this->container->findTaggedServiceIds('bazinga_geocoder.provider') as $providerId => $attributes) { + foreach ($container->findTaggedServiceIds('bazinga_geocoder.provider') as $providerId => $attributes) { $array[] = new Reference($providerId); } - $this->container + $container ->getDefinition('bazinga_geocoder.geocoder') ->addMethodCall('registerProviders', array($array)) - ; + ; } } diff --git a/DependencyInjection/Compiler/LoggablePass.php b/DependencyInjection/Compiler/LoggablePass.php index 00e9efd4..01a57c78 100644 --- a/DependencyInjection/Compiler/LoggablePass.php +++ b/DependencyInjection/Compiler/LoggablePass.php @@ -29,10 +29,7 @@ public function process(ContainerBuilder $container) } $definition = $container->getDefinition('bazinga_geocoder.geocoder'); - $definition->setClass( - $container->getParameter('bazinga_geocoder.geocoder.loggable_class') - ); + $definition->setClass($container->getParameter('bazinga_geocoder.geocoder.loggable_class')); $definition->addMethodCall('setLogger', array(new Reference('bazinga_geocoder.logger'))); - } } diff --git a/Doctrine/ORM/GeocoderListener.php b/Doctrine/ORM/GeocoderListener.php index 57ddd304..fc2a8f32 100644 --- a/Doctrine/ORM/GeocoderListener.php +++ b/Doctrine/ORM/GeocoderListener.php @@ -20,7 +20,7 @@ class GeocoderListener implements EventSubscriber public function __construct(Geocoder $geocoder, DriverInterface $driver) { - $this->driver = $driver; + $this->driver = $driver; $this->geocoder = $geocoder; } @@ -69,8 +69,8 @@ public function onFlush(OnFlushEventArgs $args) private function geocodeEntity($entity) { $metadata = $this->driver->loadMetadataFromObject($entity); - $address = $metadata->addressProperty->getValue($entity); - $result = $this->geocoder->geocode($address); + $address = $metadata->addressProperty->getValue($entity); + $result = $this->geocoder->geocode($address); $metadata->latitudeProperty->setValue($entity, $result['latitude']); $metadata->longitudeProperty->setValue($entity, $result['longitude']); diff --git a/Geocoder/LoggableGeocoder.php b/Geocoder/LoggableGeocoder.php index 8bf3d84e..250eb3d0 100644 --- a/Geocoder/LoggableGeocoder.php +++ b/Geocoder/LoggableGeocoder.php @@ -39,8 +39,8 @@ public function geocode($value) } $startTime = microtime(true); - $result = parent::geocode($value); - $duration = (microtime(true) - $startTime) * 1000; + $result = parent::geocode($value); + $duration = (microtime(true) - $startTime) * 1000; $this->logger->logRequest( sprintf("[Geocoding] %s", $value), @@ -62,8 +62,8 @@ public function reverse($latitude, $longitude) } $startTime = microtime(true); - $result = parent::reverse($latitude, $longitude); - $duration = (microtime(true) - $startTime) * 1000; + $result = parent::reverse($latitude, $longitude); + $duration = (microtime(true) - $startTime) * 1000; $value = sprintf("[Reverse geocoding] latitude: %s, longitude: %s", $latitude, $longitude); diff --git a/Logger/GeocoderLogger.php b/Logger/GeocoderLogger.php index 44f46955..c179ac7c 100644 --- a/Logger/GeocoderLogger.php +++ b/Logger/GeocoderLogger.php @@ -13,13 +13,12 @@ use Symfony\Component\HttpKernel\Log\LoggerInterface; /** - * GeocoderLogger * @author Michal Dabrowski */ class GeocoderLogger { protected $logger; - protected $nbRequests = 0; + protected $requests = array(); /** @@ -40,18 +39,19 @@ public function __construct(LoggerInterface $logger = null) */ public function logRequest($value, $duration, $providerClass, $result) { - ++$this->nbRequests; - if (null !== $this->logger) { $this->requests[] = array( - 'value' => $value, - 'duration' => $duration, + 'value' => $value, + 'duration' => $duration, 'providerClass' => $providerClass, - 'result' => $result + 'result' => $result ); - $message = sprintf("%s %0.2f ms (%s)", $value, $duration, $providerClass); - $this->logger->info($message); + $this->logger->info(sprintf("%s %0.2f ms (%s)", + $value, + $duration, + $providerClass + )); } } diff --git a/Resources/config/services.xml b/Resources/config/services.xml index c2f28512..2535d43d 100644 --- a/Resources/config/services.xml +++ b/Resources/config/services.xml @@ -59,19 +59,19 @@ - + - + - + - + - + diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 385e0712..d5c990a9 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -165,14 +165,14 @@ public function geocodeAction(Request $request) } ``` -To register a new dumper, you must tag it with _geocoder.dumper_. -Geocoder detect and register it automatically. +To register a new dumper, you must tag it with `bazinga_geocoder.dumper`. +The bundles will automatically register it. A little example: ```xml - + ``` @@ -182,8 +182,6 @@ Sometimes you have to cache the results from a provider. For this case the bundl a cache provider. The cache provider wraps another provider and delegate all calls to this provider and cache the return value. -__Configuration example:__ - ```yaml # app/config/config*.yml services: diff --git a/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php b/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php index 06be8ff4..c1981fc2 100644 --- a/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php +++ b/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php @@ -41,6 +41,7 @@ public function testLoad() ); $dumperManager = $container->get('bazinga_geocoder.dumper_manager'); + foreach (array('geojson', 'gpx', 'kmp', 'wkb', 'wkt') as $name) { $this->assertTrue($dumperManager->has($name)); } diff --git a/Tests/DependencyInjection/Compiler/AddDumperPassTest.php b/Tests/DependencyInjection/Compiler/AddDumperPassTest.php index 52a957be..5d62f1f9 100644 --- a/Tests/DependencyInjection/Compiler/AddDumperPassTest.php +++ b/Tests/DependencyInjection/Compiler/AddDumperPassTest.php @@ -17,7 +17,7 @@ public function testProcess() $builder->setDefinition('bazinga_geocoder.dumper_manager', new Definition('Bazinga\Bundle\GeocoderBundle\DumperManager')); $dumper = new Definition('Geocoder\Dumper\GeoJsonDumper'); - $dumper->addTag('geocoder.dumper', array('alias' => 'geojson')); + $dumper->addTag('bazinga_geocoder.dumper', array('alias' => 'geojson')); $builder->setDefinition('bazinga_geocoder.dumper.geojson', $dumper); From 3afb6382cc53ef7deb86b8a1a6d399e70776d2d6 Mon Sep 17 00:00:00 2001 From: William DURAND Date: Thu, 16 Jan 2014 15:14:41 +0100 Subject: [PATCH 016/235] Prepare 3.0.0 release --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index c6556dd5..56483381 100644 --- a/composer.json +++ b/composer.json @@ -27,7 +27,7 @@ "target-dir": "Bazinga/Bundle/GeocoderBundle", "extra": { "branch-alias": { - "dev-master": "2.0-dev" + "dev-master": "3.0-dev" } } } From 2c8413835600ae180b08648a7e2418c88daf7a97 Mon Sep 17 00:00:00 2001 From: William DURAND Date: Thu, 16 Jan 2014 15:24:29 +0100 Subject: [PATCH 017/235] add badges --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 1ef03295..6c59c95b 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,10 @@ BazingaGeocoderBundle [![Build Status](https://secure.travis-ci.org/geocoder-php/BazingaGeocoderBundle.png)](http://travis-ci.org/geocoder-php/BazingaGeocoderBundle) +[![Total +Downloads](https://poser.pugx.org/willdurand/geocoder-bundle/downloads.png)](https://packagist.org/packages/willdurand/geocoder-bundle) +[![Latest Stable +Version](https://poser.pugx.org/willdurand/geocoder-bundle/v/stable.png)](https://packagist.org/packages/willdurand/geocoder-bundle) Integration of the [**Geocoder**](http://github.com/geocoder-php/Geocoder) library into Symfony2. From e9f00e7808b4442a7ff15dde753e6ddbedda5fbc Mon Sep 17 00:00:00 2001 From: William DURAND Date: Thu, 16 Jan 2014 15:25:22 +0100 Subject: [PATCH 018/235] fix doc --- Resources/doc/index.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Resources/doc/index.md b/Resources/doc/index.md index d5c990a9..bf8af2aa 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -20,6 +20,10 @@ to your `composer.json` file: } ``` +**Protip:** you should browse the +[`willdurand/geocoder-bundle`](https://packagist.org/packages/willdurand/geocoder-bundle) +page to choose a stable version to use, avoid the `@stable` meta constraint. + Register the bundle in `app/AppKernel.php`: ```php From 753c6b175efdc96ebff36b9bb6ec6e110f7153ed Mon Sep 17 00:00:00 2001 From: William Durand Date: Fri, 17 Jan 2014 09:41:34 +0100 Subject: [PATCH 019/235] Update index.md --- Resources/doc/index.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Resources/doc/index.md b/Resources/doc/index.md index bf8af2aa..f9c60b6a 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -135,6 +135,10 @@ and tag it as `bazinga_geocoder.provider`: The bundle will automatically register your provider into the `bazinga_geocoder.geocoder` service. +**Note:** the `bazinga_geocoder.geocoder.adapter` service represents the configured +Geocoder's adapter. If your provider needs an HTTP adapter, you should inject this +service into the service you have just created. + ### Dumpers If you need to dump your geocoded data to a specific format, you can use the From 89ae5852bbf75fce95a91430eb0fc9b73a361335 Mon Sep 17 00:00:00 2001 From: Antoine Corcy Date: Sat, 15 Mar 2014 14:03:05 +0100 Subject: [PATCH 020/235] add --prefer-source flag --- Tests/bootstrap.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/bootstrap.php b/Tests/bootstrap.php index 48b06b1c..d21ffec8 100644 --- a/Tests/bootstrap.php +++ b/Tests/bootstrap.php @@ -3,7 +3,7 @@ if (!$loader = @require_once __DIR__ . '/../vendor/autoload.php') { die("You must set up the project dependencies, run the following commands: wget http://getcomposer.org/composer.phar -php composer.phar install --dev +php composer.phar install --dev --prefer-source "); } From 500864400dde718f1cf1bbb4bc7882de8db577de Mon Sep 17 00:00:00 2001 From: Antoine Corcy Date: Sat, 15 Mar 2014 14:14:17 +0100 Subject: [PATCH 021/235] handle multiple results --- Geocoder/LoggableGeocoder.php | 17 +++++--------- Logger/GeocoderLogger.php | 44 +++++++++++++++++++++-------------- 2 files changed, 32 insertions(+), 29 deletions(-) diff --git a/Geocoder/LoggableGeocoder.php b/Geocoder/LoggableGeocoder.php index 250eb3d0..c8ff0d1d 100644 --- a/Geocoder/LoggableGeocoder.php +++ b/Geocoder/LoggableGeocoder.php @@ -39,17 +39,17 @@ public function geocode($value) } $startTime = microtime(true); - $result = parent::geocode($value); + $results = parent::geocode($value); $duration = (microtime(true) - $startTime) * 1000; $this->logger->logRequest( sprintf("[Geocoding] %s", $value), $duration, $this->getProviderClass(), - json_encode($result->toArray()) + $results ); - return $result; + return $results; } /** @@ -62,19 +62,14 @@ public function reverse($latitude, $longitude) } $startTime = microtime(true); - $result = parent::reverse($latitude, $longitude); + $results = parent::reverse($latitude, $longitude); $duration = (microtime(true) - $startTime) * 1000; $value = sprintf("[Reverse geocoding] latitude: %s, longitude: %s", $latitude, $longitude); - $this->logger->logRequest( - $value, - $duration, - $this->getProviderClass(), - json_encode($result->toArray()) - ); + $this->logger->logRequest($value, $duration, $this->getProviderClass(), $results); - return $result; + return $results; } protected function getProviderClass() diff --git a/Logger/GeocoderLogger.php b/Logger/GeocoderLogger.php index c179ac7c..1072e449 100644 --- a/Logger/GeocoderLogger.php +++ b/Logger/GeocoderLogger.php @@ -17,12 +17,17 @@ */ class GeocoderLogger { + /** + * @var LoggerInterface + */ protected $logger; + /** + * @var array + */ protected $requests = array(); /** - * * @param LoggerInterface $logger */ public function __construct(LoggerInterface $logger = null) @@ -31,28 +36,31 @@ public function __construct(LoggerInterface $logger = null) } /** - * - * @param string $value value to geocode - * @param float $duration - * @param string $providerClass Geocoder provider class - * @param mixed $result + * @param string $value value to geocode + * @param float $duration geocoding duration + * @param string $providerClass Geocoder provider class name + * @param \SplObjectStorage|Geocoded $results */ - public function logRequest($value, $duration, $providerClass, $result) + public function logRequest($value, $duration, $providerClass, $results) { if (null !== $this->logger) { - $this->requests[] = array( - 'value' => $value, - 'duration' => $duration, - 'providerClass' => $providerClass, - 'result' => $result - ); + $this->logger->info(sprintf("%s %0.2f ms (%s)", $value, $duration, $providerClass)); + } - $this->logger->info(sprintf("%s %0.2f ms (%s)", - $value, - $duration, - $providerClass - )); + if ($results instanceof \SplObjectStorage) { + foreach ($results as $result) { + $data[] = $result->toArray(); + } + } else { + $data = $results->toArray(); } + + $this->requests[] = array( + 'value' => $value, + 'duration' => $duration, + 'providerClass' => $providerClass, + 'result' => json_encode($data), + ); } /** From 53a1aa7e6d35aa574e56d1cc089a0319ed9bc329 Mon Sep 17 00:00:00 2001 From: Antoine Corcy Date: Sat, 15 Mar 2014 14:14:34 +0100 Subject: [PATCH 022/235] add geocoder logger test --- Tests/Logger/GeocoderLoggerTest.php | 124 ++++++++++++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 Tests/Logger/GeocoderLoggerTest.php diff --git a/Tests/Logger/GeocoderLoggerTest.php b/Tests/Logger/GeocoderLoggerTest.php new file mode 100644 index 00000000..1c459c91 --- /dev/null +++ b/Tests/Logger/GeocoderLoggerTest.php @@ -0,0 +1,124 @@ + + */ +class GeocoderLoggerTest extends \PHPUnit_Framework_TestCase +{ + protected $geocoderLogger; + protected $result; + protected $results; + + public function setUp() + { + $logger = $this->getMock('Symfony\\Component\\HttpKernel\\Log\\LoggerInterface'); + $logger + ->expects($this->any()) + ->method('info') + ->will($this->returnValue(null)) + ; + + $this->geocoderLogger = new GeocoderLogger($logger); + + $this->result = new Geocoded; + $this->result->fromArray(array( + 'latitude' => 1, + 'longitude' => 2, + )); + + $this->results = new \SplObjectStorage; + $this->results->attach($this->result); + + $otherResult = new Geocoded; + $otherResult->fromArray(array( + 'latitude' => 3, + 'longitude' => 4, + )); + + $this->results->attach($otherResult); + } + + public function testLogSingleResult() + { + $this->geocoderLogger->logRequest('copenhagen', 0.123, 'FooProvider', $this->result); + + $this->assertTrue(is_array($requests = $this->geocoderLogger->getRequests())); + $this->assertCount(1, $requests); + $this->assertTrue(is_array($request = $requests[0])); + $this->assertSame($request['value'], 'copenhagen'); + $this->assertSame($request['duration'], 0.123); + $this->assertSame($request['providerClass'], 'FooProvider'); + $this->assertSame($request['result'], '{"latitude":1,"longitude":2,"bounds":null,"streetNumber":null,"streetName":null,"zipcode":null,"city":null,"cityDistrict":null,"county":null,"countyCode":null,"region":null,"regionCode":null,"country":null,"countryCode":null,"timezone":null}'); + } + + public function testLog2RequestsWithSingleResult() + { + $this->geocoderLogger->logRequest('copenhagen', 0.123, 'FooProvider', $this->result); + $this->geocoderLogger->logRequest('paris', 0.456, 'BarProvider', $this->result); + + $this->assertTrue(is_array($requests = $this->geocoderLogger->getRequests())); + $this->assertCount(2, $requests); + $this->assertTrue(is_array($request = $requests[0])); + $this->assertSame($request['value'], 'copenhagen'); + $this->assertTrue(is_array($request = $requests[1])); + $this->assertSame($request['value'], 'paris'); + } + + public function testLogMultipleResults() + { + $this->geocoderLogger->logRequest('copenhagen', 0.123, 'FooProvider', $this->results); + + $this->assertTrue(is_array($requests = $this->geocoderLogger->getRequests())); + $this->assertCount(1, $requests); + $this->assertTrue(is_array($request = $requests[0])); + $this->assertSame($request['value'], 'copenhagen'); + $this->assertSame($request['duration'], 0.123); + $this->assertSame($request['providerClass'], 'FooProvider'); + $this->assertSame($request['result'], '[{"latitude":1,"longitude":2,"bounds":null,"streetNumber":null,"streetName":null,"zipcode":null,"city":null,"cityDistrict":null,"county":null,"countyCode":null,"region":null,"regionCode":null,"country":null,"countryCode":null,"timezone":null},{"latitude":3,"longitude":4,"bounds":null,"streetNumber":null,"streetName":null,"zipcode":null,"city":null,"cityDistrict":null,"county":null,"countyCode":null,"region":null,"regionCode":null,"country":null,"countryCode":null,"timezone":null}]'); + $this->assertCount(2, json_decode($request['result'])); + } + + public function testLog2RequetsWithMultipleResults() + { + $this->geocoderLogger->logRequest('copenhagen', 0.123, 'FooProvider', $this->results); + $this->geocoderLogger->logRequest('paris', 0.456, 'BarProvider', $this->results); + + $this->assertTrue(is_array($requests = $this->geocoderLogger->getRequests())); + $this->assertCount(2, $requests); + + $this->assertTrue(is_array($request = $requests[0])); + $this->assertSame($request['value'], 'copenhagen'); + $this->assertCount(2, json_decode($request['result'])); + + $this->assertTrue(is_array($request = $requests[1])); + $this->assertSame($request['value'], 'paris'); + $this->assertCount(2, json_decode($request['result'])); + } + + public function testLogRequestsWithoutLogger() + { + $geocoderLogger = new GeocoderLogger; + $geocoderLogger->logRequest('copenhagen', 0.123, 'FooProvider', $this->result); + + $this->assertTrue(is_array($requests = $geocoderLogger->getRequests())); + $this->assertCount(1, $requests); + $this->assertTrue(is_array($request = $requests[0])); + $this->assertSame($request['value'], 'copenhagen'); + $this->assertSame($request['duration'], 0.123); + $this->assertSame($request['providerClass'], 'FooProvider'); + $this->assertSame($request['result'], '{"latitude":1,"longitude":2,"bounds":null,"streetNumber":null,"streetName":null,"zipcode":null,"city":null,"cityDistrict":null,"county":null,"countyCode":null,"region":null,"regionCode":null,"country":null,"countryCode":null,"timezone":null}'); + } +} From e99340396935715b586faf43fd0d3658df742b2e Mon Sep 17 00:00:00 2001 From: Craig Menning Date: Thu, 8 May 2014 14:27:37 -0500 Subject: [PATCH 023/235] Initialize $data in case there are no results --- Logger/GeocoderLogger.php | 1 + 1 file changed, 1 insertion(+) diff --git a/Logger/GeocoderLogger.php b/Logger/GeocoderLogger.php index 1072e449..f6dbd60b 100644 --- a/Logger/GeocoderLogger.php +++ b/Logger/GeocoderLogger.php @@ -48,6 +48,7 @@ public function logRequest($value, $duration, $providerClass, $results) } if ($results instanceof \SplObjectStorage) { + $data = array(); foreach ($results as $result) { $data[] = $result->toArray(); } From 734d2f997fe3c51676075d7343be11020c4fee8e Mon Sep 17 00:00:00 2001 From: Antoine Corcy Date: Thu, 8 May 2014 22:38:06 +0200 Subject: [PATCH 024/235] initialize in case there are no results --- Logger/GeocoderLogger.php | 2 ++ Tests/Logger/GeocoderLoggerTest.php | 28 ++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/Logger/GeocoderLogger.php b/Logger/GeocoderLogger.php index 1072e449..656c1b4c 100644 --- a/Logger/GeocoderLogger.php +++ b/Logger/GeocoderLogger.php @@ -47,6 +47,8 @@ public function logRequest($value, $duration, $providerClass, $results) $this->logger->info(sprintf("%s %0.2f ms (%s)", $value, $duration, $providerClass)); } + $data = array(); + if ($results instanceof \SplObjectStorage) { foreach ($results as $result) { $data[] = $result->toArray(); diff --git a/Tests/Logger/GeocoderLoggerTest.php b/Tests/Logger/GeocoderLoggerTest.php index 1c459c91..82715475 100644 --- a/Tests/Logger/GeocoderLoggerTest.php +++ b/Tests/Logger/GeocoderLoggerTest.php @@ -51,6 +51,34 @@ public function setUp() $this->results->attach($otherResult); } + public function testLogNoResult() + { + $this->geocoderLogger->logRequest('copenhagen', 0.123, 'FooProvider', new Geocoded); + + $requests = $this->geocoderLogger->getRequests(); + + $this->assertTrue(is_array($requests = $this->geocoderLogger->getRequests())); + $this->assertCount(1, $requests); + $this->assertTrue(is_array($request = $requests[0])); + $this->assertSame($request['value'], 'copenhagen'); + $this->assertSame($request['duration'], 0.123); + $this->assertSame($request['providerClass'], 'FooProvider'); + $this->assertSame($request['result'], '{"latitude":0,"longitude":0,"bounds":null,"streetNumber":null,"streetName":null,"zipcode":null,"city":null,"cityDistrict":null,"county":null,"countyCode":null,"region":null,"regionCode":null,"country":null,"countryCode":null,"timezone":null}'); + } + + public function testLogNoResults() + { + $this->geocoderLogger->logRequest('copenhagen', 0.123, 'FooProvider', new \SplObjectStorage); + + $this->assertTrue(is_array($requests = $this->geocoderLogger->getRequests())); + $this->assertCount(1, $requests); + $this->assertTrue(is_array($request = $requests[0])); + $this->assertSame($request['value'], 'copenhagen'); + $this->assertSame($request['duration'], 0.123); + $this->assertSame($request['providerClass'], 'FooProvider'); + $this->assertSame($request['result'], '[]'); + } + public function testLogSingleResult() { $this->geocoderLogger->logRequest('copenhagen', 0.123, 'FooProvider', $this->result); From 0f96555c88c5b8cb58f9a1f289a77569c54a4426 Mon Sep 17 00:00:00 2001 From: Sebastian Grodzicki Date: Tue, 13 May 2014 09:52:06 +0200 Subject: [PATCH 025/235] Inline vector icon --- Resources/public/images/geocoder_marker.png | Bin 353 -> 0 bytes Resources/views/Collector/geocoder.html.twig | 4 ++-- 2 files changed, 2 insertions(+), 2 deletions(-) delete mode 100644 Resources/public/images/geocoder_marker.png diff --git a/Resources/public/images/geocoder_marker.png b/Resources/public/images/geocoder_marker.png deleted file mode 100644 index c2d89a74ea6c87085c9ec75828278b92211920a7..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 353 zcmV-n0iOPeP)$&XMp$*6rX{L zsWT7&ML_%wi2vij-=JzR02>f*$DXaohO1Qdthh(<-2>FdZyNb8WDXH13x#^`?B zLW1Tk*g}{TSD4|7rY+>!4g+SC*bW1`@MzveO!CC%3QJ + Geocoder {{ collector.requestscount }} {% endset %} {% set text %} @@ -20,7 +20,7 @@ {% block menu %} - Geocoder + Geocoder Geocoder {{ collector.requestsCount }} From 8b9306ac4542c92023fb389caed8464aeeea485f Mon Sep 17 00:00:00 2001 From: Iakov Mishchenko Date: Wed, 14 May 2014 17:56:40 +0300 Subject: [PATCH 026/235] Added api_key parameter for google_maps fixes #70 --- DependencyInjection/BazingaGeocoderExtension.php | 1 + DependencyInjection/Configuration.php | 1 + Resources/doc/index.md | 1 + 3 files changed, 3 insertions(+) diff --git a/DependencyInjection/BazingaGeocoderExtension.php b/DependencyInjection/BazingaGeocoderExtension.php index b1c488db..bfbf5350 100644 --- a/DependencyInjection/BazingaGeocoderExtension.php +++ b/DependencyInjection/BazingaGeocoderExtension.php @@ -92,6 +92,7 @@ public function load(array $configs, ContainerBuilder $container) $googleMapsParams['locale'], $googleMapsParams['region'], $googleMapsParams['use_ssl'], + $googleMapsParams['api_key'], )); } diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index c1f295d7..f067f3c3 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -102,6 +102,7 @@ public function getConfigTreeBuilder() ->scalarNode('locale')->defaultNull()->end() ->scalarNode('region')->defaultNull()->end() ->booleanNode('use_ssl')->defaultFalse()->end() + ->scalarNode('api_key')->defaultNull()->end() ->end() ->end() ->arrayNode('google_maps_business') diff --git a/Resources/doc/index.md b/Resources/doc/index.md index f9c60b6a..c28ea2cf 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -253,6 +253,7 @@ bazinga_geocoder: locale: ~ region: ~ use_ssl: false + api_key ~ google_maps_business: client_id: ~ # Required api_key: ~ From 702a2990474eaa182f9754113959ef37a9ff09cd Mon Sep 17 00:00:00 2001 From: Iakov Mishchenko Date: Thu, 15 May 2014 23:36:34 +0300 Subject: [PATCH 027/235] Added api key to fixtures --- Tests/DependencyInjection/Fixtures/config.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/Tests/DependencyInjection/Fixtures/config.yml b/Tests/DependencyInjection/Fixtures/config.yml index b658d602..18392b61 100644 --- a/Tests/DependencyInjection/Fixtures/config.yml +++ b/Tests/DependencyInjection/Fixtures/config.yml @@ -20,6 +20,7 @@ bazinga_geocoder: google_maps: locale: en_US region: en_US + api_key: 123 google_maps_business: client_id: 123 api_key: 123 From f12f008f79fb1c14405753f7670f3545abdd0fd9 Mon Sep 17 00:00:00 2001 From: Giorgio Premi Date: Thu, 3 Jul 2014 11:16:17 +0200 Subject: [PATCH 028/235] CacheProvider: better hashing function and namespace --- Provider/CacheProvider.php | 4 ++-- Tests/Provider/CacheProviderTest.php | 8 +++++--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/Provider/CacheProvider.php b/Provider/CacheProvider.php index b3e4806d..68936630 100644 --- a/Provider/CacheProvider.php +++ b/Provider/CacheProvider.php @@ -65,7 +65,7 @@ public function __construct(Cache $cache, ProviderInterface $provider, $lifetime */ public function getGeocodedData($address) { - $key = crc32($this->locale.$address); + $key = 'geocoder_' . sha1($this->locale . $address); if (false !== $data = $this->cache->fetch($key)) { return unserialize($data); @@ -82,7 +82,7 @@ public function getGeocodedData($address) */ public function getReversedData(array $coordinates) { - $key = crc32(serialize($this->locale . json_encode($coordinates))); + $key = 'geocoder_' . sha1($this->locale . json_encode($coordinates)); if (false !== $data = $this->cache->fetch($key)) { return unserialize($data); diff --git a/Tests/Provider/CacheProviderTest.php b/Tests/Provider/CacheProviderTest.php index 03653ae3..766c271f 100644 --- a/Tests/Provider/CacheProviderTest.php +++ b/Tests/Provider/CacheProviderTest.php @@ -14,6 +14,7 @@ public function testGetGeocodedData() { $address = 'Paris, France'; $coordinates = array('lat' => 48.857049,'lng' => 2.35223); + $cacheKey = 'geocoder_' . sha1($address); $delegate = $this->getMock('Geocoder\\Provider\\ProviderInterface'); $delegate->expects($this->once()) @@ -24,12 +25,12 @@ public function testGetGeocodedData() $cache = $this->getMock('Doctrine\\Common\\Cache\\Cache'); $cache->expects($this->once()) ->method('fetch') - ->with(crc32($address)) + ->with($cacheKey) ->will($this->returnValue(false)); $cache->expects($this->once()) ->method('save') - ->with(crc32($address), serialize($coordinates), 0); + ->with($cacheKey, serialize($coordinates), 0); $provider = new CacheProvider($cache, $delegate); $this->assertEquals($coordinates, $provider->getGeocodedData($address)); @@ -39,6 +40,7 @@ public function testGetCachedGeocodedData() { $address = 'Paris, France'; $coordinates = array('lat' => 48.857049,'lng' => 2.35223); + $cacheKey = 'geocoder_' . sha1($address); $delegate = $this->getMock('Geocoder\\Provider\\ProviderInterface'); $delegate->expects($this->once()) @@ -51,7 +53,7 @@ public function testGetCachedGeocodedData() $provider->getGeocodedData($address); $provider->getGeocodedData($address); - $this->assertTrue($cache->contains(crc32($address))); + $this->assertTrue($cache->contains($cacheKey)); } public function testGetReversedData() From 8e064718cd99161a2159e20abb4a6b40cc69cebe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ste=CC=81phane=20PY?= Date: Thu, 31 Jul 2014 10:26:55 +0200 Subject: [PATCH 029/235] - External services on chain providers - Perform no deep merging on providers. --- DependencyInjection/BazingaGeocoderExtension.php | 2 ++ DependencyInjection/Configuration.php | 1 + 2 files changed, 3 insertions(+) diff --git a/DependencyInjection/BazingaGeocoderExtension.php b/DependencyInjection/BazingaGeocoderExtension.php index b1c488db..56d3e90f 100644 --- a/DependencyInjection/BazingaGeocoderExtension.php +++ b/DependencyInjection/BazingaGeocoderExtension.php @@ -236,6 +236,8 @@ public function load(array $configs, ContainerBuilder $container) $chainProvider->addMethodCall('addProvider', array( $this->container->getDefinition('bazinga_geocoder.provider.'.$name) )); + } else { + $chainProvider->addMethodCall('addProvider', array(new Reference($name))); } } } diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index c1f295d7..8b655eec 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -172,6 +172,7 @@ public function getConfigTreeBuilder() ->fixXmlConfig('provider') ->children() ->arrayNode('providers') + ->performNoDeepMerging() ->prototype('scalar')->end() ->end() ->end() From 7bcd7ac2664b64fd6e2ee51d8ac1f3bd48515345 Mon Sep 17 00:00:00 2001 From: William DURAND Date: Thu, 31 Jul 2014 14:32:00 +0200 Subject: [PATCH 030/235] Fix cs --- Logger/GeocoderLogger.php | 8 ++++---- Tests/Command/GeocodeCommandTest.php | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Logger/GeocoderLogger.php b/Logger/GeocoderLogger.php index 1623a1e1..46608415 100644 --- a/Logger/GeocoderLogger.php +++ b/Logger/GeocoderLogger.php @@ -36,10 +36,10 @@ public function __construct(LoggerInterface $logger = null) } /** - * @param string $value value to geocode - * @param float $duration geocoding duration - * @param string $providerClass Geocoder provider class name - * @param \SplObjectStorage|Geocoded $results + * @param string $value value to geocode + * @param float $duration geocoding duration + * @param string $providerClass Geocoder provider class name + * @param \SplObjectStorage|Geocoded $results */ public function logRequest($value, $duration, $providerClass, $results) { diff --git a/Tests/Command/GeocodeCommandTest.php b/Tests/Command/GeocodeCommandTest.php index f197285c..7bfc9826 100644 --- a/Tests/Command/GeocodeCommandTest.php +++ b/Tests/Command/GeocodeCommandTest.php @@ -19,7 +19,7 @@ /** * @author Markus Bachmann */ -class GeocoderCommandTest extends \PHPUnit_Framework_TestCase +class GeocodeCommandTest extends \PHPUnit_Framework_TestCase { private static $address = '10 rue Gambetta, Paris, France'; From d4b29e26a6cabbfd2518c7a4c18570037353e343 Mon Sep 17 00:00:00 2001 From: William DURAND Date: Thu, 31 Jul 2014 14:33:38 +0200 Subject: [PATCH 031/235] Prepare 3.1.0 release --- composer.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index 56483381..5a2a283b 100644 --- a/composer.json +++ b/composer.json @@ -12,7 +12,7 @@ ], "require": { "symfony/framework-bundle": "~2.1", - "willdurand/geocoder": "~2.3", + "willdurand/geocoder": "~2.5", "symfony/console": "~2.1" }, "require-dev": { @@ -27,7 +27,7 @@ "target-dir": "Bazinga/Bundle/GeocoderBundle", "extra": { "branch-alias": { - "dev-master": "3.0-dev" + "dev-master": "3.1-dev" } } } From 1f50179ea09c28a6394ab9f5c6e759b024d47714 Mon Sep 17 00:00:00 2001 From: William DURAND Date: Thu, 31 Jul 2014 14:46:43 +0200 Subject: [PATCH 032/235] update config reference --- Resources/doc/index.md | 44 ++++++++++++++++++++++++++---------------- 1 file changed, 27 insertions(+), 17 deletions(-) diff --git a/Resources/doc/index.md b/Resources/doc/index.md index c28ea2cf..16bd8df7 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -1,14 +1,20 @@ BazingaGeocoderBundle ===================== -Integration of the [**Geocoder**](http://github.com/geocoder-php/Geocoder) library -into Symfony2. +Integration of the [**Geocoder**](http://github.com/geocoder-php/Geocoder) +library into Symfony2. + +* [Installation](#installation) +* [Usage](#usage) +* [Reference Configuration](#reference-configuration) +* [Testing](#testing) Installation ------------ -Require [`willdurand/geocoder-bundle`](https://packagist.org/packages/willdurand/geocoder-bundle) +Require +[`willdurand/geocoder-bundle`](https://packagist.org/packages/willdurand/geocoder-bundle) to your `composer.json` file: @@ -232,35 +238,36 @@ You'll find the reference configuration below: bazinga_geocoder: fake_ip: enabled: true - ip: ~ + ip: null priority: 0 adapter: - class: ~ + class: null providers: bing_maps: api_key: ~ # Required - locale: ~ + locale: null cache: adapter: ~ # Required provider: ~ # Required - locale: ~ + locale: null lifetime: 86400 ip_info_db: api_key: ~ # Required cloudmade: api_key: ~ # Required google_maps: - locale: ~ - region: ~ + locale: null + region: null use_ssl: false - api_key ~ + api_key: null google_maps_business: client_id: ~ # Required - api_key: ~ - region: ~ + api_key: null + locale: null + region: null use_ssl: false openstreetmap: - locale: ~ + locale: null host_ip: [] geoip: [] free_geo_ip: [] @@ -273,18 +280,21 @@ bazinga_geocoder: api_key: ~ # Required data_science_toolkit: [] yandex: - locale: ~ - toponym: ~ + locale: null + toponym: null geo_ips: - api_key: ~ + api_key: null geo_plugin: [] maxmind: api_key: ~ # Required maxmind_binary: binary_file: ~ # Required - open_flag: ~ + open_flag: null chain: providers: [] + tom_tom: + api_key: ~ # Required + locale: null ``` From 2b8e1390f140df9bd33eb84012d596b467b6dbfd Mon Sep 17 00:00:00 2001 From: William DURAND Date: Thu, 31 Jul 2014 14:49:16 +0200 Subject: [PATCH 033/235] update toc --- Resources/doc/index.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 16bd8df7..a71581ed 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -6,6 +6,11 @@ library into Symfony2. * [Installation](#installation) * [Usage](#usage) + * [Killer Feature](#killer-feature) + * [Registering Your Own Providers](#registering-your-own-providers) + * [Dumpers](#dumpers) + * [Cache Provider](#cache-provider) + * [Symfony2 Profiler Integration](#symfony2-profiler-integration) * [Reference Configuration](#reference-configuration) * [Testing](#testing) @@ -234,7 +239,6 @@ You'll find the reference configuration below: ``` yaml # app/config/config*.yml - bazinga_geocoder: fake_ip: enabled: true From 1c19e216a4ab8ccc9124a98fb92ea4a4c6e199ad Mon Sep 17 00:00:00 2001 From: Baachi Date: Fri, 1 Aug 2014 09:30:12 +0200 Subject: [PATCH 034/235] Add default_provider parameter Add tests Fix tests --- .../BazingaGeocoderExtension.php | 4 ++++ .../Compiler/AddProvidersPass.php | 13 +++++++---- DependencyInjection/Configuration.php | 1 + .../BazingaGeocoderExtensionTest.php | 22 +++++++++++++++++++ Tests/DependencyInjection/Fixtures/config.yml | 1 + 5 files changed, 37 insertions(+), 4 deletions(-) diff --git a/DependencyInjection/BazingaGeocoderExtension.php b/DependencyInjection/BazingaGeocoderExtension.php index d7c143a2..c607a0ea 100644 --- a/DependencyInjection/BazingaGeocoderExtension.php +++ b/DependencyInjection/BazingaGeocoderExtension.php @@ -36,6 +36,10 @@ public function load(array $configs, ContainerBuilder $container) $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.xml'); + if ($config['default_provider']) { + $container->setParameter('bazinga_geocoder.default_provider', $config['default_provider']); + } + if (!empty($config['fake_ip']) && true === $config['fake_ip']['enabled']) { $definition = $container->getDefinition('bazinga_geocoder.event_listener.fake_request'); $definition->replaceArgument(0, $config['fake_ip']['ip']); diff --git a/DependencyInjection/Compiler/AddProvidersPass.php b/DependencyInjection/Compiler/AddProvidersPass.php index 83597f83..e3364b28 100644 --- a/DependencyInjection/Compiler/AddProvidersPass.php +++ b/DependencyInjection/Compiler/AddProvidersPass.php @@ -41,9 +41,14 @@ public function process(ContainerBuilder $container) $array[] = new Reference($providerId); } - $container - ->getDefinition('bazinga_geocoder.geocoder') - ->addMethodCall('registerProviders', array($array)) - ; + $geocoderDefinition =$container->getDefinition('bazinga_geocoder.geocoder'); + $geocoderDefinition->addMethodCall('registerProviders', array($array)); + + if ($container->hasParameter('bazinga_geocoder.default_provider')) { + $geocoderDefinition->addMethodCall( + 'using', + array($container->getParameter('bazinga_geocoder.default_provider')) + ); + } } } diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 41935538..fa1eceb0 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -30,6 +30,7 @@ public function getConfigTreeBuilder() $rootNode ->children() + ->scalarNode('default_provider')->defaultNull()->end() ->arrayNode('fake_ip') ->beforeNormalization() ->ifString() diff --git a/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php b/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php index c1981fc2..cd4616fe 100644 --- a/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php +++ b/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php @@ -18,6 +18,8 @@ class BazingaGeocoderExtensionTest extends \PHPUnit_Framework_TestCase public function testLoad() { $configs = Yaml::parse(file_get_contents(__DIR__.'/Fixtures/config.yml')); + unset($configs['bazinga_geocoder']['default_provider']); + $container = new ContainerBuilder(); $extension = new BazingaGeocoderExtension(); @@ -46,6 +48,8 @@ public function testLoad() $this->assertTrue($dumperManager->has($name)); } + $this->assertFalse($container->hasParameter('bazinga_geocoder.default_provider')); + $geocoder = $container->get('bazinga_geocoder.geocoder'); $providers = $geocoder->getProviders(); foreach (array( @@ -75,6 +79,24 @@ public function testLoad() } } + public function testDefaultProvider() + { + $configs = Yaml::parse(file_get_contents(__DIR__.'/Fixtures/config.yml')); + $container = new ContainerBuilder(); + $extension = new BazingaGeocoderExtension(); + + $container->setParameter('fixtures_dir', __DIR__ . '/Fixtures'); + + $container->set('doctrine.apc.cache', new ArrayCache()); + + $container->addCompilerPass(new AddProvidersPass()); + $extension->load($configs, $container); + + $container->compile(); + + $this->assertEquals('bing_maps', $container->getParameter('bazinga_geocoder.default_provider')); + } + public function testLoadingFakeIpOldWay() { $configs = Yaml::parse(file_get_contents(__DIR__.'/Fixtures/old_fake_ip.yml')); diff --git a/Tests/DependencyInjection/Fixtures/config.yml b/Tests/DependencyInjection/Fixtures/config.yml index 18392b61..d4272cba 100644 --- a/Tests/DependencyInjection/Fixtures/config.yml +++ b/Tests/DependencyInjection/Fixtures/config.yml @@ -1,4 +1,5 @@ bazinga_geocoder: + default_provider: bing_maps fake_ip: ip: 33.33.33.11 priority: 128 From 2bb5059fc9c39b56cb0ba2c54f731b128107c525 Mon Sep 17 00:00:00 2001 From: Antoine Corcy Date: Wed, 17 Dec 2014 23:04:06 +0100 Subject: [PATCH 035/235] add code of conduct to the doc --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index 6c59c95b..a080dc97 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,13 @@ Credits * [All contributors](https://github.com/geocoder-php/BazingaGeocoderBundle/contributors) +Contributor Code of Conduct +--------------------------- + +Please note that this project is released with a Contributor Code of Conduct. +By participating in this project you agree to abide by its terms. + + License ------- From 934d978bb88035e672673d2353095506c0f8fd49 Mon Sep 17 00:00:00 2001 From: Ross Masters Date: Thu, 15 Jan 2015 15:40:26 +0000 Subject: [PATCH 036/235] Add default_provider to the reference config --- Resources/doc/index.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Resources/doc/index.md b/Resources/doc/index.md index a71581ed..e53e9ee3 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -246,6 +246,7 @@ bazinga_geocoder: priority: 0 adapter: class: null + default_provider: ~ # Name of provider, e.g. chain providers: bing_maps: api_key: ~ # Required From db6599147c144ef2f6a8d805d2385bf320bd6f67 Mon Sep 17 00:00:00 2001 From: c33s Date: Mon, 23 Feb 2015 17:08:50 +0100 Subject: [PATCH 037/235] exchanged the deprecated liip/doctrine-cache-bundle with the maintained doctrine/doctrine-cache-bundle --- Resources/doc/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Resources/doc/index.md b/Resources/doc/index.md index a71581ed..64c15ca4 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -216,7 +216,7 @@ bazinga_geocoder: ``` > **Tip:** If you want to configure the cache adapter, -> we recommend the [liip/doctrine-cache-bundle](https://github.com/liip/LiipDoctrineCacheBundle). +> we recommend the [doctrine/doctrine-cache-bundle](https://github.com/doctrine/DoctrineCacheBundle). ### Symfony2 Profiler Integration From 07910abd649ef80fc1cf5be3e8ae13784eeadd06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?K=C3=A9vin=20Gomez?= Date: Sun, 1 Mar 2015 12:36:08 +0000 Subject: [PATCH 038/235] Removed all references to the CloudMade provider as it does not exist in Geocoder anymore --- DependencyInjection/BazingaGeocoderExtension.php | 8 -------- DependencyInjection/Configuration.php | 7 ------- Resources/config/services.xml | 1 - Resources/doc/index.md | 2 -- .../DependencyInjection/BazingaGeocoderExtensionTest.php | 1 - Tests/DependencyInjection/Fixtures/config.yml | 2 -- 6 files changed, 21 deletions(-) diff --git a/DependencyInjection/BazingaGeocoderExtension.php b/DependencyInjection/BazingaGeocoderExtension.php index c607a0ea..14c0a198 100644 --- a/DependencyInjection/BazingaGeocoderExtension.php +++ b/DependencyInjection/BazingaGeocoderExtension.php @@ -81,14 +81,6 @@ public function load(array $configs, ContainerBuilder $container) )); } - if (isset($config['providers']['cloudmade'])) { - $cloudMadeParams = $config['providers']['cloudmade']; - - $this->addProvider('cloudmade', array( - $cloudMadeParams['api_key'] - )); - } - if (isset($config['providers']['google_maps'])) { $googleMapsParams = $config['providers']['google_maps']; diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index fa1eceb0..4bf6088f 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -91,13 +91,6 @@ public function getConfigTreeBuilder() ->end() ->end() ->end() - ->arrayNode('cloudmade') - ->children() - ->scalarNode('api_key') - ->isRequired()->cannotBeEmpty() - ->end() - ->end() - ->end() ->arrayNode('google_maps') ->children() ->scalarNode('locale')->defaultNull()->end() diff --git a/Resources/config/services.xml b/Resources/config/services.xml index 2535d43d..e93a317c 100644 --- a/Resources/config/services.xml +++ b/Resources/config/services.xml @@ -14,7 +14,6 @@ Geocoder\Provider\HostIpProvider Geocoder\Provider\IpInfoDbProvider Geocoder\Provider\YahooProvider - Geocoder\Provider\CloudMadeProvider Geocoder\Provider\OpenStreetMapProvider Geocoder\Provider\GeoipProvider Geocoder\Provider\MapQuestProvider diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 64c15ca4..c8ad9e68 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -257,8 +257,6 @@ bazinga_geocoder: lifetime: 86400 ip_info_db: api_key: ~ # Required - cloudmade: - api_key: ~ # Required google_maps: locale: null region: null diff --git a/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php b/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php index cd4616fe..fc319e8f 100644 --- a/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php +++ b/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php @@ -56,7 +56,6 @@ public function testLoad() 'bing_maps' => 'Geocoder\\Provider\\BingMapsProvider', 'cache' => 'Bazinga\\Bundle\\GeocoderBundle\\Provider\\CacheProvider', 'ip_info_db' => 'Geocoder\\Provider\\IpInfoDbProvider', - 'cloudmade' => 'Geocoder\\Provider\\CloudMadeProvider', 'google_maps' => 'Geocoder\\Provider\\GoogleMapsProvider', 'google_maps_business' => 'Geocoder\\Provider\\GoogleMapsBusinessProvider', 'openstreetmap' => 'Geocoder\\Provider\\OpenStreetMapProvider', diff --git a/Tests/DependencyInjection/Fixtures/config.yml b/Tests/DependencyInjection/Fixtures/config.yml index d4272cba..d8b471dc 100644 --- a/Tests/DependencyInjection/Fixtures/config.yml +++ b/Tests/DependencyInjection/Fixtures/config.yml @@ -16,8 +16,6 @@ bazinga_geocoder: lifetime: 86400 ip_info_db: api_key: 123 - cloudmade: - api_key: 123 google_maps: locale: en_US region: en_US From 2726562dc88e6ddfa03362e6ad1d8b4071d3ff50 Mon Sep 17 00:00:00 2001 From: Tobias Nyholm Date: Mon, 8 Jun 2015 12:23:32 +0200 Subject: [PATCH 039/235] Added style tag in the toolbar --- Resources/views/Collector/geocoder.html.twig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Resources/views/Collector/geocoder.html.twig b/Resources/views/Collector/geocoder.html.twig index efed6ea4..3ae493be 100644 --- a/Resources/views/Collector/geocoder.html.twig +++ b/Resources/views/Collector/geocoder.html.twig @@ -2,7 +2,7 @@ {% block toolbar %} {% set icon %} - Geocoder + Geocoder {{ collector.requestscount }} {% endset %} {% set text %} From 115959f8b66c5192b531e203bdb26a48e5e7a655 Mon Sep 17 00:00:00 2001 From: Nicolas Assing Date: Sun, 16 Aug 2015 13:32:27 +0200 Subject: [PATCH 040/235] add opencage provider --- DependencyInjection/BazingaGeocoderExtension.php | 10 ++++++++++ DependencyInjection/Configuration.php | 7 +++++++ Resources/config/services.xml | 1 + Resources/doc/index.md | 4 ++++ .../BazingaGeocoderExtensionTest.php | 1 + Tests/DependencyInjection/Fixtures/config.yml | 3 +++ 6 files changed, 26 insertions(+) diff --git a/DependencyInjection/BazingaGeocoderExtension.php b/DependencyInjection/BazingaGeocoderExtension.php index 14c0a198..20043d66 100644 --- a/DependencyInjection/BazingaGeocoderExtension.php +++ b/DependencyInjection/BazingaGeocoderExtension.php @@ -195,6 +195,16 @@ public function load(array $configs, ContainerBuilder $container) $container->setDefinition('bazinga_geocoder.provider.maxmind_binary', $provider); } + if (isset($config['providers']['opencage'])) { + $openCageParams = $config['providers']['opencage']; + + $this->addProvider('opencage', array( + $openCageParams['locale'], + $openCageParams['use_ssl'], + $openCageParams['api_key'], + )); + } + if (isset($config['providers']['cache'])) { $params = $config['providers']['cache']; $cache = new Reference($params['adapter']); diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 4bf6088f..721794e2 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -163,6 +163,13 @@ public function getConfigTreeBuilder() ->end() ->end() ->end() + ->arrayNode('opencage') + ->children() + ->scalarNode('locale')->defaultNull()->end() + ->booleanNode('use_ssl')->defaultFalse()->end() + ->scalarNode('api_key')->isRequired()->cannotBeEmpty()->end() + ->end() + ->end() ->arrayNode('chain') ->fixXmlConfig('provider') ->children() diff --git a/Resources/config/services.xml b/Resources/config/services.xml index e93a317c..c3f9cb5e 100644 --- a/Resources/config/services.xml +++ b/Resources/config/services.xml @@ -27,6 +27,7 @@ Geocoder\Provider\GeoPluginProvider Geocoder\Provider\MaxMindProvider Geocoder\Provider\MaxMindBinaryProvider + Geocoder\Provider\OpenCageProvider Bazinga\Bundle\GeocoderBundle\Provider\CacheProvider Geocoder\Provider\ChainProvider Geocoder\Provider\TomTomProvider diff --git a/Resources/doc/index.md b/Resources/doc/index.md index c040a747..cb033543 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -293,6 +293,10 @@ bazinga_geocoder: maxmind_binary: binary_file: ~ # Required open_flag: null + opencage: + locale: null + use_ssl: false + api_key: null chain: providers: [] tom_tom: diff --git a/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php b/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php index fc319e8f..2fd69a1a 100644 --- a/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php +++ b/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php @@ -73,6 +73,7 @@ public function testLoad() 'maxmind' => 'Geocoder\\Provider\\MaxmindProvider', 'chain' => 'Geocoder\\Provider\\ChainProvider', 'maxmind_binary' => 'Geocoder\\Provider\\MaxmindBinaryProvider', + 'opencage' => 'Geocoder\\Provider\\OpenCageProvider', ) as $name => $class) { $this->assertInstanceOf($class, $providers[$name], sprintf('-> Assert that %s is instance of %s', $name, $class)); } diff --git a/Tests/DependencyInjection/Fixtures/config.yml b/Tests/DependencyInjection/Fixtures/config.yml index d8b471dc..aa1896b6 100644 --- a/Tests/DependencyInjection/Fixtures/config.yml +++ b/Tests/DependencyInjection/Fixtures/config.yml @@ -48,5 +48,8 @@ bazinga_geocoder: api_key: 123 maxmind_binary: binary_file: %fixtures_dir%/maxmind.dat + opencage: + locale: en_US + api_key: 123 chain: providers: [free_geo_ip, host_ip] From 01d181dfbbe3ff2a8ab65f0791d3baadd79d5914 Mon Sep 17 00:00:00 2001 From: Nicolas Assing Date: Sun, 16 Aug 2015 13:33:49 +0200 Subject: [PATCH 041/235] CS --- BazingaGeocoderBundle.php | 2 - Command/GeocodeCommand.php | 7 ++- DataCollector/GeocoderDataCollector.php | 4 +- .../BazingaGeocoderExtension.php | 29 +++++------ .../Compiler/AddDumperPass.php | 3 +- .../Compiler/AddProvidersPass.php | 3 +- DependencyInjection/Compiler/LoggablePass.php | 3 +- DependencyInjection/Configuration.php | 1 - Doctrine/ORM/GeocoderListener.php | 11 ++-- DumperManager.php | 10 ++-- EventListener/FakeRequestListener.php | 1 - Geocoder/LoggableGeocoder.php | 18 +++---- Logger/GeocoderLogger.php | 9 ++-- Mapping/Annotations/Address.php | 1 - Mapping/Driver/DriverInterface.php | 2 +- Provider/CacheProvider.php | 25 +++++---- Tests/Command/GeocodeCommandTest.php | 2 - .../BazingaGeocoderExtensionTest.php | 52 +++++++++---------- .../Compiler/AddDumperPassTest.php | 4 +- .../DependencyInjection/ConfigurationTest.php | 2 +- Tests/Doctrine/ORM/GeocoderListenerTest.php | 2 +- Tests/DumperManagerTest.php | 2 +- Tests/Logger/GeocoderLoggerTest.php | 17 +++--- Tests/Mapping/Driver/AnnotationDriverTest.php | 7 +-- Tests/Provider/CacheProviderTest.php | 4 +- Tests/bootstrap.php | 10 ++-- 26 files changed, 106 insertions(+), 125 deletions(-) diff --git a/BazingaGeocoderBundle.php b/BazingaGeocoderBundle.php index 5624c2e3..03aef541 100644 --- a/BazingaGeocoderBundle.php +++ b/BazingaGeocoderBundle.php @@ -7,12 +7,10 @@ * * @license MIT License */ - namespace Bazinga\Bundle\GeocoderBundle; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Bundle\Bundle; - use Bazinga\Bundle\GeocoderBundle\DependencyInjection\Compiler\AddProvidersPass; use Bazinga\Bundle\GeocoderBundle\DependencyInjection\Compiler\AddDumperPass; use Bazinga\Bundle\GeocoderBundle\DependencyInjection\Compiler\LoggablePass; diff --git a/Command/GeocodeCommand.php b/Command/GeocodeCommand.php index a0cadece..e827a4a0 100644 --- a/Command/GeocodeCommand.php +++ b/Command/GeocodeCommand.php @@ -7,7 +7,6 @@ * * @license MIT License */ - namespace Bazinga\Bundle\GeocoderBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; @@ -22,7 +21,7 @@ class GeocodeCommand extends ContainerAwareCommand { /** - * {@inheritDoc} + * {@inheritdoc} */ protected function configure() { @@ -43,7 +42,7 @@ protected function configure() } /** - * {@inheritDoc} + * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { @@ -55,7 +54,7 @@ protected function execute(InputInterface $input, OutputInterface $output) } $result = $geocoder->geocode($input->getArgument('address')); - $data = $result->toArray(); + $data = $result->toArray(); $max = 0; diff --git a/DataCollector/GeocoderDataCollector.php b/DataCollector/GeocoderDataCollector.php index a11ebbb6..d11dd120 100644 --- a/DataCollector/GeocoderDataCollector.php +++ b/DataCollector/GeocoderDataCollector.php @@ -7,7 +7,6 @@ * * @license MIT License */ - namespace Bazinga\Bundle\GeocoderBundle\DataCollector; use Bazinga\Bundle\GeocoderBundle\Logger\GeocoderLogger; @@ -26,7 +25,6 @@ class GeocoderDataCollector extends DataCollector protected $logger; /** - * * @param GeocoderLogger $logger */ public function __construct(GeocoderLogger $logger) @@ -57,7 +55,7 @@ public function getRequests() /** * Returns the number of collected requests. * - * @return integer + * @return int */ public function getRequestsCount() { diff --git a/DependencyInjection/BazingaGeocoderExtension.php b/DependencyInjection/BazingaGeocoderExtension.php index 20043d66..1a87fea5 100644 --- a/DependencyInjection/BazingaGeocoderExtension.php +++ b/DependencyInjection/BazingaGeocoderExtension.php @@ -7,7 +7,6 @@ * * @license MIT License */ - namespace Bazinga\Bundle\GeocoderBundle\DependencyInjection; use Symfony\Component\HttpKernel\DependencyInjection\Extension; @@ -19,7 +18,7 @@ use Symfony\Component\Config\Definition\Processor; /** - * William Durand + * William Durand . */ class BazingaGeocoderExtension extends Extension { @@ -29,9 +28,9 @@ public function load(array $configs, ContainerBuilder $container) { $this->container = $container; - $processor = new Processor(); - $configuration = new Configuration(); - $config = $processor->processConfiguration($configuration, $configs); + $processor = new Processor(); + $configuration = new Configuration(); + $config = $processor->processConfiguration($configuration, $configs); $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.xml'); @@ -77,7 +76,7 @@ public function load(array $configs, ContainerBuilder $container) $ipInfoDbParams = $config['providers']['ip_info_db']; $this->addProvider('ip_info_db', array( - $ipInfoDbParams['api_key'] + $ipInfoDbParams['api_key'], )); } @@ -108,7 +107,7 @@ public function load(array $configs, ContainerBuilder $container) $openstreetMapsParams = $config['providers']['openstreetmap']; $this->addProvider('openstreetmap', array( - $openstreetMapsParams['locale'] + $openstreetMapsParams['locale'], )); } @@ -120,7 +119,7 @@ public function load(array $configs, ContainerBuilder $container) $mapQuestParams = $config['providers']['mapquest']; $this->addProvider('mapquest', array( - $mapQuestParams['api_key'] + $mapQuestParams['api_key'], )); } @@ -140,7 +139,7 @@ public function load(array $configs, ContainerBuilder $container) $ignOpenlsParams = $config['providers']['ign_openls']; $this->addProvider('ign_openls', array( - $ignOpenlsParams['api_key'] + $ignOpenlsParams['api_key'], )); } @@ -153,7 +152,7 @@ public function load(array $configs, ContainerBuilder $container) $this->addProvider('yandex', array( $yandexParams['locale'], - $yandexParams['toponym'] + $yandexParams['toponym'], )); } @@ -161,7 +160,7 @@ public function load(array $configs, ContainerBuilder $container) $geoIpsParams = $config['providers']['geo_ips']; $this->addProvider('geo_ips', array( - $geoIpsParams['api_key'] + $geoIpsParams['api_key'], )); } @@ -173,7 +172,7 @@ public function load(array $configs, ContainerBuilder $container) $maxmindParams = $config['providers']['maxmind']; $this->addProvider('maxmind', array( - $maxmindParams['api_key'] + $maxmindParams['api_key'], )); } @@ -206,8 +205,8 @@ public function load(array $configs, ContainerBuilder $container) } if (isset($config['providers']['cache'])) { - $params = $config['providers']['cache']; - $cache = new Reference($params['adapter']); + $params = $config['providers']['cache']; + $cache = new Reference($params['adapter']); $fallback = new Reference('bazinga_geocoder.provider.'.$params['provider']); $provider = new Definition( @@ -241,7 +240,7 @@ public function load(array $configs, ContainerBuilder $container) foreach ($config['providers']['chain']['providers'] as $name) { if ($this->container->hasDefinition('bazinga_geocoder.provider.'.$name)) { $chainProvider->addMethodCall('addProvider', array( - $this->container->getDefinition('bazinga_geocoder.provider.'.$name) + $this->container->getDefinition('bazinga_geocoder.provider.'.$name), )); } else { $chainProvider->addMethodCall('addProvider', array(new Reference($name))); diff --git a/DependencyInjection/Compiler/AddDumperPass.php b/DependencyInjection/Compiler/AddDumperPass.php index 6e7b3f1b..c9563347 100644 --- a/DependencyInjection/Compiler/AddDumperPass.php +++ b/DependencyInjection/Compiler/AddDumperPass.php @@ -7,7 +7,6 @@ * * @license MIT License */ - namespace Bazinga\Bundle\GeocoderBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; @@ -19,7 +18,7 @@ class AddDumperPass implements CompilerPassInterface { /** - * {@inheritDoc} + * {@inheritdoc} */ public function process(ContainerBuilder $container) { diff --git a/DependencyInjection/Compiler/AddProvidersPass.php b/DependencyInjection/Compiler/AddProvidersPass.php index e3364b28..fe697e10 100644 --- a/DependencyInjection/Compiler/AddProvidersPass.php +++ b/DependencyInjection/Compiler/AddProvidersPass.php @@ -7,7 +7,6 @@ * * @license MIT License */ - namespace Bazinga\Bundle\GeocoderBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; @@ -41,7 +40,7 @@ public function process(ContainerBuilder $container) $array[] = new Reference($providerId); } - $geocoderDefinition =$container->getDefinition('bazinga_geocoder.geocoder'); + $geocoderDefinition = $container->getDefinition('bazinga_geocoder.geocoder'); $geocoderDefinition->addMethodCall('registerProviders', array($array)); if ($container->hasParameter('bazinga_geocoder.default_provider')) { diff --git a/DependencyInjection/Compiler/LoggablePass.php b/DependencyInjection/Compiler/LoggablePass.php index 01a57c78..34ed6c71 100644 --- a/DependencyInjection/Compiler/LoggablePass.php +++ b/DependencyInjection/Compiler/LoggablePass.php @@ -7,7 +7,6 @@ * * @license MIT License */ - namespace Bazinga\Bundle\GeocoderBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; @@ -20,7 +19,7 @@ class LoggablePass implements CompilerPassInterface { /** - * {@inheritDoc} + * {@inheritdoc} */ public function process(ContainerBuilder $container) { diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 721794e2..ba30c001 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -7,7 +7,6 @@ * * @license MIT License */ - namespace Bazinga\Bundle\GeocoderBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; diff --git a/Doctrine/ORM/GeocoderListener.php b/Doctrine/ORM/GeocoderListener.php index fc2a8f32..2172c5a7 100644 --- a/Doctrine/ORM/GeocoderListener.php +++ b/Doctrine/ORM/GeocoderListener.php @@ -5,7 +5,6 @@ use Doctrine\Common\EventSubscriber; use Doctrine\ORM\Events; use Doctrine\ORM\Event\OnFlushEventArgs; - use Bazinga\Bundle\GeocoderBundle\Mapping\Driver\DriverInterface; use Geocoder\Geocoder; @@ -20,17 +19,17 @@ class GeocoderListener implements EventSubscriber public function __construct(Geocoder $geocoder, DriverInterface $driver) { - $this->driver = $driver; + $this->driver = $driver; $this->geocoder = $geocoder; } /** - * {@inheritDoc} + * {@inheritdoc} */ public function getSubscribedEvents() { return array( - Events::onFlush + Events::onFlush, ); } @@ -69,8 +68,8 @@ public function onFlush(OnFlushEventArgs $args) private function geocodeEntity($entity) { $metadata = $this->driver->loadMetadataFromObject($entity); - $address = $metadata->addressProperty->getValue($entity); - $result = $this->geocoder->geocode($address); + $address = $metadata->addressProperty->getValue($entity); + $result = $this->geocoder->geocode($address); $metadata->latitudeProperty->setValue($entity, $result['latitude']); $metadata->longitudeProperty->setValue($entity, $result['longitude']); diff --git a/DumperManager.php b/DumperManager.php index e3ae390b..faf042b0 100644 --- a/DumperManager.php +++ b/DumperManager.php @@ -1,4 +1,5 @@ logger->logRequest( - sprintf("[Geocoding] %s", $value), + sprintf('[Geocoding] %s', $value), $duration, $this->getProviderClass(), $results @@ -53,7 +51,7 @@ public function geocode($value) } /** - * {@inheritDoc} + * {@inheritdoc} */ public function reverse($latitude, $longitude) { @@ -62,10 +60,10 @@ public function reverse($latitude, $longitude) } $startTime = microtime(true); - $results = parent::reverse($latitude, $longitude); - $duration = (microtime(true) - $startTime) * 1000; + $results = parent::reverse($latitude, $longitude); + $duration = (microtime(true) - $startTime) * 1000; - $value = sprintf("[Reverse geocoding] latitude: %s, longitude: %s", $latitude, $longitude); + $value = sprintf('[Reverse geocoding] latitude: %s, longitude: %s', $latitude, $longitude); $this->logger->logRequest($value, $duration, $this->getProviderClass(), $results); diff --git a/Logger/GeocoderLogger.php b/Logger/GeocoderLogger.php index 46608415..08d2bcc7 100644 --- a/Logger/GeocoderLogger.php +++ b/Logger/GeocoderLogger.php @@ -7,7 +7,6 @@ * * @license MIT License */ - namespace Bazinga\Bundle\GeocoderBundle\Logger; use Symfony\Component\HttpKernel\Log\LoggerInterface; @@ -44,7 +43,7 @@ public function __construct(LoggerInterface $logger = null) public function logRequest($value, $duration, $providerClass, $results) { if (null !== $this->logger) { - $this->logger->info(sprintf("%s %0.2f ms (%s)", $value, $duration, $providerClass)); + $this->logger->info(sprintf('%s %0.2f ms (%s)', $value, $duration, $providerClass)); } $data = array(); @@ -59,10 +58,10 @@ public function logRequest($value, $duration, $providerClass, $results) } $this->requests[] = array( - 'value' => $value, - 'duration' => $duration, + 'value' => $value, + 'duration' => $duration, 'providerClass' => $providerClass, - 'result' => json_encode($data), + 'result' => json_encode($data), ); } diff --git a/Mapping/Annotations/Address.php b/Mapping/Annotations/Address.php index c2b36cf4..09a8e712 100644 --- a/Mapping/Annotations/Address.php +++ b/Mapping/Annotations/Address.php @@ -9,5 +9,4 @@ */ class Address { - } diff --git a/Mapping/Driver/DriverInterface.php b/Mapping/Driver/DriverInterface.php index fb5e60fc..a45ad58b 100644 --- a/Mapping/Driver/DriverInterface.php +++ b/Mapping/Driver/DriverInterface.php @@ -1,8 +1,8 @@ */ - namespace Bazinga\Bundle\GeocoderBundle\Mapping\Driver; interface DriverInterface diff --git a/Provider/CacheProvider.php b/Provider/CacheProvider.php index 68936630..76046a4b 100644 --- a/Provider/CacheProvider.php +++ b/Provider/CacheProvider.php @@ -7,7 +7,6 @@ * * @license MIT License */ - namespace Bazinga\Bundle\GeocoderBundle\Provider; use Geocoder\Geocoder; @@ -30,7 +29,7 @@ class CacheProvider implements ProviderInterface private $provider; /** - * @var integer + * @var int */ private $lifetime; @@ -40,32 +39,32 @@ class CacheProvider implements ProviderInterface private $locale; /** - * @var integer + * @var int */ private $maxResults = Geocoder::MAX_RESULTS; /** - * Constructor + * Constructor. * * @param Cache $cache The cache interface * @param ProviderInterface $provider The fallback provider - * @param integer $lifetime The cache lifetime + * @param int $lifetime The cache lifetime * @param string $locale */ public function __construct(Cache $cache, ProviderInterface $provider, $lifetime = 0, $locale = null) { - $this->cache = $cache; + $this->cache = $cache; $this->provider = $provider; $this->lifetime = $lifetime; - $this->locale = $locale; + $this->locale = $locale; } /** - * {@inheritDoc} + * {@inheritdoc} */ public function getGeocodedData($address) { - $key = 'geocoder_' . sha1($this->locale . $address); + $key = 'geocoder_'.sha1($this->locale.$address); if (false !== $data = $this->cache->fetch($key)) { return unserialize($data); @@ -78,11 +77,11 @@ public function getGeocodedData($address) } /** - * {@inheritDoc} + * {@inheritdoc} */ public function getReversedData(array $coordinates) { - $key = 'geocoder_' . sha1($this->locale . json_encode($coordinates)); + $key = 'geocoder_'.sha1($this->locale.json_encode($coordinates)); if (false !== $data = $this->cache->fetch($key)) { return unserialize($data); @@ -95,7 +94,7 @@ public function getReversedData(array $coordinates) } /** - * {@inheritDoc} + * {@inheritdoc} */ public function getName() { @@ -103,7 +102,7 @@ public function getName() } /** - * {@inheritDoc} + * {@inheritdoc} */ public function setMaxResults($maxResults) { diff --git a/Tests/Command/GeocodeCommandTest.php b/Tests/Command/GeocodeCommandTest.php index 7bfc9826..dcd8876a 100644 --- a/Tests/Command/GeocodeCommandTest.php +++ b/Tests/Command/GeocodeCommandTest.php @@ -7,12 +7,10 @@ * * @license MIT License */ - namespace Bazinga\Bundle\GeocoderBundle\Tests\Command; use Bazinga\Bundle\GeocoderBundle\Command\GeocodeCommand; use Geocoder\Result\Geocoded; - use Symfony\Bundle\FrameworkBundle\Console\Application; use Symfony\Component\Console\Tester\CommandTester; diff --git a/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php b/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php index 2fd69a1a..4e098d24 100644 --- a/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php +++ b/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php @@ -17,13 +17,13 @@ class BazingaGeocoderExtensionTest extends \PHPUnit_Framework_TestCase { public function testLoad() { - $configs = Yaml::parse(file_get_contents(__DIR__.'/Fixtures/config.yml')); + $configs = Yaml::parse(file_get_contents(__DIR__.'/Fixtures/config.yml')); unset($configs['bazinga_geocoder']['default_provider']); $container = new ContainerBuilder(); $extension = new BazingaGeocoderExtension(); - $container->setParameter('fixtures_dir', __DIR__ . '/Fixtures'); + $container->setParameter('fixtures_dir', __DIR__.'/Fixtures'); $container->set('doctrine.apc.cache', new ArrayCache()); @@ -50,30 +50,30 @@ public function testLoad() $this->assertFalse($container->hasParameter('bazinga_geocoder.default_provider')); - $geocoder = $container->get('bazinga_geocoder.geocoder'); + $geocoder = $container->get('bazinga_geocoder.geocoder'); $providers = $geocoder->getProviders(); foreach (array( - 'bing_maps' => 'Geocoder\\Provider\\BingMapsProvider', - 'cache' => 'Bazinga\\Bundle\\GeocoderBundle\\Provider\\CacheProvider', - 'ip_info_db' => 'Geocoder\\Provider\\IpInfoDbProvider', - 'google_maps' => 'Geocoder\\Provider\\GoogleMapsProvider', + 'bing_maps' => 'Geocoder\\Provider\\BingMapsProvider', + 'cache' => 'Bazinga\\Bundle\\GeocoderBundle\\Provider\\CacheProvider', + 'ip_info_db' => 'Geocoder\\Provider\\IpInfoDbProvider', + 'google_maps' => 'Geocoder\\Provider\\GoogleMapsProvider', 'google_maps_business' => 'Geocoder\\Provider\\GoogleMapsBusinessProvider', - 'openstreetmap' => 'Geocoder\\Provider\\OpenStreetMapProvider', - 'host_ip' => 'Geocoder\\Provider\\HostIpProvider', - 'free_geo_ip' => 'Geocoder\\Provider\\FreeGeoIpProvider', - 'map_quest' => 'Geocoder\\Provider\\MapQuestProvider', - 'oio_rest' => 'Geocoder\\Provider\\OIORestProvider', - 'geocoder_ca' => 'Geocoder\\Provider\\GeocoderCaProvider', - 'geocoder_us' => 'Geocoder\\Provider\\GeocoderUsProvider', - 'ign_openls' => 'Geocoder\\Provider\\IGNOpenLSProvider', + 'openstreetmap' => 'Geocoder\\Provider\\OpenStreetMapProvider', + 'host_ip' => 'Geocoder\\Provider\\HostIpProvider', + 'free_geo_ip' => 'Geocoder\\Provider\\FreeGeoIpProvider', + 'map_quest' => 'Geocoder\\Provider\\MapQuestProvider', + 'oio_rest' => 'Geocoder\\Provider\\OIORestProvider', + 'geocoder_ca' => 'Geocoder\\Provider\\GeocoderCaProvider', + 'geocoder_us' => 'Geocoder\\Provider\\GeocoderUsProvider', + 'ign_openls' => 'Geocoder\\Provider\\IGNOpenLSProvider', 'data_science_toolkit' => 'Geocoder\\Provider\\DataScienceToolkitProvider', - 'yandex' => 'Geocoder\\Provider\\YandexProvider', - 'geo_ips' => 'Geocoder\\Provider\\GeoIpsProvider', - 'geo_plugin' => 'Geocoder\\Provider\\GeoPluginProvider', - 'maxmind' => 'Geocoder\\Provider\\MaxmindProvider', - 'chain' => 'Geocoder\\Provider\\ChainProvider', - 'maxmind_binary' => 'Geocoder\\Provider\\MaxmindBinaryProvider', - 'opencage' => 'Geocoder\\Provider\\OpenCageProvider', + 'yandex' => 'Geocoder\\Provider\\YandexProvider', + 'geo_ips' => 'Geocoder\\Provider\\GeoIpsProvider', + 'geo_plugin' => 'Geocoder\\Provider\\GeoPluginProvider', + 'maxmind' => 'Geocoder\\Provider\\MaxmindProvider', + 'chain' => 'Geocoder\\Provider\\ChainProvider', + 'maxmind_binary' => 'Geocoder\\Provider\\MaxmindBinaryProvider', + 'opencage' => 'Geocoder\\Provider\\OpenCageProvider', ) as $name => $class) { $this->assertInstanceOf($class, $providers[$name], sprintf('-> Assert that %s is instance of %s', $name, $class)); } @@ -81,11 +81,11 @@ public function testLoad() public function testDefaultProvider() { - $configs = Yaml::parse(file_get_contents(__DIR__.'/Fixtures/config.yml')); + $configs = Yaml::parse(file_get_contents(__DIR__.'/Fixtures/config.yml')); $container = new ContainerBuilder(); $extension = new BazingaGeocoderExtension(); - $container->setParameter('fixtures_dir', __DIR__ . '/Fixtures'); + $container->setParameter('fixtures_dir', __DIR__.'/Fixtures'); $container->set('doctrine.apc.cache', new ArrayCache()); @@ -99,11 +99,11 @@ public function testDefaultProvider() public function testLoadingFakeIpOldWay() { - $configs = Yaml::parse(file_get_contents(__DIR__.'/Fixtures/old_fake_ip.yml')); + $configs = Yaml::parse(file_get_contents(__DIR__.'/Fixtures/old_fake_ip.yml')); $container = new ContainerBuilder(); $extension = new BazingaGeocoderExtension(); - $container->setParameter('fixtures_dir', __DIR__ . '/Fixtures'); + $container->setParameter('fixtures_dir', __DIR__.'/Fixtures'); $container->set('doctrine.apc.cache', new ArrayCache()); diff --git a/Tests/DependencyInjection/Compiler/AddDumperPassTest.php b/Tests/DependencyInjection/Compiler/AddDumperPassTest.php index 5d62f1f9..25a7a7dc 100644 --- a/Tests/DependencyInjection/Compiler/AddDumperPassTest.php +++ b/Tests/DependencyInjection/Compiler/AddDumperPassTest.php @@ -13,7 +13,7 @@ class AddDumperPassTest extends \PHPUnit_Framework_TestCase { public function testProcess() { - $builder = new ContainerBuilder; + $builder = new ContainerBuilder(); $builder->setDefinition('bazinga_geocoder.dumper_manager', new Definition('Bazinga\Bundle\GeocoderBundle\DumperManager')); $dumper = new Definition('Geocoder\Dumper\GeoJsonDumper'); @@ -32,7 +32,7 @@ public function testProcess() public function testProcessWithoutManager() { $builder = new ContainerBuilder(); - $compiler = new AddDumperPass; + $compiler = new AddDumperPass(); $this->assertNull($compiler->process($builder)); } diff --git a/Tests/DependencyInjection/ConfigurationTest.php b/Tests/DependencyInjection/ConfigurationTest.php index 9ec1f488..89162209 100644 --- a/Tests/DependencyInjection/ConfigurationTest.php +++ b/Tests/DependencyInjection/ConfigurationTest.php @@ -17,7 +17,7 @@ public function testGetConfigTreeBuilder() $configuration = new Configuration(); $treeBuilder = $configuration->getConfigTreeBuilder(); - $processor = new Processor; + $processor = new Processor(); $config = $processor->process($treeBuilder->buildTree(), $config); } diff --git a/Tests/Doctrine/ORM/GeocoderListenerTest.php b/Tests/Doctrine/ORM/GeocoderListenerTest.php index 2bbe1d24..2a0cfb3f 100644 --- a/Tests/Doctrine/ORM/GeocoderListenerTest.php +++ b/Tests/Doctrine/ORM/GeocoderListenerTest.php @@ -50,7 +50,7 @@ protected function setUp() $sm = new SchemaTool($this->em); $sm->createSchema(array( - $this->em->getClassMetadata('Bazinga\Bundle\GeocoderBundle\Tests\Doctrine\ORM\Dummy') + $this->em->getClassMetadata('Bazinga\Bundle\GeocoderBundle\Tests\Doctrine\ORM\Dummy'), )); } diff --git a/Tests/DumperManagerTest.php b/Tests/DumperManagerTest.php index 273451ca..97a63bc6 100644 --- a/Tests/DumperManagerTest.php +++ b/Tests/DumperManagerTest.php @@ -16,7 +16,7 @@ class DumperManagerTest extends \PHPUnit_Framework_TestCase protected function setup() { - $this->manager = new DumperManager; + $this->manager = new DumperManager(); } public function testSet() diff --git a/Tests/Logger/GeocoderLoggerTest.php b/Tests/Logger/GeocoderLoggerTest.php index 82715475..9ebc42ff 100644 --- a/Tests/Logger/GeocoderLoggerTest.php +++ b/Tests/Logger/GeocoderLoggerTest.php @@ -7,7 +7,6 @@ * * @license MIT License */ - namespace Bazinga\Bundle\GeocoderBundle\Tests\Logger; use Bazinga\Bundle\GeocoderBundle\Logger\GeocoderLogger; @@ -33,18 +32,18 @@ public function setUp() $this->geocoderLogger = new GeocoderLogger($logger); - $this->result = new Geocoded; + $this->result = new Geocoded(); $this->result->fromArray(array( - 'latitude' => 1, + 'latitude' => 1, 'longitude' => 2, )); - $this->results = new \SplObjectStorage; + $this->results = new \SplObjectStorage(); $this->results->attach($this->result); - $otherResult = new Geocoded; + $otherResult = new Geocoded(); $otherResult->fromArray(array( - 'latitude' => 3, + 'latitude' => 3, 'longitude' => 4, )); @@ -53,7 +52,7 @@ public function setUp() public function testLogNoResult() { - $this->geocoderLogger->logRequest('copenhagen', 0.123, 'FooProvider', new Geocoded); + $this->geocoderLogger->logRequest('copenhagen', 0.123, 'FooProvider', new Geocoded()); $requests = $this->geocoderLogger->getRequests(); @@ -68,7 +67,7 @@ public function testLogNoResult() public function testLogNoResults() { - $this->geocoderLogger->logRequest('copenhagen', 0.123, 'FooProvider', new \SplObjectStorage); + $this->geocoderLogger->logRequest('copenhagen', 0.123, 'FooProvider', new \SplObjectStorage()); $this->assertTrue(is_array($requests = $this->geocoderLogger->getRequests())); $this->assertCount(1, $requests); @@ -138,7 +137,7 @@ public function testLog2RequetsWithMultipleResults() public function testLogRequestsWithoutLogger() { - $geocoderLogger = new GeocoderLogger; + $geocoderLogger = new GeocoderLogger(); $geocoderLogger->logRequest('copenhagen', 0.123, 'FooProvider', $this->result); $this->assertTrue(is_array($requests = $geocoderLogger->getRequests())); diff --git a/Tests/Mapping/Driver/AnnotationDriverTest.php b/Tests/Mapping/Driver/AnnotationDriverTest.php index 5178b8a5..6407e92f 100644 --- a/Tests/Mapping/Driver/AnnotationDriverTest.php +++ b/Tests/Mapping/Driver/AnnotationDriverTest.php @@ -26,7 +26,7 @@ protected function setUp() { AnnotationRegistry::registerLoader('class_exists'); - $this->reader = new SimpleAnnotationReader; + $this->reader = new SimpleAnnotationReader(); $this->reader->addNamespace('Bazinga\Bundle\GeocoderBundle\Mapping\Annotations'); $this->driver = new AnnotationDriver($this->reader); @@ -47,7 +47,7 @@ public function testLoadMetadata() */ public function testLoadMetadataFromWrongObject() { - $this->driver->loadMetadataFromObject(new Dummy2); + $this->driver->loadMetadataFromObject(new Dummy2()); } public function testIsGeocodable() @@ -78,4 +78,5 @@ class Dummy } class Dummy2 -{} +{ +} diff --git a/Tests/Provider/CacheProviderTest.php b/Tests/Provider/CacheProviderTest.php index 766c271f..c6d7d445 100644 --- a/Tests/Provider/CacheProviderTest.php +++ b/Tests/Provider/CacheProviderTest.php @@ -14,7 +14,7 @@ public function testGetGeocodedData() { $address = 'Paris, France'; $coordinates = array('lat' => 48.857049,'lng' => 2.35223); - $cacheKey = 'geocoder_' . sha1($address); + $cacheKey = 'geocoder_'.sha1($address); $delegate = $this->getMock('Geocoder\\Provider\\ProviderInterface'); $delegate->expects($this->once()) @@ -40,7 +40,7 @@ public function testGetCachedGeocodedData() { $address = 'Paris, France'; $coordinates = array('lat' => 48.857049,'lng' => 2.35223); - $cacheKey = 'geocoder_' . sha1($address); + $cacheKey = 'geocoder_'.sha1($address); $delegate = $this->getMock('Geocoder\\Provider\\ProviderInterface'); $delegate->expects($this->once()) diff --git a/Tests/bootstrap.php b/Tests/bootstrap.php index d21ffec8..e7b54d51 100644 --- a/Tests/bootstrap.php +++ b/Tests/bootstrap.php @@ -1,13 +1,13 @@ add('Doctrine\Tests', __DIR__.'/../vendor/doctrine/orm/tests'); From 7d1b87cd183a63374ff5c4aef6e503b4c279afb8 Mon Sep 17 00:00:00 2001 From: Nicolas Assing Date: Sun, 16 Aug 2015 13:53:39 +0200 Subject: [PATCH 042/235] fix parameters order --- DependencyInjection/BazingaGeocoderExtension.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/DependencyInjection/BazingaGeocoderExtension.php b/DependencyInjection/BazingaGeocoderExtension.php index 1a87fea5..230a3462 100644 --- a/DependencyInjection/BazingaGeocoderExtension.php +++ b/DependencyInjection/BazingaGeocoderExtension.php @@ -198,9 +198,9 @@ public function load(array $configs, ContainerBuilder $container) $openCageParams = $config['providers']['opencage']; $this->addProvider('opencage', array( - $openCageParams['locale'], - $openCageParams['use_ssl'], $openCageParams['api_key'], + $openCageParams['use_ssl'], + $openCageParams['locale'], )); } From 964671a29c372a698f5b6907880eee5db5a7674f Mon Sep 17 00:00:00 2001 From: Nicolas Assing Date: Tue, 18 Aug 2015 19:11:45 +0200 Subject: [PATCH 043/235] Upgrade to Geocoder v3 --- Command/GeocodeCommand.php | 4 +- .../BazingaGeocoderExtension.php | 32 +------ .../Compiler/AddProvidersPass.php | 6 +- DependencyInjection/Configuration.php | 10 +-- DumperManager.php | 8 +- Geocoder/LoggableGeocoder.php | 4 +- Logger/GeocoderLogger.php | 18 ++-- Provider/{CacheProvider.php => Cache.php} | 30 +++---- Resources/config/services.xml | 59 ++++++------- Resources/doc/index.md | 5 -- Tests/Command/GeocodeCommandTest.php | 13 ++- .../BazingaGeocoderExtensionTest.php | 37 ++++---- .../Compiler/AddDumperPassTest.php | 2 +- Tests/DependencyInjection/Fixtures/config.yml | 9 +- Tests/Doctrine/ORM/GeocoderListenerTest.php | 8 +- Tests/DumperManagerTest.php | 8 +- Tests/Logger/GeocoderLoggerTest.php | 84 +++++-------------- Tests/Provider/CacheProviderTest.php | 44 +++++----- composer.json | 2 +- 19 files changed, 146 insertions(+), 237 deletions(-) rename Provider/{CacheProvider.php => Cache.php} (68%) diff --git a/Command/GeocodeCommand.php b/Command/GeocodeCommand.php index e827a4a0..695a26cf 100644 --- a/Command/GeocodeCommand.php +++ b/Command/GeocodeCommand.php @@ -53,8 +53,8 @@ protected function execute(InputInterface $input, OutputInterface $output) $geocoder->using($input->getOption('provider')); } - $result = $geocoder->geocode($input->getArgument('address')); - $data = $result->toArray(); + $results = $geocoder->geocode($input->getArgument('address')); + $data = $results->first()->toArray(); $max = 0; diff --git a/DependencyInjection/BazingaGeocoderExtension.php b/DependencyInjection/BazingaGeocoderExtension.php index 230a3462..e76a1d2e 100644 --- a/DependencyInjection/BazingaGeocoderExtension.php +++ b/DependencyInjection/BazingaGeocoderExtension.php @@ -51,9 +51,7 @@ public function load(array $configs, ContainerBuilder $container) $container->removeDefinition('bazinga_geocoder.event_listener.fake_request'); } - if (isset($config['adapter']['class']) && !empty($config['adapter']['class'])) { - $container->setParameter('bazinga_geocoder.geocoder.adapter.class', $config['adapter']['class']); - } + $container->setAlias('bazinga_geocoder.geocoder.adapter', $config['adapter']); if (isset($config['providers']['free_geo_ip'])) { $this->addProvider('free_geo_ip'); @@ -123,30 +121,6 @@ public function load(array $configs, ContainerBuilder $container) )); } - if (isset($config['providers']['oiorest'])) { - $this->addProvider('oiorest'); - } - - if (isset($config['providers']['geocoder_ca'])) { - $this->addProvider('geocoder_ca'); - } - - if (isset($config['providers']['geocoder_us'])) { - $this->addProvider('geocoder_us'); - } - - if (isset($config['providers']['ign_openls'])) { - $ignOpenlsParams = $config['providers']['ign_openls']; - - $this->addProvider('ign_openls', array( - $ignOpenlsParams['api_key'], - )); - } - - if (isset($config['providers']['data_science_toolkit'])) { - $this->addProvider('data_science_toolkit'); - } - if (isset($config['providers']['yandex'])) { $yandexParams = $config['providers']['yandex']; @@ -239,11 +213,11 @@ public function load(array $configs, ContainerBuilder $container) if (isset($config['providers']['chain']['providers'])) { foreach ($config['providers']['chain']['providers'] as $name) { if ($this->container->hasDefinition('bazinga_geocoder.provider.'.$name)) { - $chainProvider->addMethodCall('addProvider', array( + $chainProvider->addMethodCall('add', array( $this->container->getDefinition('bazinga_geocoder.provider.'.$name), )); } else { - $chainProvider->addMethodCall('addProvider', array(new Reference($name))); + $chainProvider->addMethodCall('add', array(new Reference($name))); } } } diff --git a/DependencyInjection/Compiler/AddProvidersPass.php b/DependencyInjection/Compiler/AddProvidersPass.php index fe697e10..e7cfd64d 100644 --- a/DependencyInjection/Compiler/AddProvidersPass.php +++ b/DependencyInjection/Compiler/AddProvidersPass.php @@ -35,13 +35,13 @@ public function process(ContainerBuilder $container) return; } - $array = array(); + $providers = array(); foreach ($container->findTaggedServiceIds('bazinga_geocoder.provider') as $providerId => $attributes) { - $array[] = new Reference($providerId); + $providers[] = new Reference($providerId); } $geocoderDefinition = $container->getDefinition('bazinga_geocoder.geocoder'); - $geocoderDefinition->addMethodCall('registerProviders', array($array)); + $geocoderDefinition->addMethodCall('registerProviders', array($providers)); if ($container->hasParameter('bazinga_geocoder.default_provider')) { $geocoderDefinition->addMethodCall( diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index ba30c001..c97d5fd7 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -46,11 +46,7 @@ public function getConfigTreeBuilder() ->scalarNode('priority')->defaultValue(0)->end() ->end() ->end() - ->arrayNode('adapter') - ->children() - ->scalarNode('class')->defaultNull()->end() - ->end() - ->end() + ->scalarNode('adapter')->defaultValue('bazinga_geocoder.geocoder.default_adapter')->end() ->arrayNode('providers') ->children() ->arrayNode('bing_maps') @@ -122,9 +118,6 @@ public function getConfigTreeBuilder() ->end() ->end() ->end() - ->arrayNode('oiorest')->end() - ->arrayNode('geocoder_ca')->end() - ->arrayNode('geocoder_us')->end() ->arrayNode('ign_openls') ->children() ->scalarNode('api_key') @@ -132,7 +125,6 @@ public function getConfigTreeBuilder() ->end() ->end() ->end() - ->arrayNode('data_science_toolkit')->end() ->arrayNode('yandex') ->children() ->scalarNode('locale')->defaultNull()->end() diff --git a/DumperManager.php b/DumperManager.php index faf042b0..3ca8d8bb 100644 --- a/DumperManager.php +++ b/DumperManager.php @@ -9,7 +9,7 @@ */ namespace Bazinga\Bundle\GeocoderBundle; -use Geocoder\Dumper\DumperInterface; +use Geocoder\Dumper\Dumper; /** * @author Markus Bachmann @@ -40,7 +40,7 @@ public function __construct(array $dumpers = array()) * * @param string $name The name of the dumper * - * @return DumperInterface + * @return Dumper * * @throws \RuntimeException If no dumper was found */ @@ -57,9 +57,9 @@ public function get($name) * Sets a dumper. * * @param string $name The name - * @param DumperInterface $dumper The dumper instance + * @param Dumper $dumper The dumper instance */ - public function set($name, DumperInterface $dumper) + public function set($name, Dumper $dumper) { $this->dumpers[$name] = $dumper; } diff --git a/Geocoder/LoggableGeocoder.php b/Geocoder/LoggableGeocoder.php index b24ebf3a..00e15352 100644 --- a/Geocoder/LoggableGeocoder.php +++ b/Geocoder/LoggableGeocoder.php @@ -9,10 +9,10 @@ */ namespace Bazinga\Bundle\GeocoderBundle\Geocoder; -use Geocoder\Geocoder; use Bazinga\Bundle\GeocoderBundle\Logger\GeocoderLogger; +use Geocoder\ProviderAggregator; -class LoggableGeocoder extends Geocoder +class LoggableGeocoder extends ProviderAggregator { /** * @var GeocoderLogger diff --git a/Logger/GeocoderLogger.php b/Logger/GeocoderLogger.php index 08d2bcc7..3f89c838 100644 --- a/Logger/GeocoderLogger.php +++ b/Logger/GeocoderLogger.php @@ -9,7 +9,9 @@ */ namespace Bazinga\Bundle\GeocoderBundle\Logger; -use Symfony\Component\HttpKernel\Log\LoggerInterface; +use Psr\Log\LoggerInterface; +use Geocoder\Model\AddressCollection; +use Geocoder\Model\Address; /** * @author Michal Dabrowski @@ -38,9 +40,9 @@ public function __construct(LoggerInterface $logger = null) * @param string $value value to geocode * @param float $duration geocoding duration * @param string $providerClass Geocoder provider class name - * @param \SplObjectStorage|Geocoded $results + * @param AddressCollection $results */ - public function logRequest($value, $duration, $providerClass, $results) + public function logRequest($value, $duration, $providerClass, AddressCollection $results) { if (null !== $this->logger) { $this->logger->info(sprintf('%s %0.2f ms (%s)', $value, $duration, $providerClass)); @@ -48,13 +50,9 @@ public function logRequest($value, $duration, $providerClass, $results) $data = array(); - if ($results instanceof \SplObjectStorage) { - $data = array(); - foreach ($results as $result) { - $data[] = $result->toArray(); - } - } else { - $data = $results->toArray(); + /** @var Address $result */ + foreach ($results as $result) { + $data[] = $result->toArray(); } $this->requests[] = array( diff --git a/Provider/CacheProvider.php b/Provider/Cache.php similarity index 68% rename from Provider/CacheProvider.php rename to Provider/Cache.php index 76046a4b..beb1228e 100644 --- a/Provider/CacheProvider.php +++ b/Provider/Cache.php @@ -9,14 +9,14 @@ */ namespace Bazinga\Bundle\GeocoderBundle\Provider; -use Geocoder\Geocoder; -use Geocoder\Provider\ProviderInterface; -use Doctrine\Common\Cache\Cache; +use Doctrine\Common\Cache\Cache as DoctrineCache; +use Geocoder\Provider\AbstractProvider; +use Geocoder\Provider\Provider; /** * @author Markus Bachmann */ -class CacheProvider implements ProviderInterface +class Cache extends AbstractProvider implements Provider { /** * @var Cache @@ -24,7 +24,7 @@ class CacheProvider implements ProviderInterface private $cache; /** - * @var ProviderInterface + * @var Provider */ private $provider; @@ -41,18 +41,20 @@ class CacheProvider implements ProviderInterface /** * @var int */ - private $maxResults = Geocoder::MAX_RESULTS; + private $maxResults = Provider::MAX_RESULTS; /** * Constructor. * - * @param Cache $cache The cache interface - * @param ProviderInterface $provider The fallback provider + * @param DoctrineCache $cache The cache interface + * @param Provider $provider The fallback provider * @param int $lifetime The cache lifetime * @param string $locale */ - public function __construct(Cache $cache, ProviderInterface $provider, $lifetime = 0, $locale = null) + public function __construct(DoctrineCache $cache, Provider $provider, $lifetime = 0, $locale = null) { + parent::__construct(); + $this->cache = $cache; $this->provider = $provider; $this->lifetime = $lifetime; @@ -62,7 +64,7 @@ public function __construct(Cache $cache, ProviderInterface $provider, $lifetime /** * {@inheritdoc} */ - public function getGeocodedData($address) + public function geocode($address) { $key = 'geocoder_'.sha1($this->locale.$address); @@ -70,7 +72,7 @@ public function getGeocodedData($address) return unserialize($data); } - $data = $this->provider->getGeocodedData($address); + $data = $this->provider->geocode($address); $this->cache->save($key, serialize($data), $this->lifetime); return $data; @@ -79,15 +81,15 @@ public function getGeocodedData($address) /** * {@inheritdoc} */ - public function getReversedData(array $coordinates) + public function reverse($latitude, $longitude) { - $key = 'geocoder_'.sha1($this->locale.json_encode($coordinates)); + $key = 'geocoder_'.sha1($this->locale.$latitude.$longitude); if (false !== $data = $this->cache->fetch($key)) { return unserialize($data); } - $data = $this->provider->getReversedData($coordinates); + $data = $this->provider->reverse($latitude, $longitude); $this->cache->save($key, serialize($data), $this->lifetime); return $data; diff --git a/Resources/config/services.xml b/Resources/config/services.xml index c3f9cb5e..f7171801 100644 --- a/Resources/config/services.xml +++ b/Resources/config/services.xml @@ -4,33 +4,28 @@ xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> - Geocoder\Geocoder + Geocoder\ProviderAggregator Bazinga\Bundle\GeocoderBundle\Geocoder\LoggableGeocoder - Geocoder\HttpAdapter\CurlHttpAdapter - Geocoder\Provider\BingMapsProvider - Geocoder\Provider\FreeGeoIpProvider - Geocoder\Provider\GoogleMapsProvider - Geocoder\Provider\GoogleMapsBusinessProvider - Geocoder\Provider\HostIpProvider - Geocoder\Provider\IpInfoDbProvider - Geocoder\Provider\YahooProvider - Geocoder\Provider\OpenStreetMapProvider - Geocoder\Provider\GeoipProvider - Geocoder\Provider\MapQuestProvider - Geocoder\Provider\OIORestProvider - Geocoder\Provider\GeocoderCaProvider - Geocoder\Provider\GeocoderUsProvider - Geocoder\Provider\IGNOpenLSProvider - Geocoder\Provider\DataScienceToolkitProvider - Geocoder\Provider\YandexProvider - Geocoder\Provider\GeoIPsProvider - Geocoder\Provider\GeoPluginProvider - Geocoder\Provider\MaxMindProvider - Geocoder\Provider\MaxMindBinaryProvider - Geocoder\Provider\OpenCageProvider - Bazinga\Bundle\GeocoderBundle\Provider\CacheProvider - Geocoder\Provider\ChainProvider - Geocoder\Provider\TomTomProvider + Ivory\HttpAdapter\CurlHttpAdapter + Geocoder\Provider\BingMaps + Geocoder\Provider\FreeGeoIp + Geocoder\Provider\GoogleMaps + Geocoder\Provider\GoogleMapsBusiness + Geocoder\Provider\HostIp + Geocoder\Provider\IpInfoDb + Geocoder\Provider\Yahoo + Geocoder\Provider\OpenStreetMap + Geocoder\Provider\Geoip + Geocoder\Provider\MapQuest + Geocoder\Provider\Yandex + Geocoder\Provider\GeoIPs + Geocoder\Provider\GeoPlugin + Geocoder\Provider\MaxMind + Geocoder\Provider\MaxMindBinary + Geocoder\Provider\OpenCage + Bazinga\Bundle\GeocoderBundle\Provider\Cache + Geocoder\Provider\Chain + Geocoder\Provider\TomTom Bazinga\Bundle\GeocoderBundle\Logger\GeocoderLogger @@ -40,11 +35,11 @@ Bazinga\Bundle\GeocoderBundle\EventListener\FakeRequestListener Bazinga\Bundle\GeocoderBundle\DumperManager - Geocoder\Dumper\GeoJsonDumper - Geocoder\Dumper\GpxDumper - Geocoder\Dumper\KmlDumper - Geocoder\Dumper\WkbDumper - Geocoder\Dumper\WktDumper + Geocoder\Dumper\GeoJson + Geocoder\Dumper\Gpx + Geocoder\Dumper\Kml + Geocoder\Dumper\Wkb + Geocoder\Dumper\Wkt @@ -52,7 +47,7 @@ - + diff --git a/Resources/doc/index.md b/Resources/doc/index.md index cb033543..402eea7b 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -276,11 +276,6 @@ bazinga_geocoder: free_geo_ip: [] mapquest: api_key: ~ # Required - oiorest: [] - geocoder_ca: [] - geocoder_us: [] - ign_openls: - api_key: ~ # Required data_science_toolkit: [] yandex: locale: null diff --git a/Tests/Command/GeocodeCommandTest.php b/Tests/Command/GeocodeCommandTest.php index dcd8876a..122802c9 100644 --- a/Tests/Command/GeocodeCommandTest.php +++ b/Tests/Command/GeocodeCommandTest.php @@ -10,6 +10,11 @@ namespace Bazinga\Bundle\GeocoderBundle\Tests\Command; use Bazinga\Bundle\GeocoderBundle\Command\GeocodeCommand; +use Geocoder\Model\Address; +use Geocoder\Model\AddressCollection; +use Geocoder\Model\Bounds; +use Geocoder\Model\Coordinates; +use Geocoder\Model\Country; use Geocoder\Result\Geocoded; use Symfony\Bundle\FrameworkBundle\Console\Application; use Symfony\Component\Console\Tester\CommandTester; @@ -23,12 +28,16 @@ class GeocodeCommandTest extends \PHPUnit_Framework_TestCase public function testExecute() { - $geocoder = $this->getMock('Geocoder\\Geocoder'); + $coordinates = new Coordinates(1, 2); + $bounds = new Bounds(1, 2, 3, 4); + $country = new Country('France', 'FR'); + $address = new Address($coordinates, $bounds, '10', 'rue Gambetta', '75020', 'Paris', null, null, $country); + $geocoder = $this->getMock('Geocoder\\ProviderAggregator'); $geocoder->expects($this->once()) ->method('geocode') ->with(self::$address) - ->will($this->returnValue(new Geocoded())); + ->will($this->returnValue(new AddressCollection(array($address)))); $container = $this->getMock('Symfony\\Component\\DependencyInjection\\Container'); $container->expects($this->once()) diff --git a/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php b/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php index 4e098d24..687d3a7c 100644 --- a/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php +++ b/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php @@ -53,27 +53,22 @@ public function testLoad() $geocoder = $container->get('bazinga_geocoder.geocoder'); $providers = $geocoder->getProviders(); foreach (array( - 'bing_maps' => 'Geocoder\\Provider\\BingMapsProvider', - 'cache' => 'Bazinga\\Bundle\\GeocoderBundle\\Provider\\CacheProvider', - 'ip_info_db' => 'Geocoder\\Provider\\IpInfoDbProvider', - 'google_maps' => 'Geocoder\\Provider\\GoogleMapsProvider', - 'google_maps_business' => 'Geocoder\\Provider\\GoogleMapsBusinessProvider', - 'openstreetmap' => 'Geocoder\\Provider\\OpenStreetMapProvider', - 'host_ip' => 'Geocoder\\Provider\\HostIpProvider', - 'free_geo_ip' => 'Geocoder\\Provider\\FreeGeoIpProvider', - 'map_quest' => 'Geocoder\\Provider\\MapQuestProvider', - 'oio_rest' => 'Geocoder\\Provider\\OIORestProvider', - 'geocoder_ca' => 'Geocoder\\Provider\\GeocoderCaProvider', - 'geocoder_us' => 'Geocoder\\Provider\\GeocoderUsProvider', - 'ign_openls' => 'Geocoder\\Provider\\IGNOpenLSProvider', - 'data_science_toolkit' => 'Geocoder\\Provider\\DataScienceToolkitProvider', - 'yandex' => 'Geocoder\\Provider\\YandexProvider', - 'geo_ips' => 'Geocoder\\Provider\\GeoIpsProvider', - 'geo_plugin' => 'Geocoder\\Provider\\GeoPluginProvider', - 'maxmind' => 'Geocoder\\Provider\\MaxmindProvider', - 'chain' => 'Geocoder\\Provider\\ChainProvider', - 'maxmind_binary' => 'Geocoder\\Provider\\MaxmindBinaryProvider', - 'opencage' => 'Geocoder\\Provider\\OpenCageProvider', + 'bing_maps' => 'Geocoder\\Provider\\BingMaps', + 'cache' => 'Bazinga\\Bundle\\GeocoderBundle\\Provider\\Cache', + 'ip_info_db' => 'Geocoder\\Provider\\IpInfoDb', + 'google_maps' => 'Geocoder\\Provider\\GoogleMaps', + 'google_maps_business' => 'Geocoder\\Provider\\GoogleMapsBusiness', + 'openstreetmap' => 'Geocoder\\Provider\\OpenStreetMap', + 'host_ip' => 'Geocoder\\Provider\\HostIp', + 'free_geo_ip' => 'Geocoder\\Provider\\FreeGeoIp', + 'map_quest' => 'Geocoder\\Provider\\MapQuest', + 'yandex' => 'Geocoder\\Provider\\Yandex', + 'geo_ips' => 'Geocoder\\Provider\\GeoIps', + 'geo_plugin' => 'Geocoder\\Provider\\GeoPlugin', + 'maxmind' => 'Geocoder\\Provider\\Maxmind', + 'chain' => 'Geocoder\\Provider\\Chain', + 'maxmind_binary' => 'Geocoder\\Provider\\MaxmindBinary', + 'opencage' => 'Geocoder\\Provider\\OpenCage', ) as $name => $class) { $this->assertInstanceOf($class, $providers[$name], sprintf('-> Assert that %s is instance of %s', $name, $class)); } diff --git a/Tests/DependencyInjection/Compiler/AddDumperPassTest.php b/Tests/DependencyInjection/Compiler/AddDumperPassTest.php index 25a7a7dc..99c1175c 100644 --- a/Tests/DependencyInjection/Compiler/AddDumperPassTest.php +++ b/Tests/DependencyInjection/Compiler/AddDumperPassTest.php @@ -16,7 +16,7 @@ public function testProcess() $builder = new ContainerBuilder(); $builder->setDefinition('bazinga_geocoder.dumper_manager', new Definition('Bazinga\Bundle\GeocoderBundle\DumperManager')); - $dumper = new Definition('Geocoder\Dumper\GeoJsonDumper'); + $dumper = new Definition('Geocoder\Dumper\GeoJson'); $dumper->addTag('bazinga_geocoder.dumper', array('alias' => 'geojson')); $builder->setDefinition('bazinga_geocoder.dumper.geojson', $dumper); diff --git a/Tests/DependencyInjection/Fixtures/config.yml b/Tests/DependencyInjection/Fixtures/config.yml index aa1896b6..5635e095 100644 --- a/Tests/DependencyInjection/Fixtures/config.yml +++ b/Tests/DependencyInjection/Fixtures/config.yml @@ -3,8 +3,7 @@ bazinga_geocoder: fake_ip: ip: 33.33.33.11 priority: 128 - adapter: - class: Geocoder\HttpAdapter\CurlHttpAdapter + adapter: bazinga_geocoder.geocoder.default_adapter providers: bing_maps: api_key: 123 @@ -32,12 +31,6 @@ bazinga_geocoder: free_geo_ip: ~ mapquest: api_key: 123 - oiorest: ~ - geocoder_ca: ~ - geocoder_us: ~ - ign_openls: - api_key: 123 - data_science_toolkit: ~ yandex: locale: en-US toponym: locality diff --git a/Tests/Doctrine/ORM/GeocoderListenerTest.php b/Tests/Doctrine/ORM/GeocoderListenerTest.php index 2a0cfb3f..1fdab420 100644 --- a/Tests/Doctrine/ORM/GeocoderListenerTest.php +++ b/Tests/Doctrine/ORM/GeocoderListenerTest.php @@ -10,9 +10,8 @@ use Doctrine\ORM\EntityManager; use Doctrine\ORM\Tools\SchemaTool; use Doctrine\Tests\OrmTestCase; -use Geocoder\Geocoder; -use Geocoder\HttpAdapter\CurlHttpAdapter; -use Geocoder\Provider\GoogleMapsProvider; +use Ivory\HttpAdapter\CurlHttpAdapter; +use Geocoder\Provider\GoogleMaps; /** * @author Markus Bachmann @@ -41,8 +40,7 @@ protected function setUp() $driver = new AnnotationDriver($reader); - $geocoder = new Geocoder(); - $geocoder->registerProvider(new GoogleMapsProvider(new CurlHttpAdapter())); + $geocoder = new GoogleMaps(new CurlHttpAdapter()); $this->listener = new GeocoderListener($geocoder, $driver); diff --git a/Tests/DumperManagerTest.php b/Tests/DumperManagerTest.php index 97a63bc6..454952d1 100644 --- a/Tests/DumperManagerTest.php +++ b/Tests/DumperManagerTest.php @@ -21,12 +21,12 @@ protected function setup() public function testSet() { - $this->assertNull($this->manager->set('test', $this->getMock('Geocoder\\Dumper\\DumperInterface'))); + $this->assertNull($this->manager->set('test', $this->getMock('Geocoder\\Dumper\\Dumper'))); } public function testGet() { - $dumper = $this->getMock('Geocoder\\Dumper\\DumperInterface'); + $dumper = $this->getMock('Geocoder\\Dumper\\Dumper'); $this->manager->set('test', $dumper); $this->assertEquals($dumper, $this->manager->get('test')); @@ -43,13 +43,13 @@ public function testGetNotExistDumper() public function testHas() { $this->assertFalse($this->manager->has('test')); - $this->manager->set('test', $this->getMock('Geocoder\\Dumper\\DumperInterface')); + $this->manager->set('test', $this->getMock('Geocoder\\Dumper\\Dumper')); $this->assertTrue($this->manager->has('test')); } public function testRemove() { - $this->manager->set('test', $this->getMock('Geocoder\\Dumper\\DumperInterface')); + $this->manager->set('test', $this->getMock('Geocoder\\Dumper\\Dumper')); $this->manager->remove('test'); $this->assertFalse($this->manager->has('test')); } diff --git a/Tests/Logger/GeocoderLoggerTest.php b/Tests/Logger/GeocoderLoggerTest.php index 9ebc42ff..b300789b 100644 --- a/Tests/Logger/GeocoderLoggerTest.php +++ b/Tests/Logger/GeocoderLoggerTest.php @@ -10,7 +10,11 @@ namespace Bazinga\Bundle\GeocoderBundle\Tests\Logger; use Bazinga\Bundle\GeocoderBundle\Logger\GeocoderLogger; -use Geocoder\Result\Geocoded; +use Geocoder\Model\Address; +use Geocoder\Model\AddressCollection; +use Geocoder\Model\Bounds; +use Geocoder\Model\Coordinates; +use Geocoder\Model\Country; /** * @author Antoine Corcy @@ -23,7 +27,7 @@ class GeocoderLoggerTest extends \PHPUnit_Framework_TestCase public function setUp() { - $logger = $this->getMock('Symfony\\Component\\HttpKernel\\Log\\LoggerInterface'); + $logger = $this->getMock('Psr\\Log\\LoggerInterface'); $logger ->expects($this->any()) ->method('info') @@ -32,42 +36,22 @@ public function setUp() $this->geocoderLogger = new GeocoderLogger($logger); - $this->result = new Geocoded(); - $this->result->fromArray(array( - 'latitude' => 1, - 'longitude' => 2, - )); + $coordinates = new Coordinates(1, 2); + $bounds = new Bounds(1, 2, 3, 4); + $country = new Country('France', 'FR'); + $this->result = new Address($coordinates, $bounds, '10', 'rue Gambetta', '75020', 'Paris', null, null, $country); - $this->results = new \SplObjectStorage(); - $this->results->attach($this->result); + $coordinates = new Coordinates(3, 4); + $bounds = new Bounds(5, 6, 7, 8); + $country = new Country('France', 'FR'); + $otherResult = new Address($coordinates, $bounds, '3', 'avenue Secrétan', '75019', 'Paris', null, null, $country); - $otherResult = new Geocoded(); - $otherResult->fromArray(array( - 'latitude' => 3, - 'longitude' => 4, - )); - - $this->results->attach($otherResult); - } - - public function testLogNoResult() - { - $this->geocoderLogger->logRequest('copenhagen', 0.123, 'FooProvider', new Geocoded()); - - $requests = $this->geocoderLogger->getRequests(); - - $this->assertTrue(is_array($requests = $this->geocoderLogger->getRequests())); - $this->assertCount(1, $requests); - $this->assertTrue(is_array($request = $requests[0])); - $this->assertSame($request['value'], 'copenhagen'); - $this->assertSame($request['duration'], 0.123); - $this->assertSame($request['providerClass'], 'FooProvider'); - $this->assertSame($request['result'], '{"latitude":0,"longitude":0,"bounds":null,"streetNumber":null,"streetName":null,"zipcode":null,"city":null,"cityDistrict":null,"county":null,"countyCode":null,"region":null,"regionCode":null,"country":null,"countryCode":null,"timezone":null}'); + $this->results = new AddressCollection(array($this->result, $otherResult)); } public function testLogNoResults() { - $this->geocoderLogger->logRequest('copenhagen', 0.123, 'FooProvider', new \SplObjectStorage()); + $this->geocoderLogger->logRequest('copenhagen', 0.123, 'FooProvider', new AddressCollection()); $this->assertTrue(is_array($requests = $this->geocoderLogger->getRequests())); $this->assertCount(1, $requests); @@ -78,33 +62,7 @@ public function testLogNoResults() $this->assertSame($request['result'], '[]'); } - public function testLogSingleResult() - { - $this->geocoderLogger->logRequest('copenhagen', 0.123, 'FooProvider', $this->result); - - $this->assertTrue(is_array($requests = $this->geocoderLogger->getRequests())); - $this->assertCount(1, $requests); - $this->assertTrue(is_array($request = $requests[0])); - $this->assertSame($request['value'], 'copenhagen'); - $this->assertSame($request['duration'], 0.123); - $this->assertSame($request['providerClass'], 'FooProvider'); - $this->assertSame($request['result'], '{"latitude":1,"longitude":2,"bounds":null,"streetNumber":null,"streetName":null,"zipcode":null,"city":null,"cityDistrict":null,"county":null,"countyCode":null,"region":null,"regionCode":null,"country":null,"countryCode":null,"timezone":null}'); - } - - public function testLog2RequestsWithSingleResult() - { - $this->geocoderLogger->logRequest('copenhagen', 0.123, 'FooProvider', $this->result); - $this->geocoderLogger->logRequest('paris', 0.456, 'BarProvider', $this->result); - - $this->assertTrue(is_array($requests = $this->geocoderLogger->getRequests())); - $this->assertCount(2, $requests); - $this->assertTrue(is_array($request = $requests[0])); - $this->assertSame($request['value'], 'copenhagen'); - $this->assertTrue(is_array($request = $requests[1])); - $this->assertSame($request['value'], 'paris'); - } - - public function testLogMultipleResults() + public function testLogResults() { $this->geocoderLogger->logRequest('copenhagen', 0.123, 'FooProvider', $this->results); @@ -114,11 +72,11 @@ public function testLogMultipleResults() $this->assertSame($request['value'], 'copenhagen'); $this->assertSame($request['duration'], 0.123); $this->assertSame($request['providerClass'], 'FooProvider'); - $this->assertSame($request['result'], '[{"latitude":1,"longitude":2,"bounds":null,"streetNumber":null,"streetName":null,"zipcode":null,"city":null,"cityDistrict":null,"county":null,"countyCode":null,"region":null,"regionCode":null,"country":null,"countryCode":null,"timezone":null},{"latitude":3,"longitude":4,"bounds":null,"streetNumber":null,"streetName":null,"zipcode":null,"city":null,"cityDistrict":null,"county":null,"countyCode":null,"region":null,"regionCode":null,"country":null,"countryCode":null,"timezone":null}]'); + $this->assertSame($request['result'], '[{"latitude":1,"longitude":2,"bounds":{"south":1,"west":2,"north":3,"east":4},"streetNumber":"10","streetName":"rue Gambetta","postalCode":"75020","locality":"Paris","subLocality":null,"adminLevels":[],"country":"France","countryCode":"FR","timezone":null},{"latitude":3,"longitude":4,"bounds":{"south":5,"west":6,"north":7,"east":8},"streetNumber":"3","streetName":"avenue Secr\u00e9tan","postalCode":"75019","locality":"Paris","subLocality":null,"adminLevels":[],"country":"France","countryCode":"FR","timezone":null}]'); $this->assertCount(2, json_decode($request['result'])); } - public function testLog2RequetsWithMultipleResults() + public function testLog2RequestWithMultipleResults() { $this->geocoderLogger->logRequest('copenhagen', 0.123, 'FooProvider', $this->results); $this->geocoderLogger->logRequest('paris', 0.456, 'BarProvider', $this->results); @@ -138,7 +96,7 @@ public function testLog2RequetsWithMultipleResults() public function testLogRequestsWithoutLogger() { $geocoderLogger = new GeocoderLogger(); - $geocoderLogger->logRequest('copenhagen', 0.123, 'FooProvider', $this->result); + $geocoderLogger->logRequest('copenhagen', 0.123, 'FooProvider', $this->results); $this->assertTrue(is_array($requests = $geocoderLogger->getRequests())); $this->assertCount(1, $requests); @@ -146,6 +104,6 @@ public function testLogRequestsWithoutLogger() $this->assertSame($request['value'], 'copenhagen'); $this->assertSame($request['duration'], 0.123); $this->assertSame($request['providerClass'], 'FooProvider'); - $this->assertSame($request['result'], '{"latitude":1,"longitude":2,"bounds":null,"streetNumber":null,"streetName":null,"zipcode":null,"city":null,"cityDistrict":null,"county":null,"countyCode":null,"region":null,"regionCode":null,"country":null,"countryCode":null,"timezone":null}'); + $this->assertSame($request['result'], '[{"latitude":1,"longitude":2,"bounds":{"south":1,"west":2,"north":3,"east":4},"streetNumber":"10","streetName":"rue Gambetta","postalCode":"75020","locality":"Paris","subLocality":null,"adminLevels":[],"country":"France","countryCode":"FR","timezone":null},{"latitude":3,"longitude":4,"bounds":{"south":5,"west":6,"north":7,"east":8},"streetNumber":"3","streetName":"avenue Secr\u00e9tan","postalCode":"75019","locality":"Paris","subLocality":null,"adminLevels":[],"country":"France","countryCode":"FR","timezone":null}]'); } } diff --git a/Tests/Provider/CacheProviderTest.php b/Tests/Provider/CacheProviderTest.php index c6d7d445..993e17af 100644 --- a/Tests/Provider/CacheProviderTest.php +++ b/Tests/Provider/CacheProviderTest.php @@ -2,7 +2,7 @@ namespace Bazinga\Bundle\GeocoderBundle\Tests\Provider; -use Bazinga\Bundle\GeocoderBundle\Provider\CacheProvider; +use Bazinga\Bundle\GeocoderBundle\Provider\Cache; use Doctrine\Common\Cache\ArrayCache; /** @@ -10,15 +10,15 @@ */ class CacheProviderTest extends \PHPUnit_Framework_TestCase { - public function testGetGeocodedData() + public function testGeocode() { $address = 'Paris, France'; $coordinates = array('lat' => 48.857049,'lng' => 2.35223); $cacheKey = 'geocoder_'.sha1($address); - $delegate = $this->getMock('Geocoder\\Provider\\ProviderInterface'); + $delegate = $this->getMock('Geocoder\\Provider\\Provider'); $delegate->expects($this->once()) - ->method('getGeocodedData') + ->method('geocode') ->with($address) ->will($this->returnValue($coordinates)); @@ -32,54 +32,54 @@ public function testGetGeocodedData() ->method('save') ->with($cacheKey, serialize($coordinates), 0); - $provider = new CacheProvider($cache, $delegate); - $this->assertEquals($coordinates, $provider->getGeocodedData($address)); + $provider = new Cache($cache, $delegate); + $this->assertEquals($coordinates, $provider->geocode($address)); } - public function testGetCachedGeocodedData() + public function testCachedGeocode() { $address = 'Paris, France'; $coordinates = array('lat' => 48.857049,'lng' => 2.35223); $cacheKey = 'geocoder_'.sha1($address); - $delegate = $this->getMock('Geocoder\\Provider\\ProviderInterface'); + $delegate = $this->getMock('Geocoder\\Provider\\Provider'); $delegate->expects($this->once()) - ->method('getGeocodedData') + ->method('geocode') ->with($address) ->will($this->returnValue($coordinates)); - $provider = new CacheProvider($cache = new ArrayCache(), $delegate); + $provider = new Cache($cache = new ArrayCache(), $delegate); - $provider->getGeocodedData($address); - $provider->getGeocodedData($address); + $provider->geocode($address); + $provider->geocode($address); $this->assertTrue($cache->contains($cacheKey)); } - public function testGetReversedData() + public function testReverse() { - $coordinates = array(48.857049, 2.35223); + $coordinates = array('lat' => 48.857049, 'lon' => 2.35223); - $delegate = $this->getMock('Geocoder\\Provider\\ProviderInterface'); + $delegate = $this->getMock('Geocoder\\Provider\\Provider'); $delegate->expects($this->once()) - ->method('getReversedData') - ->with($coordinates) + ->method('reverse') + ->with($coordinates['lat'], $coordinates['lon']) ->will($this->returnValue('Paris, France')); $cache = new ArrayCache(); - $provider = new CacheProvider($cache, $delegate); + $provider = new Cache($cache, $delegate); - $this->assertEquals('Paris, France', $provider->getReversedData($coordinates)); - $this->assertEquals('Paris, France', $provider->getReversedData($coordinates)); + $this->assertEquals('Paris, France', $provider->reverse($coordinates['lat'], $coordinates['lon'])); + $this->assertEquals('Paris, France', $provider->reverse($coordinates['lat'], $coordinates['lon'])); } public function testGetName() { - $delegate = $this->getMock('Geocoder\\Provider\\ProviderInterface'); + $delegate = $this->getMock('Geocoder\\Provider\\Provider'); $cache = $this->getMock('Doctrine\\Common\\Cache\\Cache'); - $provider = new CacheProvider($cache, $delegate); + $provider = new Cache($cache, $delegate); $this->assertEquals('cache', $provider->getName()); } diff --git a/composer.json b/composer.json index 5a2a283b..9ca71623 100644 --- a/composer.json +++ b/composer.json @@ -12,7 +12,7 @@ ], "require": { "symfony/framework-bundle": "~2.1", - "willdurand/geocoder": "~2.5", + "willdurand/geocoder": "~3.0", "symfony/console": "~2.1" }, "require-dev": { From 0825933405edd01cc2f98c034a184252e09c0efa Mon Sep 17 00:00:00 2001 From: Nicolas Assing Date: Tue, 18 Aug 2015 19:11:45 +0200 Subject: [PATCH 044/235] Upgrade to Geocoder v3 --- Doctrine/ORM/GeocoderListener.php | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/Doctrine/ORM/GeocoderListener.php b/Doctrine/ORM/GeocoderListener.php index 2172c5a7..06725513 100644 --- a/Doctrine/ORM/GeocoderListener.php +++ b/Doctrine/ORM/GeocoderListener.php @@ -69,9 +69,12 @@ private function geocodeEntity($entity) { $metadata = $this->driver->loadMetadataFromObject($entity); $address = $metadata->addressProperty->getValue($entity); - $result = $this->geocoder->geocode($address); + $results = $this->geocoder->geocode($address); - $metadata->latitudeProperty->setValue($entity, $result['latitude']); - $metadata->longitudeProperty->setValue($entity, $result['longitude']); + if (!empty($results)) { + $result = $results->first(); + $metadata->latitudeProperty->setValue($entity, $results->first()->getLatitude()); + $metadata->longitudeProperty->setValue($entity, $results->first()->getLongitude()); + } } } From 4c704d14ae1df93656704c238e3ee97e30ba36bc Mon Sep 17 00:00:00 2001 From: Nicolas Assing Date: Tue, 18 Aug 2015 19:29:29 +0200 Subject: [PATCH 045/235] CS --- DumperManager.php | 4 ++-- Logger/GeocoderLogger.php | 8 ++++---- Provider/Cache.php | 8 ++++---- Tests/Command/GeocodeCommandTest.php | 1 - 4 files changed, 10 insertions(+), 11 deletions(-) diff --git a/DumperManager.php b/DumperManager.php index 3ca8d8bb..8f2ac9ce 100644 --- a/DumperManager.php +++ b/DumperManager.php @@ -56,8 +56,8 @@ public function get($name) /** * Sets a dumper. * - * @param string $name The name - * @param Dumper $dumper The dumper instance + * @param string $name The name + * @param Dumper $dumper The dumper instance */ public function set($name, Dumper $dumper) { diff --git a/Logger/GeocoderLogger.php b/Logger/GeocoderLogger.php index 3f89c838..350b652f 100644 --- a/Logger/GeocoderLogger.php +++ b/Logger/GeocoderLogger.php @@ -37,10 +37,10 @@ public function __construct(LoggerInterface $logger = null) } /** - * @param string $value value to geocode - * @param float $duration geocoding duration - * @param string $providerClass Geocoder provider class name - * @param AddressCollection $results + * @param string $value value to geocode + * @param float $duration geocoding duration + * @param string $providerClass Geocoder provider class name + * @param AddressCollection $results */ public function logRequest($value, $duration, $providerClass, AddressCollection $results) { diff --git a/Provider/Cache.php b/Provider/Cache.php index beb1228e..659d25eb 100644 --- a/Provider/Cache.php +++ b/Provider/Cache.php @@ -46,10 +46,10 @@ class Cache extends AbstractProvider implements Provider /** * Constructor. * - * @param DoctrineCache $cache The cache interface - * @param Provider $provider The fallback provider - * @param int $lifetime The cache lifetime - * @param string $locale + * @param DoctrineCache $cache The cache interface + * @param Provider $provider The fallback provider + * @param int $lifetime The cache lifetime + * @param string $locale */ public function __construct(DoctrineCache $cache, Provider $provider, $lifetime = 0, $locale = null) { diff --git a/Tests/Command/GeocodeCommandTest.php b/Tests/Command/GeocodeCommandTest.php index 122802c9..b205abb9 100644 --- a/Tests/Command/GeocodeCommandTest.php +++ b/Tests/Command/GeocodeCommandTest.php @@ -15,7 +15,6 @@ use Geocoder\Model\Bounds; use Geocoder\Model\Coordinates; use Geocoder\Model\Country; -use Geocoder\Result\Geocoded; use Symfony\Bundle\FrameworkBundle\Console\Application; use Symfony\Component\Console\Tester\CommandTester; From 023ce611f093189b6733e04394928c365613758d Mon Sep 17 00:00:00 2001 From: Nicolas Assing Date: Wed, 19 Aug 2015 10:26:29 +0200 Subject: [PATCH 046/235] fix php minimum version --- .travis.yml | 1 - composer.json | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 1519fa81..7d2651b0 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,6 @@ language: php php: - - 5.3 - 5.4 - 5.5 diff --git a/composer.json b/composer.json index 9ca71623..6310aed5 100644 --- a/composer.json +++ b/composer.json @@ -16,6 +16,7 @@ "symfony/console": "~2.1" }, "require-dev": { + "php": ">=5.4", "symfony/yaml": "~2.1", "maxromanovsky/php-maxmind-geoip": "~1.12", "doctrine/cache": "~1.3", From 4d23b5c8bb03c3f421f4bc9f2866c7593b558a9d Mon Sep 17 00:00:00 2001 From: Nicolas Assing Date: Wed, 19 Aug 2015 11:20:16 +0200 Subject: [PATCH 047/235] fix symfony version --- .travis.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 7d2651b0..d6bb34d0 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,7 +5,6 @@ php: - 5.5 env: - - SYMFONY_VERSION=2.1.* - SYMFONY_VERSION=2.2.* - SYMFONY_VERSION=2.3.* - SYMFONY_VERSION=2.4.* From 77ca5c21219018df7401a77d072f8d061004cef8 Mon Sep 17 00:00:00 2001 From: Nicolas Assing Date: Sun, 23 Aug 2015 14:23:42 +0200 Subject: [PATCH 048/235] add documentation for http adapters --- Resources/doc/index.md | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 402eea7b..1f3204f4 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -218,6 +218,22 @@ bazinga_geocoder: > **Tip:** If you want to configure the cache adapter, > we recommend the [doctrine/doctrine-cache-bundle](https://github.com/doctrine/DoctrineCacheBundle). +### Custom HTTP Adapter + +Geocoder Bundle integrates with [egeloen/http-adapter] (https://github.com/egeloen/ivory-http-adapter). By default the bundle use a simple cURL Adapter. +You can use any [PSR-7] (http://www.php-fig.org/psr/psr-7/) compliant adapter. + +An example, if you want to use Guzzle. + +```yaml +# app/config/config*.yml +services: + guzzle_http_adapter: + class: "Ivory\HttpAdapter\Guzzle6HttpAdapter" + +bazinga_geocoder: + adapter: guzzle_http_adapter +``` ### Symfony2 Profiler Integration @@ -244,8 +260,7 @@ bazinga_geocoder: enabled: true ip: null priority: 0 - adapter: - class: null + adapter: ~ # An adapter service id default_provider: ~ # Name of provider, e.g. chain providers: bing_maps: From 624b40e8c7d5b150846e1311f4e235eace79bae9 Mon Sep 17 00:00:00 2001 From: William Durand Date: Wed, 28 Oct 2015 09:39:21 +0100 Subject: [PATCH 049/235] Prepare v4.0.0 release --- .travis.yml | 5 +++-- composer.json | 8 ++++---- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/.travis.yml b/.travis.yml index d6bb34d0..0af2bdad 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,11 +3,12 @@ language: php php: - 5.4 - 5.5 + - 5.6 env: - - SYMFONY_VERSION=2.2.* - SYMFONY_VERSION=2.3.* - - SYMFONY_VERSION=2.4.* + - SYMFONY_VERSION=2.5.* + - SYMFONY_VERSION=2.7.* - SYMFONY_VERSION=dev-master matrix: diff --git a/composer.json b/composer.json index 6310aed5..d1dea662 100644 --- a/composer.json +++ b/composer.json @@ -1,18 +1,18 @@ { "name": "willdurand/geocoder-bundle", - "description": "Integration of Geocoder into Symfony2", + "description": "Integration of Geocoder into Symfony", "keywords": ["geocoding", "geocoder"], "type": "symfony-bundle", "license": "MIT", "authors": [ { "name": "William Durand", - "email": "william.durand1@gmail.com" + "email": "will+git@drnd.me" } ], "require": { "symfony/framework-bundle": "~2.1", - "willdurand/geocoder": "~3.0", + "willdurand/geocoder": "~3.1", "symfony/console": "~2.1" }, "require-dev": { @@ -28,7 +28,7 @@ "target-dir": "Bazinga/Bundle/GeocoderBundle", "extra": { "branch-alias": { - "dev-master": "3.1-dev" + "dev-master": "4.0-dev" } } } From 5352aed2525ee869a98e5aa70fcf237d87293581 Mon Sep 17 00:00:00 2001 From: William Durand Date: Wed, 28 Oct 2015 09:45:32 +0100 Subject: [PATCH 050/235] test with hhvm too --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 0af2bdad..dbac0381 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,6 +4,7 @@ php: - 5.4 - 5.5 - 5.6 + - hhvm env: - SYMFONY_VERSION=2.3.* From 14ca2d1a0402624c0f73b7e0c899a53108bea289 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fran=C3=A7ois=20Pluchino?= Date: Mon, 7 Dec 2015 19:14:11 +0100 Subject: [PATCH 051/235] Add support of Symfony 3.0 --- composer.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/composer.json b/composer.json index d1dea662..ebdfe381 100644 --- a/composer.json +++ b/composer.json @@ -11,13 +11,13 @@ } ], "require": { - "symfony/framework-bundle": "~2.1", + "symfony/framework-bundle": "~2.1|~3.0", "willdurand/geocoder": "~3.1", - "symfony/console": "~2.1" + "symfony/console": "~2.1|~3.0" }, "require-dev": { "php": ">=5.4", - "symfony/yaml": "~2.1", + "symfony/yaml": "~2.1|~3.0", "maxromanovsky/php-maxmind-geoip": "~1.12", "doctrine/cache": "~1.3", "doctrine/orm": "~2.3" From 660d83c26238cb4cf41519b230d720d27d98957d Mon Sep 17 00:00:00 2001 From: MAXakaWIZARD Date: Wed, 6 Jan 2016 19:36:03 +0200 Subject: [PATCH 052/235] Fix wrong example in docs --- Resources/doc/index.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 1f3204f4..ef3660f2 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -94,8 +94,9 @@ information in your development environment, for instance: ->geocode($request->server->get('REMOTE_ADDR')); // Find the 5 nearest objects (15km) from the current user. + $address = $result->first(); $objects = ObjectQuery::create() - ->filterByDistanceFrom($result->getLatitude(), $result->getLongitude(), 15) + ->filterByDistanceFrom($address->getLatitude(), $address->getLongitude(), 15) ->limit(5) ->find(); From 08e48ae6a6d2c2463ad45b89e2016c21ed755e2a Mon Sep 17 00:00:00 2001 From: William Durand Date: Thu, 25 Feb 2016 17:40:59 +0100 Subject: [PATCH 053/235] Prepare 4.1.0 release --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index ebdfe381..523b43b0 100644 --- a/composer.json +++ b/composer.json @@ -28,7 +28,7 @@ "target-dir": "Bazinga/Bundle/GeocoderBundle", "extra": { "branch-alias": { - "dev-master": "4.0-dev" + "dev-master": "4.1-dev" } } } From 9c47ed2fd968f7f91c0876bef53707df59de3640 Mon Sep 17 00:00:00 2001 From: Tobias Nyholm Date: Tue, 20 Jun 2017 20:02:17 +0200 Subject: [PATCH 054/235] Fixed broken master (#125) * Fixed broken master * Travis fix * Fixed typo * Allow to fail on HHVM --- .travis.yml | 6 ++++-- Tests/Command/GeocodeCommandTest.php | 10 +++++++--- .../EventListener/FakeRequestListenerTest.php | 2 +- Tests/DependencyInjection/Fixtures/config.yml | 2 +- Tests/DumperManagerTest.php | 8 ++++---- Tests/Logger/GeocoderLoggerTest.php | 2 +- Tests/Provider/CacheProviderTest.php | 12 ++++++------ Tests/bootstrap.php | 4 ++-- composer.json | 5 ++++- 9 files changed, 30 insertions(+), 21 deletions(-) diff --git a/.travis.yml b/.travis.yml index dbac0381..ddda3573 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,18 +4,20 @@ php: - 5.4 - 5.5 - 5.6 - - hhvm env: - SYMFONY_VERSION=2.3.* - SYMFONY_VERSION=2.5.* - SYMFONY_VERSION=2.7.* + - SYMFONY_VERSION=2.8.* - SYMFONY_VERSION=dev-master matrix: allow_failures: - env: SYMFONY_VERSION=dev-master - + - php: hhvm + dist: trusty + env: SYMFONY_VERSION=2.7.* before_script: - composer require symfony/framework-bundle:${SYMFONY_VERSION} --no-update diff --git a/Tests/Command/GeocodeCommandTest.php b/Tests/Command/GeocodeCommandTest.php index b205abb9..a9e210fc 100644 --- a/Tests/Command/GeocodeCommandTest.php +++ b/Tests/Command/GeocodeCommandTest.php @@ -32,13 +32,13 @@ public function testExecute() $country = new Country('France', 'FR'); $address = new Address($coordinates, $bounds, '10', 'rue Gambetta', '75020', 'Paris', null, null, $country); - $geocoder = $this->getMock('Geocoder\\ProviderAggregator'); + $geocoder = $this->getMockBuilder('Geocoder\\ProviderAggregator')->getMock(); $geocoder->expects($this->once()) ->method('geocode') ->with(self::$address) ->will($this->returnValue(new AddressCollection(array($address)))); - $container = $this->getMock('Symfony\\Component\\DependencyInjection\\Container'); + $container = $this->getMockBuilder('Symfony\\Component\\DependencyInjection\\Container')->getMock(); $container->expects($this->once()) ->method('get') ->with('bazinga_geocoder.geocoder') @@ -48,10 +48,14 @@ public function testExecute() ->disableOriginalConstructor() ->getMock(); - $kernel->expects($this->once()) + $kernel->expects($this->any()) ->method('getContainer') ->will($this->returnValue($container)); + $kernel->expects($this->any()) + ->method('getBundles') + ->will($this->returnValue([])); + $app = new Application($kernel); $app->add(new GeocodeCommand()); diff --git a/Tests/DependencyInjection/EventListener/FakeRequestListenerTest.php b/Tests/DependencyInjection/EventListener/FakeRequestListenerTest.php index 13a5dc48..fa25b01f 100644 --- a/Tests/DependencyInjection/EventListener/FakeRequestListenerTest.php +++ b/Tests/DependencyInjection/EventListener/FakeRequestListenerTest.php @@ -16,7 +16,7 @@ public function testOnKernelRequest() { $listener = new FakeRequestListener('33.33.33.1'); - $kernel = $this->getMock('Symfony\\Component\\HttpKernel\\HttpKernelInterface'); + $kernel = $this->getMockBuilder('Symfony\\Component\\HttpKernel\\HttpKernelInterface')->getMock(); $request = new Request(); $event = new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST); diff --git a/Tests/DependencyInjection/Fixtures/config.yml b/Tests/DependencyInjection/Fixtures/config.yml index 5635e095..38a45a19 100644 --- a/Tests/DependencyInjection/Fixtures/config.yml +++ b/Tests/DependencyInjection/Fixtures/config.yml @@ -40,7 +40,7 @@ bazinga_geocoder: maxmind: api_key: 123 maxmind_binary: - binary_file: %fixtures_dir%/maxmind.dat + binary_file: "%fixtures_dir%/maxmind.dat" opencage: locale: en_US api_key: 123 diff --git a/Tests/DumperManagerTest.php b/Tests/DumperManagerTest.php index 454952d1..76798ea4 100644 --- a/Tests/DumperManagerTest.php +++ b/Tests/DumperManagerTest.php @@ -21,12 +21,12 @@ protected function setup() public function testSet() { - $this->assertNull($this->manager->set('test', $this->getMock('Geocoder\\Dumper\\Dumper'))); + $this->assertNull($this->manager->set('test', $this->getMockBuilder('Geocoder\\Dumper\\Dumper')->getMock())); } public function testGet() { - $dumper = $this->getMock('Geocoder\\Dumper\\Dumper'); + $dumper = $this->getMockBuilder('Geocoder\\Dumper\\Dumper')->getMock(); $this->manager->set('test', $dumper); $this->assertEquals($dumper, $this->manager->get('test')); @@ -43,13 +43,13 @@ public function testGetNotExistDumper() public function testHas() { $this->assertFalse($this->manager->has('test')); - $this->manager->set('test', $this->getMock('Geocoder\\Dumper\\Dumper')); + $this->manager->set('test', $this->getMockBuilder('Geocoder\\Dumper\\Dumper')->getMock()); $this->assertTrue($this->manager->has('test')); } public function testRemove() { - $this->manager->set('test', $this->getMock('Geocoder\\Dumper\\Dumper')); + $this->manager->set('test', $this->getMockBuilder('Geocoder\\Dumper\\Dumper')->getMock()); $this->manager->remove('test'); $this->assertFalse($this->manager->has('test')); } diff --git a/Tests/Logger/GeocoderLoggerTest.php b/Tests/Logger/GeocoderLoggerTest.php index b300789b..b327b6b2 100644 --- a/Tests/Logger/GeocoderLoggerTest.php +++ b/Tests/Logger/GeocoderLoggerTest.php @@ -27,7 +27,7 @@ class GeocoderLoggerTest extends \PHPUnit_Framework_TestCase public function setUp() { - $logger = $this->getMock('Psr\\Log\\LoggerInterface'); + $logger = $this->getMockBuilder('Psr\\Log\\LoggerInterface')->getMock(); $logger ->expects($this->any()) ->method('info') diff --git a/Tests/Provider/CacheProviderTest.php b/Tests/Provider/CacheProviderTest.php index 993e17af..d641320d 100644 --- a/Tests/Provider/CacheProviderTest.php +++ b/Tests/Provider/CacheProviderTest.php @@ -16,13 +16,13 @@ public function testGeocode() $coordinates = array('lat' => 48.857049,'lng' => 2.35223); $cacheKey = 'geocoder_'.sha1($address); - $delegate = $this->getMock('Geocoder\\Provider\\Provider'); + $delegate = $this->getMockBuilder('Geocoder\\Provider\\Provider')->getMock(); $delegate->expects($this->once()) ->method('geocode') ->with($address) ->will($this->returnValue($coordinates)); - $cache = $this->getMock('Doctrine\\Common\\Cache\\Cache'); + $cache = $this->getMockBuilder('Doctrine\\Common\\Cache\\Cache')->getMock(); $cache->expects($this->once()) ->method('fetch') ->with($cacheKey) @@ -42,7 +42,7 @@ public function testCachedGeocode() $coordinates = array('lat' => 48.857049,'lng' => 2.35223); $cacheKey = 'geocoder_'.sha1($address); - $delegate = $this->getMock('Geocoder\\Provider\\Provider'); + $delegate = $this->getMockBuilder('Geocoder\\Provider\\Provider')->getMock(); $delegate->expects($this->once()) ->method('geocode') ->with($address) @@ -60,7 +60,7 @@ public function testReverse() { $coordinates = array('lat' => 48.857049, 'lon' => 2.35223); - $delegate = $this->getMock('Geocoder\\Provider\\Provider'); + $delegate = $this->getMockBuilder('Geocoder\\Provider\\Provider')->getMock(); $delegate->expects($this->once()) ->method('reverse') ->with($coordinates['lat'], $coordinates['lon']) @@ -76,8 +76,8 @@ public function testReverse() public function testGetName() { - $delegate = $this->getMock('Geocoder\\Provider\\Provider'); - $cache = $this->getMock('Doctrine\\Common\\Cache\\Cache'); + $delegate = $this->getMockBuilder('Geocoder\\Provider\\Provider')->getMock(); + $cache = $this->getMockBuilder('Doctrine\\Common\\Cache\\Cache')->getMock(); $provider = new Cache($cache, $delegate); diff --git a/Tests/bootstrap.php b/Tests/bootstrap.php index e7b54d51..be9b3157 100644 --- a/Tests/bootstrap.php +++ b/Tests/bootstrap.php @@ -7,7 +7,7 @@ '); } -require_once __DIR__.'/../vendor/maxromanovsky/php-maxmind-geoip/geoip.inc'; -require_once __DIR__.'/../vendor/maxromanovsky/php-maxmind-geoip/geoipcity.inc'; +require_once __DIR__.'/../vendor/geoip/geoip/src/geoip.inc'; +require_once __DIR__.'/../vendor/geoip/geoip/src/geoipcity.inc'; $loader->add('Doctrine\Tests', __DIR__.'/../vendor/doctrine/orm/tests'); diff --git a/composer.json b/composer.json index 523b43b0..c9ee0b4e 100644 --- a/composer.json +++ b/composer.json @@ -18,10 +18,13 @@ "require-dev": { "php": ">=5.4", "symfony/yaml": "~2.1|~3.0", - "maxromanovsky/php-maxmind-geoip": "~1.12", + "geoip/geoip": "~1.17", "doctrine/cache": "~1.3", "doctrine/orm": "~2.3" }, + "conflict": { + "willdurand/geocoder": "3.2" + }, "autoload": { "psr-0": { "Bazinga\\Bundle\\GeocoderBundle": "" } }, From 651f69361f42a7b45b6ce96def02a41918f5f0a3 Mon Sep 17 00:00:00 2001 From: Tobias Nyholm Date: Tue, 20 Jun 2017 20:03:52 +0200 Subject: [PATCH 055/235] Make sure we have a valid IP in the example (#118) --- Resources/doc/index.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Resources/doc/index.md b/Resources/doc/index.md index ef3660f2..1970c09b 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -115,7 +115,7 @@ an easy way to fake this behavior by using a `fake_ip` configuration. ``` yaml # app/config/config_dev.yml bazinga_geocoder: - fake_ip: 123.345.643.133 + fake_ip: 123.123.123.123 ``` If set, the parameter will replace the `REMOTE_ADDR` value by the given one. @@ -129,7 +129,7 @@ listeners, You can set up different fake ip listener priority. # app/config/config_dev.yml bazinga_geocoder: fake_ip: - ip: 123.345.643.133 + ip: 123.123.123.123 priority: 128 ``` From e282631b3f3feae71e95a932f00714b22b889e16 Mon Sep 17 00:00:00 2001 From: Antoine Lemaire Date: Tue, 20 Jun 2017 21:42:31 +0200 Subject: [PATCH 056/235] Update WebdebugToolbar design (#126) --- Resources/views/Collector/geocoder.html.twig | 30 +++++++++++--------- Resources/views/Collector/icon.svg | 5 ++++ 2 files changed, 21 insertions(+), 14 deletions(-) create mode 100644 Resources/views/Collector/icon.svg diff --git a/Resources/views/Collector/geocoder.html.twig b/Resources/views/Collector/geocoder.html.twig index 3ae493be..ed1e9410 100644 --- a/Resources/views/Collector/geocoder.html.twig +++ b/Resources/views/Collector/geocoder.html.twig @@ -2,13 +2,15 @@ {% block toolbar %} {% set icon %} - Geocoder - {{ collector.requestscount }} + {{ include('@BazingaGeocoder/Collector/icon.svg') }} + + {{ collector.requestscount }} + {% endset %} {% set text %}
Requests - {{ collector.requestsCount }} + {{ collector.requestsCount }}
Total time @@ -19,7 +21,7 @@ {% endblock %} {% block menu %} - + Geocoder Geocoder @@ -41,8 +43,8 @@
- + - - + + + - {{ request.value }} ({{request.providerClass}})
@@ -64,15 +66,15 @@ {% endif %} + return false; + } + //]]> {% endblock %} diff --git a/Resources/views/Collector/icon.svg b/Resources/views/Collector/icon.svg new file mode 100644 index 00000000..4ca756dc --- /dev/null +++ b/Resources/views/Collector/icon.svg @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file From 923cb785ed34f3d723e2d984255f16fead10ee2f Mon Sep 17 00:00:00 2001 From: Kowol Date: Tue, 20 Jun 2017 21:44:29 +0200 Subject: [PATCH 057/235] Added ArcGIS support (#119) --- DependencyInjection/BazingaGeocoderExtension.php | 9 +++++++++ DependencyInjection/Configuration.php | 6 ++++++ Resources/config/services.xml | 1 + .../DependencyInjection/BazingaGeocoderExtensionTest.php | 1 + Tests/DependencyInjection/Fixtures/config.yml | 1 + 5 files changed, 18 insertions(+) diff --git a/DependencyInjection/BazingaGeocoderExtension.php b/DependencyInjection/BazingaGeocoderExtension.php index e76a1d2e..6666bed9 100644 --- a/DependencyInjection/BazingaGeocoderExtension.php +++ b/DependencyInjection/BazingaGeocoderExtension.php @@ -89,6 +89,15 @@ public function load(array $configs, ContainerBuilder $container) )); } + if (isset($config['providers']['arcgis_online'])) { + $params = $config['providers']['arcgis_online']; + + $this->addProvider('arcgis_online', array( + $params['source_country'], + $params['use_ssl'], + )); + } + if (isset($config['providers']['google_maps_business'])) { $googleMapsBusinessParams = $config['providers']['google_maps_business']; diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index c97d5fd7..292b60ff 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -94,6 +94,12 @@ public function getConfigTreeBuilder() ->scalarNode('api_key')->defaultNull()->end() ->end() ->end() + ->arrayNode('arcgis_online') + ->children() + ->scalarNode('source_country')->defaultNull()->end() + ->booleanNode('use_ssl')->defaultFalse()->end() + ->end() + ->end() ->arrayNode('google_maps_business') ->children() ->scalarNode('client_id')->isRequired()->cannotBeEmpty()->end() diff --git a/Resources/config/services.xml b/Resources/config/services.xml index f7171801..4f6b2df1 100644 --- a/Resources/config/services.xml +++ b/Resources/config/services.xml @@ -10,6 +10,7 @@ Geocoder\Provider\BingMaps Geocoder\Provider\FreeGeoIp Geocoder\Provider\GoogleMaps + Geocoder\Provider\ArcGISOnline Geocoder\Provider\GoogleMapsBusiness Geocoder\Provider\HostIp Geocoder\Provider\IpInfoDb diff --git a/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php b/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php index 687d3a7c..537f3061 100644 --- a/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php +++ b/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php @@ -57,6 +57,7 @@ public function testLoad() 'cache' => 'Bazinga\\Bundle\\GeocoderBundle\\Provider\\Cache', 'ip_info_db' => 'Geocoder\\Provider\\IpInfoDb', 'google_maps' => 'Geocoder\\Provider\\GoogleMaps', + 'arcgis_online' => 'Geocoder\\Provider\\ArcGISOnline', 'google_maps_business' => 'Geocoder\\Provider\\GoogleMapsBusiness', 'openstreetmap' => 'Geocoder\\Provider\\OpenStreetMap', 'host_ip' => 'Geocoder\\Provider\\HostIp', diff --git a/Tests/DependencyInjection/Fixtures/config.yml b/Tests/DependencyInjection/Fixtures/config.yml index 38a45a19..0b376990 100644 --- a/Tests/DependencyInjection/Fixtures/config.yml +++ b/Tests/DependencyInjection/Fixtures/config.yml @@ -15,6 +15,7 @@ bazinga_geocoder: lifetime: 86400 ip_info_db: api_key: 123 + arcgis_online: ~ google_maps: locale: en_US region: en_US From 25302dc8801cfdaa7f6c7027c7c6329e1aaa9534 Mon Sep 17 00:00:00 2001 From: Tobias Nyholm Date: Sun, 25 Jun 2017 18:14:38 +0200 Subject: [PATCH 058/235] Added license file and coc --- CODE_OF_CONDUCT.md | 29 +++++++++++++++++++++++++++++ LICENSE | 19 +++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 CODE_OF_CONDUCT.md create mode 100644 LICENSE diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..fe12b3ba --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,29 @@ + +Contributor Code of Conduct +--------------------------- + +As contributors and maintainers of this project, we pledge to respect all people +who contribute through reporting issues, posting feature requests, updating +documentation, submitting pull requests or patches, and other activities. + +We are committed to making participation in this project a harassment-free +experience for everyone, regardless of level of experience, gender, gender +identity and expression, sexual orientation, disability, personal appearance, +body size, race, age, or religion. + +Examples of unacceptable behavior by participants include the use of sexual +language or imagery, derogatory comments or personal attacks, trolling, public +or private harassment, insults, or other unprofessional conduct. + +Project maintainers have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct. Project maintainers who do not follow the +Code of Conduct may be removed from the project team. + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by opening an issue or contacting one or more of the project +maintainers. + +This Code of Conduct is adapted from the [Contributor +Covenant](http:contributor-covenant.org), version 1.0.0, available at +[http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/) diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..a6b7b809 --- /dev/null +++ b/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) Since 2011 — William Durand + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. From 392de1c4b12dd837b422dd91850973002655bcb6 Mon Sep 17 00:00:00 2001 From: Tobias Nyholm Date: Thu, 6 Jul 2017 20:33:24 +0200 Subject: [PATCH 059/235] First idea of how version 5 will look (#127) * Starting to support geocoder v4 * Using provider factories to create providers * Factory fixes * Adding profiling provider * Do not profile if not debug * Remove services.xml * Added chain factory * Bugfixes * Bugfixes * Bugfixes * Fixed tests * Travis config update * Adding support for cache * Added change log --- .travis.yml | 22 +- BazingaGeocoderBundle.php | 6 +- Changelog.md | 26 ++ DataCollector/GeocoderDataCollector.php | 4 +- DataCollector/ProfilingProvider.php | 83 ++++++ .../BazingaGeocoderExtension.php | 269 +++++------------- .../Compiler/AddDumperPass.php | 42 --- .../Compiler/AddProvidersPass.php | 11 +- DependencyInjection/Compiler/LoggablePass.php | 34 --- DependencyInjection/Compiler/ProfilerPass.php | 44 +++ DependencyInjection/Configuration.php | 196 ++++--------- Doctrine/ORM/GeocoderListener.php | 16 +- DumperManager.php | 94 ------ Geocoder/LoggableGeocoder.php | 79 ----- Logger/GeocoderLogger.php | 15 +- Provider/Cache.php | 115 -------- ProviderFactory/AbstractFactory.php | 93 ++++++ ProviderFactory/ChainFactory.php | 44 +++ ProviderFactory/GoogleMapsFactory.php | 35 +++ ProviderFactory/ProviderFactoryInterface.php | 43 +++ Resources/config/profiling.yml | 7 + Resources/config/services.xml | 91 ------ Resources/config/services.yml | 28 ++ Resources/doc/index.md | 6 +- Resources/meta/LICENSE | 19 -- Tests/Command/GeocodeCommandTest.php | 11 +- .../BazingaGeocoderExtensionTest.php | 121 -------- .../Compiler/AddDumperPassTest.php | 39 --- .../DependencyInjection/ConfigurationTest.php | 2 +- Tests/DependencyInjection/Fixtures/config.yml | 44 ++- .../Fixtures/old_fake_ip.yml | 2 - Tests/Doctrine/ORM/GeocoderListenerTest.php | 12 +- Tests/DumperManagerTest.php | 64 ----- Tests/Logger/GeocoderLoggerTest.php | 65 ++++- Tests/Provider/CacheProviderTest.php | 86 ------ Tests/bootstrap.php | 2 + composer.json | 26 +- 37 files changed, 700 insertions(+), 1196 deletions(-) create mode 100644 Changelog.md create mode 100644 DataCollector/ProfilingProvider.php delete mode 100644 DependencyInjection/Compiler/AddDumperPass.php delete mode 100644 DependencyInjection/Compiler/LoggablePass.php create mode 100644 DependencyInjection/Compiler/ProfilerPass.php delete mode 100644 DumperManager.php delete mode 100644 Geocoder/LoggableGeocoder.php delete mode 100644 Provider/Cache.php create mode 100644 ProviderFactory/AbstractFactory.php create mode 100644 ProviderFactory/ChainFactory.php create mode 100644 ProviderFactory/GoogleMapsFactory.php create mode 100644 ProviderFactory/ProviderFactoryInterface.php create mode 100644 Resources/config/profiling.yml delete mode 100644 Resources/config/services.xml create mode 100644 Resources/config/services.yml delete mode 100644 Resources/meta/LICENSE delete mode 100644 Tests/DependencyInjection/BazingaGeocoderExtensionTest.php delete mode 100644 Tests/DependencyInjection/Compiler/AddDumperPassTest.php delete mode 100644 Tests/DependencyInjection/Fixtures/old_fake_ip.yml delete mode 100644 Tests/DumperManagerTest.php delete mode 100644 Tests/Provider/CacheProviderTest.php diff --git a/.travis.yml b/.travis.yml index ddda3573..45b415ed 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,23 +1,22 @@ language: php +sudo: false + +cache: + directories: + - $HOME/.composer/cache + php: - - 5.4 - - 5.5 - - 5.6 + - 7.0 + - 7.1 env: - - SYMFONY_VERSION=2.3.* - - SYMFONY_VERSION=2.5.* - - SYMFONY_VERSION=2.7.* - - SYMFONY_VERSION=2.8.* + - SYMFONY_VERSION=3.3.* - SYMFONY_VERSION=dev-master matrix: allow_failures: - env: SYMFONY_VERSION=dev-master - - php: hhvm - dist: trusty - env: SYMFONY_VERSION=2.7.* before_script: - composer require symfony/framework-bundle:${SYMFONY_VERSION} --no-update @@ -25,4 +24,5 @@ before_script: # won't be found. - composer update --prefer-source -script: phpunit --coverage-text +script: + - phpunit --coverage-text --coverage-clover=build/coverage.xml diff --git a/BazingaGeocoderBundle.php b/BazingaGeocoderBundle.php index 03aef541..ed20d7e6 100644 --- a/BazingaGeocoderBundle.php +++ b/BazingaGeocoderBundle.php @@ -12,8 +12,7 @@ use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Bundle\Bundle; use Bazinga\Bundle\GeocoderBundle\DependencyInjection\Compiler\AddProvidersPass; -use Bazinga\Bundle\GeocoderBundle\DependencyInjection\Compiler\AddDumperPass; -use Bazinga\Bundle\GeocoderBundle\DependencyInjection\Compiler\LoggablePass; +use Bazinga\Bundle\GeocoderBundle\DependencyInjection\Compiler\ProfilerPass; /** * @author William Durand @@ -27,8 +26,7 @@ public function build(ContainerBuilder $container) { parent::build($container); + $container->addCompilerPass(new ProfilerPass()); $container->addCompilerPass(new AddProvidersPass()); - $container->addCompilerPass(new AddDumperPass()); - $container->addCompilerPass(new LoggablePass()); } } diff --git a/Changelog.md b/Changelog.md new file mode 100644 index 00000000..7ecc7f6e --- /dev/null +++ b/Changelog.md @@ -0,0 +1,26 @@ +# Changelog + +The changelog describes what have been "Added", "Changed", "Removed" or "Fixed" between versions. + +## Version 5.0.0 + +Version 5 does only support Symfony 3.3+ and PHP7. We dropped some complexity and added plenty of type hints. + +### Added + +- Support for Geocoder 4.0 +- Provider factories + +### Changed + +- We moved cache support to `geocoder-php/cache-provider` + +### Removed + +- `DumperManager` +- `LoggableGeocoder` +- Configuration for default provider + +## Version 4.1.0 + +No changelog before this version \ No newline at end of file diff --git a/DataCollector/GeocoderDataCollector.php b/DataCollector/GeocoderDataCollector.php index d11dd120..1f16c425 100644 --- a/DataCollector/GeocoderDataCollector.php +++ b/DataCollector/GeocoderDataCollector.php @@ -22,7 +22,7 @@ class GeocoderDataCollector extends DataCollector /** * @var GeocoderLogger */ - protected $logger; + private $logger; /** * @param GeocoderLogger $logger @@ -38,7 +38,7 @@ public function __construct(GeocoderLogger $logger) public function collect(Request $request, Response $response, \Exception $exception = null) { $this->data = array( - 'requests' => null !== $this->logger ? $this->logger->getRequests() : array(), + 'requests' => $this->logger->getRequests(), ); } diff --git a/DataCollector/ProfilingProvider.php b/DataCollector/ProfilingProvider.php new file mode 100644 index 00000000..ac975ea2 --- /dev/null +++ b/DataCollector/ProfilingProvider.php @@ -0,0 +1,83 @@ + + */ +class ProfilingProvider implements Provider +{ + /** + * @var Provider + */ + private $realProvider; + + /** + * @var GeocoderLogger + */ + private $logger; + + /** + * @param Provider $realProvider + * @param GeocoderLogger $logger + */ + public function __construct(Provider $realProvider, GeocoderLogger $logger) + { + $this->realProvider = $realProvider; + $this->logger = $logger; + } + + public function geocodeQuery(GeocodeQuery $query): Collection + { + $startTime = microtime(true); + try { + $results = $this->realProvider->geocodeQuery($query); + } finally { + $duration = (microtime(true) - $startTime) * 1000; + + $this->logger->logRequest( + sprintf('[Geocoding] %s', $query), + $duration, + $this->getName(), + $results + ); + } + + return $results; + } + + public function reverseQuery(ReverseQuery $query): Collection + { + $startTime = microtime(true); + try { + $results = $this->realProvider->reverseQuery($query); + } finally { + $duration = (microtime(true) - $startTime) * 1000; + + $this->logger->logRequest( + sprintf('[Geocoding] %s', $query), + $duration, + $this->getName(), + $results + ); + } + + return $results; + } + + public function __call($method, $args) + { + return call_user_func_array([$this->realProvider, $method], $args); + } + + public function getName(): string + { + return $this->realProvider->getName(); + } +} diff --git a/DependencyInjection/BazingaGeocoderExtension.php b/DependencyInjection/BazingaGeocoderExtension.php index 6666bed9..b796f6f4 100644 --- a/DependencyInjection/BazingaGeocoderExtension.php +++ b/DependencyInjection/BazingaGeocoderExtension.php @@ -9,6 +9,9 @@ */ namespace Bazinga\Bundle\GeocoderBundle\DependencyInjection; +use Bazinga\Bundle\GeocoderBundle\ProviderFactory\ProviderFactoryInterface; +use Geocoder\Provider\Provider; +use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; use Symfony\Component\DependencyInjection\ContainerBuilder; @@ -22,22 +25,19 @@ */ class BazingaGeocoderExtension extends Extension { - protected $container; - public function load(array $configs, ContainerBuilder $container) { - $this->container = $container; - $processor = new Processor(); - $configuration = new Configuration(); + $configuration = $this->getConfiguration($configs, $container); $config = $processor->processConfiguration($configuration, $configs); - $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); - $loader->load('services.xml'); + $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); + $loader->load('services.yml'); - if ($config['default_provider']) { - $container->setParameter('bazinga_geocoder.default_provider', $config['default_provider']); + if ($config['profiling']) { + $loader->load('profiling.yml'); } + $this->loadProviders($container, $config); if (!empty($config['fake_ip']) && true === $config['fake_ip']['enabled']) { $definition = $container->getDefinition('bazinga_geocoder.event_listener.fake_request'); @@ -50,203 +50,90 @@ public function load(array $configs, ContainerBuilder $container) } else { $container->removeDefinition('bazinga_geocoder.event_listener.fake_request'); } + } - $container->setAlias('bazinga_geocoder.geocoder.adapter', $config['adapter']); - - if (isset($config['providers']['free_geo_ip'])) { - $this->addProvider('free_geo_ip'); - } - - if (isset($config['providers']['host_ip'])) { - $this->addProvider('host_ip'); - } - - if (isset($config['providers']['bing_maps'])) { - $bingMapsParams = $config['providers']['bing_maps']; - - $this->addProvider('bing_maps', array( - $bingMapsParams['api_key'], - $bingMapsParams['locale'], - )); - } - - if (isset($config['providers']['ip_info_db'])) { - $ipInfoDbParams = $config['providers']['ip_info_db']; - - $this->addProvider('ip_info_db', array( - $ipInfoDbParams['api_key'], - )); - } - - if (isset($config['providers']['google_maps'])) { - $googleMapsParams = $config['providers']['google_maps']; - - $this->addProvider('google_maps', array( - $googleMapsParams['locale'], - $googleMapsParams['region'], - $googleMapsParams['use_ssl'], - $googleMapsParams['api_key'], - )); - } - - if (isset($config['providers']['arcgis_online'])) { - $params = $config['providers']['arcgis_online']; - - $this->addProvider('arcgis_online', array( - $params['source_country'], - $params['use_ssl'], - )); - } - - if (isset($config['providers']['google_maps_business'])) { - $googleMapsBusinessParams = $config['providers']['google_maps_business']; - - $this->addProvider('google_maps_business', array( - $googleMapsBusinessParams['client_id'], - $googleMapsBusinessParams['api_key'], - $googleMapsBusinessParams['locale'], - $googleMapsBusinessParams['region'], - $googleMapsBusinessParams['use_ssl'], - )); - } - - if (isset($config['providers']['openstreetmap'])) { - $openstreetMapsParams = $config['providers']['openstreetmap']; - - $this->addProvider('openstreetmap', array( - $openstreetMapsParams['locale'], - )); - } - - if (isset($config['providers']['geoip'])) { - $this->addProvider('geoip'); - } - - if (isset($config['providers']['mapquest'])) { - $mapQuestParams = $config['providers']['mapquest']; - - $this->addProvider('mapquest', array( - $mapQuestParams['api_key'], - )); - } - - if (isset($config['providers']['yandex'])) { - $yandexParams = $config['providers']['yandex']; - - $this->addProvider('yandex', array( - $yandexParams['locale'], - $yandexParams['toponym'], - )); - } - - if (isset($config['providers']['geo_ips'])) { - $geoIpsParams = $config['providers']['geo_ips']; - - $this->addProvider('geo_ips', array( - $geoIpsParams['api_key'], - )); - } - - if (isset($config['providers']['geo_plugin'])) { - $this->addProvider('geo_plugin'); - } - - if (isset($config['providers']['maxmind'])) { - $maxmindParams = $config['providers']['maxmind']; - - $this->addProvider('maxmind', array( - $maxmindParams['api_key'], - )); - } + private function loadProviders(ContainerBuilder $container, array $config) + { + foreach ($config['providers'] as $providerName => $providerConfig) { + $factoryService = $container->getDefinition($providerConfig['factory']); + $factoryClass = $factoryService->getClass() ?: $providerConfig['factory']; + if (!(is_a($factoryClass, ProviderFactoryInterface::class))) { + //throw new \LogicException(sprintf('Provider factory "%s" must implement ProviderFactoryInterface', $providerConfig['factory'])); + } + $factoryClass::validate($providerConfig['options'], $providerName); - if (isset($config['providers']['maxmind_binary'])) { - $maxmindBinaryParams = $config['providers']['maxmind_binary']; + // See if any option has a service reference + $providerConfig['options'] = $this->findReferences($providerConfig['options']); - $provider = new Definition( - '%bazinga_geocoder.geocoder.provider.maxmind_binary.class%', - array( - $maxmindBinaryParams['binary_file'], - $maxmindBinaryParams['open_flag'], - ) - ); + $serviceId = 'bazinga_geocoder.provider.'.$providerName; + $def = $container->register($serviceId, Provider::class); + $def->setFactory([new Reference($providerConfig['factory']), 'createProvider']) + ->addArgument($providerConfig['options']); - $provider - ->setPublic(false) - ->addTag('bazinga_geocoder.provider'); + $def->addTag('bazinga_geocoder.provider'); + foreach ($providerConfig['aliases'] as $alias) { + $container->setAlias($alias, $serviceId); + } - $container->setDefinition('bazinga_geocoder.provider.maxmind_binary', $provider); + $this->configureCache($container, $serviceId, $providerConfig); } + } - if (isset($config['providers']['opencage'])) { - $openCageParams = $config['providers']['opencage']; - - $this->addProvider('opencage', array( - $openCageParams['api_key'], - $openCageParams['use_ssl'], - $openCageParams['locale'], - )); + /** + * Add cache to a provider if needed. + * + * @param ContainerBuilder $ + * @param string $serviceId + * @param array $providerConfig + */ + private function configureCache(ContainerBuilder $container, string $serviceId, array $providerConfig) + { + if ( + (null !== $providerConfig['cache'] || null !== $providerConfig['cache_lifetime']) && + !class_exists(ProviderCache::class) + ) { + throw new \LogicException('You must install "geocoder-php/chain-provider" to use cache.'); } - if (isset($config['providers']['cache'])) { - $params = $config['providers']['cache']; - $cache = new Reference($params['adapter']); - $fallback = new Reference('bazinga_geocoder.provider.'.$params['provider']); - - $provider = new Definition( - '%bazinga_geocoder.geocoder.provider.cache.class%', - array($cache, $fallback, $params['lifetime']) - ); - - if (isset($params['locale'])) { - $provider->addArgument($params['locale']); + if (null !== $cacheServiceId = $providerConfig['cache']) { + if (!$container->has('app.cache\'')) { + throw new \LogicException('You need to specify a service for cache.'); } + $cacheServiceId = 'app.cache'; + } - $provider - ->setPublic(false) - ->addTag('bazinga_geocoder.provider'); + $container->register($serviceId.'.cache', ProviderCache::class) + ->setDecoratedService($serviceId) + ->setArguments([ + new Reference($serviceId.'.cache.inner'), + new Reference($cacheServiceId), + $providerConfig['cache_lifetime'] + ]); + } - $container->setDefinition('bazinga_geocoder.provider.cache', $provider); - } + /** + * {@inheritdoc} + */ + public function getConfiguration(array $config, ContainerBuilder $container) + { + return new Configuration($container->getParameter('kernel.debug')); + } - if (isset($config['providers']['chain'])) { - $chainProvider = new Definition( - '%bazinga_geocoder.geocoder.provider.chain.class%' - ); - - $this->container->setDefinition('bazinga_geocoder.provider.chain', $chainProvider); - - $chainProvider - ->setPublic(false) - ->addTag('bazinga_geocoder.provider'); - - if (isset($config['providers']['chain']['providers'])) { - foreach ($config['providers']['chain']['providers'] as $name) { - if ($this->container->hasDefinition('bazinga_geocoder.provider.'.$name)) { - $chainProvider->addMethodCall('add', array( - $this->container->getDefinition('bazinga_geocoder.provider.'.$name), - )); - } else { - $chainProvider->addMethodCall('add', array(new Reference($name))); - } - } + /** + * @param array $options + * + * @return array + */ + private function findReferences(array $options) + { + foreach ($options as $key => $value) { + if (is_array($value)) { + $options[$key] = $this->findReferences($value); + } elseif (substr($key, -8) === '_service' || strpos($value, '@') === 0 || $key === 'service') { + $options[$key] = new Reference(ltrim($value, '@')); } } - } - protected function addProvider($name, array $arguments = array()) - { - $provider = new Definition( - '%bazinga_geocoder.geocoder.provider.'.$name.'.class%', - array_merge( - array(new Reference('bazinga_geocoder.geocoder.adapter')), - $arguments - ) - ); - - $provider - ->setPublic(false) - ->addTag('bazinga_geocoder.provider'); - - $this->container->setDefinition('bazinga_geocoder.provider.'.$name, $provider); + return $options; } } diff --git a/DependencyInjection/Compiler/AddDumperPass.php b/DependencyInjection/Compiler/AddDumperPass.php deleted file mode 100644 index c9563347..00000000 --- a/DependencyInjection/Compiler/AddDumperPass.php +++ /dev/null @@ -1,42 +0,0 @@ - - */ -class AddDumperPass implements CompilerPassInterface -{ - /** - * {@inheritdoc} - */ - public function process(ContainerBuilder $container) - { - if (!$container->hasDefinition('bazinga_geocoder.dumper_manager')) { - return; - } - - $manager = $container->findDefinition('bazinga_geocoder.dumper_manager'); - - $dumpers = array(); - foreach ($container->findTaggedServiceIds('bazinga_geocoder.dumper') as $id => $attributes) { - if (!isset($attributes[0]['alias'])) { - throw new \RuntimeException(sprintf('No alias for service "%s" provided. Please set a alias!', $id)); - } - - $dumpers[$attributes[0]['alias']] = $container->getDefinition($id); - } - - $manager->setArguments(array($dumpers)); - } -} diff --git a/DependencyInjection/Compiler/AddProvidersPass.php b/DependencyInjection/Compiler/AddProvidersPass.php index e7cfd64d..647db81f 100644 --- a/DependencyInjection/Compiler/AddProvidersPass.php +++ b/DependencyInjection/Compiler/AddProvidersPass.php @@ -31,7 +31,7 @@ class AddProvidersPass implements CompilerPassInterface */ public function process(ContainerBuilder $container) { - if (!$container->hasDefinition('bazinga_geocoder.geocoder')) { + if (!$container->hasDefinition('Geocoder\\ProviderAggregator')) { return; } @@ -40,14 +40,7 @@ public function process(ContainerBuilder $container) $providers[] = new Reference($providerId); } - $geocoderDefinition = $container->getDefinition('bazinga_geocoder.geocoder'); + $geocoderDefinition = $container->getDefinition('Geocoder\\ProviderAggregator'); $geocoderDefinition->addMethodCall('registerProviders', array($providers)); - - if ($container->hasParameter('bazinga_geocoder.default_provider')) { - $geocoderDefinition->addMethodCall( - 'using', - array($container->getParameter('bazinga_geocoder.default_provider')) - ); - } } } diff --git a/DependencyInjection/Compiler/LoggablePass.php b/DependencyInjection/Compiler/LoggablePass.php deleted file mode 100644 index 34ed6c71..00000000 --- a/DependencyInjection/Compiler/LoggablePass.php +++ /dev/null @@ -1,34 +0,0 @@ - - */ -class LoggablePass implements CompilerPassInterface -{ - /** - * {@inheritdoc} - */ - public function process(ContainerBuilder $container) - { - if (!$container->hasDefinition('bazinga_geocoder.geocoder')) { - return; - } - - $definition = $container->getDefinition('bazinga_geocoder.geocoder'); - $definition->setClass($container->getParameter('bazinga_geocoder.geocoder.loggable_class')); - $definition->addMethodCall('setLogger', array(new Reference('bazinga_geocoder.logger'))); - } -} diff --git a/DependencyInjection/Compiler/ProfilerPass.php b/DependencyInjection/Compiler/ProfilerPass.php new file mode 100644 index 00000000..a9367681 --- /dev/null +++ b/DependencyInjection/Compiler/ProfilerPass.php @@ -0,0 +1,44 @@ + + */ +class ProfilerPass implements CompilerPassInterface +{ + /** + * {@inheritdoc} + */ + public function process(ContainerBuilder $container) + { + if (!$container->hasDefinition(GeocoderDataCollector::class)) { + return; + } + + foreach ($container->findTaggedServiceIds('bazinga_geocoder.provider') as $providerId => $attributes) { + $container->register($providerId.'.debug', ProfilingProvider::class) + ->setDecoratedService($providerId) + ->setArguments([ + new Reference($providerId.'.debug.inner'), + new Reference(GeocoderLogger::class) + ]); + } + } +} diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 292b60ff..b9154cfc 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -9,6 +9,7 @@ */ namespace Bazinga\Bundle\GeocoderBundle\DependencyInjection; +use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; @@ -17,6 +18,23 @@ */ class Configuration implements ConfigurationInterface { + /** + * Whether to use the debug mode. + * + * @see https://github.com/doctrine/DoctrineBundle/blob/v1.5.2/DependencyInjection/Configuration.php#L31-L41 + * + * @var bool + */ + private $debug; + + /** + * @param bool $debug + */ + public function __construct($debug) + { + $this->debug = (bool) $debug; + } + /** * Generates the configuration tree builder. * @@ -29,6 +47,20 @@ public function getConfigTreeBuilder() $rootNode ->children() + ->append($this->getProvidersNode()) + ->arrayNode('profiling') + ->addDefaultsIfNotSet() + ->treatFalseLike(['enabled' => false]) + ->treatTrueLike(['enabled' => true]) + ->treatNullLike(['enabled' => $this->debug]) + ->info('Extend the debug profiler with information about requests.') + ->children() + ->booleanNode('enabled') + ->info('Turn the toolbar on or off. Defaults to kernel debug mode.') + ->defaultValue($this->debug) + ->end() + ->end() + ->end() ->scalarNode('default_provider')->defaultNull()->end() ->arrayNode('fake_ip') ->beforeNormalization() @@ -46,147 +78,35 @@ public function getConfigTreeBuilder() ->scalarNode('priority')->defaultValue(0)->end() ->end() ->end() - ->scalarNode('adapter')->defaultValue('bazinga_geocoder.geocoder.default_adapter')->end() - ->arrayNode('providers') + ; + + return $treeBuilder; + } + + /** + * @return ArrayNodeDefinition + */ + private function getProvidersNode() + { + $treeBuilder = new TreeBuilder(); + $node = $treeBuilder->root('providers'); + + $node + ->requiresAtLeastOneElement() + ->useAttributeAsKey('name') + ->prototype('array') ->children() - ->arrayNode('bing_maps') - ->children() - ->scalarNode('api_key') - ->isRequired()->cannotBeEmpty() - ->end() - ->scalarNode('locale')->defaultNull()->end() - ->end() - ->end() - ->arrayNode('cache') - ->children() - ->scalarNode('adapter') - ->isRequired() - ->cannotBeEmpty() - ->end() - ->scalarNode('provider') - ->isRequired() - ->cannotBeEmpty() - ->end() - ->scalarNode('locale') - ->defaultNull() - ->end() - ->scalarNode('lifetime') - ->defaultValue(86400) - ->validate() - ->ifTrue(function ($v) { return !is_integer($v); }) - ->thenInvalid('Only integer are allowed!') - ->end() - ->end() + ->scalarNode('factory')->isRequired()->cannotBeEmpty()->end() + ->variableNode('options')->defaultValue([])->end() + ->scalarNode('cache')->defaultNull()->end() + ->scalarNode('cache_lifetime')->defaultNull()->end() + ->arrayNode('aliases') + ->prototype('scalar')->end() ->end() ->end() - ->arrayNode('ip_info_db') - ->children() - ->scalarNode('api_key') - ->isRequired()->cannotBeEmpty() - ->end() - ->end() - ->end() - ->arrayNode('google_maps') - ->children() - ->scalarNode('locale')->defaultNull()->end() - ->scalarNode('region')->defaultNull()->end() - ->booleanNode('use_ssl')->defaultFalse()->end() - ->scalarNode('api_key')->defaultNull()->end() - ->end() - ->end() - ->arrayNode('arcgis_online') - ->children() - ->scalarNode('source_country')->defaultNull()->end() - ->booleanNode('use_ssl')->defaultFalse()->end() - ->end() - ->end() - ->arrayNode('google_maps_business') - ->children() - ->scalarNode('client_id')->isRequired()->cannotBeEmpty()->end() - ->scalarNode('api_key')->defaultNull()->end() - ->scalarNode('locale')->defaultNull()->end() - ->scalarNode('region')->defaultNull()->end() - ->booleanNode('use_ssl')->defaultFalse()->end() - ->end() - ->end() - ->arrayNode('openstreetmap') - ->children() - ->scalarNode('locale')->defaultNull()->end() - ->end() - ->end() - ->arrayNode('host_ip')->end() - ->arrayNode('geoip')->end() - ->arrayNode('free_geo_ip')->end() - ->arrayNode('mapquest') - ->children() - ->scalarNode('api_key') - ->isRequired()->cannotBeEmpty() - ->end() - ->end() - ->end() - ->arrayNode('ign_openls') - ->children() - ->scalarNode('api_key') - ->isRequired()->cannotBeEmpty() - ->end() - ->end() - ->end() - ->arrayNode('yandex') - ->children() - ->scalarNode('locale')->defaultNull()->end() - ->scalarNode('toponym')->defaultNull()->end() - ->end() - ->end() - ->arrayNode('geo_ips') - ->children() - ->scalarNode('api_key')->defaultNull()->end() - ->end() - ->end() - ->arrayNode('geo_plugin')->end() - ->arrayNode('maxmind') - ->children() - ->scalarNode('api_key') - ->isRequired()->cannotBeEmpty() - ->end() - ->end() - ->end() - ->arrayNode('maxmind_binary') - ->children() - ->scalarNode('binary_file') - ->isRequired()->cannotBeEmpty() - ->end() - ->scalarNode('open_flag') - ->defaultValue(null) - ->end() - ->end() - ->end() - ->arrayNode('opencage') - ->children() - ->scalarNode('locale')->defaultNull()->end() - ->booleanNode('use_ssl')->defaultFalse()->end() - ->scalarNode('api_key')->isRequired()->cannotBeEmpty()->end() - ->end() - ->end() - ->arrayNode('chain') - ->fixXmlConfig('provider') - ->children() - ->arrayNode('providers') - ->performNoDeepMerging() - ->prototype('scalar')->end() - ->end() - ->end() - ->end() - ->arrayNode('tom_tom') - ->children() - ->scalarNode('api_key') - ->isRequired()->cannotBeEmpty() - ->end() - ->scalarNode('locale')->defaultNull()->end() - ->end() - ->end() - ->end() - ; + ->end(); - return $treeBuilder; + return $node; } + } diff --git a/Doctrine/ORM/GeocoderListener.php b/Doctrine/ORM/GeocoderListener.php index 06725513..aca0cd60 100644 --- a/Doctrine/ORM/GeocoderListener.php +++ b/Doctrine/ORM/GeocoderListener.php @@ -7,17 +7,25 @@ use Doctrine\ORM\Event\OnFlushEventArgs; use Bazinga\Bundle\GeocoderBundle\Mapping\Driver\DriverInterface; use Geocoder\Geocoder; +use Geocoder\Provider\Provider; +use Geocoder\Query\GeocodeQuery; /** * @author Markus Bachmann */ class GeocoderListener implements EventSubscriber { + /** + * @var DriverInterface + */ private $driver; + /** + * @var Provider + */ private $geocoder; - public function __construct(Geocoder $geocoder, DriverInterface $driver) + public function __construct(Provider $geocoder, DriverInterface $driver) { $this->driver = $driver; $this->geocoder = $geocoder; @@ -69,12 +77,12 @@ private function geocodeEntity($entity) { $metadata = $this->driver->loadMetadataFromObject($entity); $address = $metadata->addressProperty->getValue($entity); - $results = $this->geocoder->geocode($address); + $results = $this->geocoder->geocodeQuery(GeocodeQuery::create($address)); if (!empty($results)) { $result = $results->first(); - $metadata->latitudeProperty->setValue($entity, $results->first()->getLatitude()); - $metadata->longitudeProperty->setValue($entity, $results->first()->getLongitude()); + $metadata->latitudeProperty->setValue($entity, $result->getCoordinates()->getLatitude()); + $metadata->longitudeProperty->setValue($entity, $result->getCoordinates()->getLongitude()); } } } diff --git a/DumperManager.php b/DumperManager.php deleted file mode 100644 index 8f2ac9ce..00000000 --- a/DumperManager.php +++ /dev/null @@ -1,94 +0,0 @@ - - */ -class DumperManager -{ - /** - * @var array - */ - private $dumpers; - - /** - * Constructor. - * - * @param array $dumpers - */ - public function __construct(array $dumpers = array()) - { - $this->dumpers = array(); - - foreach ($dumpers as $name => $dumper) { - $this->set($name, $dumper); - } - } - - /** - * Get a dumper. - * - * @param string $name The name of the dumper - * - * @return Dumper - * - * @throws \RuntimeException If no dumper was found - */ - public function get($name) - { - if (!isset($this->dumpers[$name])) { - throw new \RuntimeException(sprintf('The dumper "%s" does not exist', $name)); - } - - return $this->dumpers[$name]; - } - - /** - * Sets a dumper. - * - * @param string $name The name - * @param Dumper $dumper The dumper instance - */ - public function set($name, Dumper $dumper) - { - $this->dumpers[$name] = $dumper; - } - - /** - * Remove a dumper instance from the manager. - * - * @param string $name The name of the dumper - * - * @throws \RuntimeException If no dumper was found - */ - public function remove($name) - { - if (!isset($this->dumpers[$name])) { - throw new \RuntimeException(sprintf('The dumper "%s" does not exist', $name)); - } - - unset($this->dumpers[$name]); - } - - /** - * Return true if $name exists, false otherwise. - * - * @param $name The name of the dumper - * - * @return bool - */ - public function has($name) - { - return array_key_exists($name, $this->dumpers); - } -} diff --git a/Geocoder/LoggableGeocoder.php b/Geocoder/LoggableGeocoder.php deleted file mode 100644 index 00e15352..00000000 --- a/Geocoder/LoggableGeocoder.php +++ /dev/null @@ -1,79 +0,0 @@ -logger = $logger; - } - - /** - * {@inheritdoc} - */ - public function geocode($value) - { - if (null === $this->logger) { - return parent::geocode($value); - } - - $startTime = microtime(true); - $results = parent::geocode($value); - $duration = (microtime(true) - $startTime) * 1000; - - $this->logger->logRequest( - sprintf('[Geocoding] %s', $value), - $duration, - $this->getProviderClass(), - $results - ); - - return $results; - } - - /** - * {@inheritdoc} - */ - public function reverse($latitude, $longitude) - { - if (null === $this->logger) { - return parent::reverse($latitude, $longitude); - } - - $startTime = microtime(true); - $results = parent::reverse($latitude, $longitude); - $duration = (microtime(true) - $startTime) * 1000; - - $value = sprintf('[Reverse geocoding] latitude: %s, longitude: %s', $latitude, $longitude); - - $this->logger->logRequest($value, $duration, $this->getProviderClass(), $results); - - return $results; - } - - protected function getProviderClass() - { - $provider = explode('\\', get_class($this->getProvider())); - - return end($provider); - } -} diff --git a/Logger/GeocoderLogger.php b/Logger/GeocoderLogger.php index 350b652f..0f89655e 100644 --- a/Logger/GeocoderLogger.php +++ b/Logger/GeocoderLogger.php @@ -9,9 +9,9 @@ */ namespace Bazinga\Bundle\GeocoderBundle\Logger; +use Geocoder\Collection; +use Geocoder\Location; use Psr\Log\LoggerInterface; -use Geocoder\Model\AddressCollection; -use Geocoder\Model\Address; /** * @author Michal Dabrowski @@ -21,12 +21,12 @@ class GeocoderLogger /** * @var LoggerInterface */ - protected $logger; + private $logger; /** * @var array */ - protected $requests = array(); + private $requests = array(); /** * @param LoggerInterface $logger @@ -40,17 +40,16 @@ public function __construct(LoggerInterface $logger = null) * @param string $value value to geocode * @param float $duration geocoding duration * @param string $providerClass Geocoder provider class name - * @param AddressCollection $results + * @param Collection $results */ - public function logRequest($value, $duration, $providerClass, AddressCollection $results) + public function logRequest(string $value, float $duration, string $providerClass, Collection $results) { if (null !== $this->logger) { $this->logger->info(sprintf('%s %0.2f ms (%s)', $value, $duration, $providerClass)); } $data = array(); - - /** @var Address $result */ + /** @var Location $result */ foreach ($results as $result) { $data[] = $result->toArray(); } diff --git a/Provider/Cache.php b/Provider/Cache.php deleted file mode 100644 index 659d25eb..00000000 --- a/Provider/Cache.php +++ /dev/null @@ -1,115 +0,0 @@ - - */ -class Cache extends AbstractProvider implements Provider -{ - /** - * @var Cache - */ - private $cache; - - /** - * @var Provider - */ - private $provider; - - /** - * @var int - */ - private $lifetime; - - /** - * @var string|null - */ - private $locale; - - /** - * @var int - */ - private $maxResults = Provider::MAX_RESULTS; - - /** - * Constructor. - * - * @param DoctrineCache $cache The cache interface - * @param Provider $provider The fallback provider - * @param int $lifetime The cache lifetime - * @param string $locale - */ - public function __construct(DoctrineCache $cache, Provider $provider, $lifetime = 0, $locale = null) - { - parent::__construct(); - - $this->cache = $cache; - $this->provider = $provider; - $this->lifetime = $lifetime; - $this->locale = $locale; - } - - /** - * {@inheritdoc} - */ - public function geocode($address) - { - $key = 'geocoder_'.sha1($this->locale.$address); - - if (false !== $data = $this->cache->fetch($key)) { - return unserialize($data); - } - - $data = $this->provider->geocode($address); - $this->cache->save($key, serialize($data), $this->lifetime); - - return $data; - } - - /** - * {@inheritdoc} - */ - public function reverse($latitude, $longitude) - { - $key = 'geocoder_'.sha1($this->locale.$latitude.$longitude); - - if (false !== $data = $this->cache->fetch($key)) { - return unserialize($data); - } - - $data = $this->provider->reverse($latitude, $longitude); - $this->cache->save($key, serialize($data), $this->lifetime); - - return $data; - } - - /** - * {@inheritdoc} - */ - public function getName() - { - return 'cache'; - } - - /** - * {@inheritdoc} - */ - public function setMaxResults($maxResults) - { - $this->maxResults = $maxResults; - - return $this; - } -} diff --git a/ProviderFactory/AbstractFactory.php b/ProviderFactory/AbstractFactory.php new file mode 100644 index 00000000..fd630183 --- /dev/null +++ b/ProviderFactory/AbstractFactory.php @@ -0,0 +1,93 @@ + + */ +abstract class AbstractFactory implements ProviderFactoryInterface +{ + protected static $dependencies = []; + + /** + * @param array $config + * + * @return Provider + */ + abstract protected function getProvider(array $config); + + /** + * {@inheritdoc} + */ + public function createProvider(array $options = []) + { + $this->verifyDependencies(); + + $resolver = new OptionsResolver(); + static::configureOptionResolver($resolver); + $config = $resolver->resolve($options); + + return $this->getProvider($config); + } + + /** + * {@inheritdoc} + */ + public static function validate(array $options, $providerName) + { + static::verifyDependencies(); + + $resolver = new OptionsResolver(); + static::configureOptionResolver($resolver); + + try { + $resolver->resolve($options); + } catch (\Exception $e) { + $message = sprintf( + 'Error while configure provider "%s". Verify your configuration at "bazinga_geocoder.providers.%s.options". %s', + $providerName, + $providerName, + $e->getMessage() + ); + + throw new InvalidConfigurationException($message, $e->getCode(), $e); + } + } + + /** + * Make sure that we have the required class and throw and exception if we don't. + * + * @throws \LogicException + */ + protected static function verifyDependencies() + { + foreach (static::$dependencies as $dependency) { + if (!class_exists($dependency['requiredClass'])) { + throw new \LogicException( + sprintf( + 'You must install the "%s" package to use the "%s" factory.', + $dependency['packageName'], + static::class + ) + ); + } + } + } + + /** + * By default we do not have any options to configure. A factory should override this function and confgure + * the options resolver. + * + * @param OptionsResolver $resolver + */ + protected static function configureOptionResolver(OptionsResolver $resolver) + { + } +} \ No newline at end of file diff --git a/ProviderFactory/ChainFactory.php b/ProviderFactory/ChainFactory.php new file mode 100644 index 00000000..dec7cdf3 --- /dev/null +++ b/ProviderFactory/ChainFactory.php @@ -0,0 +1,44 @@ +, Tobias Nyholm + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace Bazinga\Bundle\GeocoderBundle\ProviderFactory; + +use Geocoder\Provider\Chain\Chain; +use Symfony\Component\OptionsResolver\OptionsResolver; + +/** + * @author Tobias Nyholm + */ +final class ChainFactory extends AbstractFactory +{ + protected static $dependencies = [ + ['requiredClass' => Chain::class, 'packageName' => 'geocoder-php/chain-provider'], + ]; + + /** + * {@inheritdoc} + */ + protected function getProvider(array $config) + { + return new Chain($config['services']); + } + + /** + * {@inheritdoc} + */ + protected static function configureOptionResolver(OptionsResolver $resolver) + { + parent::configureOptionResolver($resolver); + + $resolver->setRequired('services'); + $resolver->setAllowedTypes('services', ['array']); + } +} diff --git a/ProviderFactory/GoogleMapsFactory.php b/ProviderFactory/GoogleMapsFactory.php new file mode 100644 index 00000000..e2b3d8c9 --- /dev/null +++ b/ProviderFactory/GoogleMapsFactory.php @@ -0,0 +1,35 @@ + GoogleMaps::class, 'packageName' => 'geocoder-php/google-maps-provider'], + ]; + + protected function getProvider(array $config) + { + $httplug = $config['httplug_client'] ?: HttpClientDiscovery::find(); + + return new GoogleMaps($httplug, $config['region'], $config['api_key']); + } + + protected static function configureOptionResolver(OptionsResolver $resolver) + { + $resolver->setDefaults([ + 'httplug_client' => null, + 'region' => null, + 'api_key' => null, + ]); + + $resolver->setAllowedTypes('httplug_client', [HttpClient::class, 'null']); + $resolver->setAllowedTypes('region', ['string', 'null']); + $resolver->setAllowedTypes('api_key', ['string', 'null']); + } +} diff --git a/ProviderFactory/ProviderFactoryInterface.php b/ProviderFactory/ProviderFactoryInterface.php new file mode 100644 index 00000000..69888f32 --- /dev/null +++ b/ProviderFactory/ProviderFactoryInterface.php @@ -0,0 +1,43 @@ +, Tobias Nyholm + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace Bazinga\Bundle\GeocoderBundle\ProviderFactory; + +use Geocoder\Provider\Provider; + +/** + * @author Tobias Nyholm + */ +interface ProviderFactoryInterface +{ + /** + * @param array $options + * + * @return Provider + */ + public function createProvider(array $options = []); + + /** + * Make sure the options are valid and the dependencies are met. + * + * @param array $options the options the user has provided + * @param string $providerName the name the user has chosen for this provider + * + * @throws \LogicException If the factory has missing dependencies + * @throws \Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException If an option name is undefined + * @throws \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException If an option doesn't fulfill the specified validation rules + * @throws \Symfony\Component\OptionsResolver\Exception\MissingOptionsException If a required option is missing + * @throws \Symfony\Component\OptionsResolver\Exception\OptionDefinitionException If there is a cyclic dependency between lazy options and/or normalizers + * @throws \Symfony\Component\OptionsResolver\Exception\NoSuchOptionException If a lazy option reads an unavailable option + * @throws \Symfony\Component\OptionsResolver\Exception\AccessException If called from a lazy option or normalizer + */ + public static function validate(array $options, $providerName); +} diff --git a/Resources/config/profiling.yml b/Resources/config/profiling.yml new file mode 100644 index 00000000..2d601eed --- /dev/null +++ b/Resources/config/profiling.yml @@ -0,0 +1,7 @@ +services: + Bazinga\Bundle\GeocoderBundle\DataCollector\GeocoderDataCollector: + class: Bazinga\Bundle\GeocoderBundle\DataCollector\GeocoderDataCollector + arguments: ['@Bazinga\Bundle\GeocoderBundle\Logger\GeocoderLogger'] + public: false + tags: + - { name: data_collector, template: "BazingaGeocoderBundle:Collector:geocoder", id: "geocoder" } diff --git a/Resources/config/services.xml b/Resources/config/services.xml deleted file mode 100644 index 4f6b2df1..00000000 --- a/Resources/config/services.xml +++ /dev/null @@ -1,91 +0,0 @@ - - - - - Geocoder\ProviderAggregator - Bazinga\Bundle\GeocoderBundle\Geocoder\LoggableGeocoder - Ivory\HttpAdapter\CurlHttpAdapter - Geocoder\Provider\BingMaps - Geocoder\Provider\FreeGeoIp - Geocoder\Provider\GoogleMaps - Geocoder\Provider\ArcGISOnline - Geocoder\Provider\GoogleMapsBusiness - Geocoder\Provider\HostIp - Geocoder\Provider\IpInfoDb - Geocoder\Provider\Yahoo - Geocoder\Provider\OpenStreetMap - Geocoder\Provider\Geoip - Geocoder\Provider\MapQuest - Geocoder\Provider\Yandex - Geocoder\Provider\GeoIPs - Geocoder\Provider\GeoPlugin - Geocoder\Provider\MaxMind - Geocoder\Provider\MaxMindBinary - Geocoder\Provider\OpenCage - Bazinga\Bundle\GeocoderBundle\Provider\Cache - Geocoder\Provider\Chain - Geocoder\Provider\TomTom - - - Bazinga\Bundle\GeocoderBundle\Logger\GeocoderLogger - - Bazinga\Bundle\GeocoderBundle\DataCollector\GeocoderDataCollector - - Bazinga\Bundle\GeocoderBundle\EventListener\FakeRequestListener - - Bazinga\Bundle\GeocoderBundle\DumperManager - Geocoder\Dumper\GeoJson - Geocoder\Dumper\Gpx - Geocoder\Dumper\Kml - Geocoder\Dumper\Wkb - Geocoder\Dumper\Wkt - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Resources/config/services.yml b/Resources/config/services.yml new file mode 100644 index 00000000..479026c2 --- /dev/null +++ b/Resources/config/services.yml @@ -0,0 +1,28 @@ +services: + Geocoder\Dumper\: + resource: '%kernel.root_dir%/../vendor/willdurand/geocoder/Dumper' + public: true + tags: ['bazinga_geocoder.dumper'] + + Bazinga\Bundle\GeocoderBundle\ProviderFactory\: + resource: '../../ProviderFactory' + public: false + + Geocoder\ProviderAggregator: + class: Geocoder\ProviderAggregator + + bazinga_geocoder.geocoder: + alias: "Geocoder\\ProviderAggregator" + + geocoder: + alias: "Geocoder\\ProviderAggregator" + + Bazinga\Bundle\GeocoderBundle\Logger\GeocoderLogger: + class: Bazinga\Bundle\GeocoderBundle\Logger\GeocoderLogger + arguments: ['@?logger'] + + Bazinga\Bundle\GeocoderBundle\EventListener\FakeRequestListener: + class: Bazinga\Bundle\GeocoderBundle\EventListener\FakeRequestListener + arguments: ['127.0.0.1'] + tags: + - { name: kernel.event_listener, event: "kernel.request", method: "onKernelRequest" } diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 1970c09b..973f6dbb 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -26,15 +26,11 @@ to your `composer.json` file: ```json { "require": { - "willdurand/geocoder-bundle": "@stable" + "willdurand/geocoder-bundle": "^5.0" } } ``` -**Protip:** you should browse the -[`willdurand/geocoder-bundle`](https://packagist.org/packages/willdurand/geocoder-bundle) -page to choose a stable version to use, avoid the `@stable` meta constraint. - Register the bundle in `app/AppKernel.php`: ```php diff --git a/Resources/meta/LICENSE b/Resources/meta/LICENSE deleted file mode 100644 index 71b39b91..00000000 --- a/Resources/meta/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2011-2013 William Durand - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is furnished -to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/Tests/Command/GeocodeCommandTest.php b/Tests/Command/GeocodeCommandTest.php index a9e210fc..b7ae2116 100644 --- a/Tests/Command/GeocodeCommandTest.php +++ b/Tests/Command/GeocodeCommandTest.php @@ -28,9 +28,16 @@ class GeocodeCommandTest extends \PHPUnit_Framework_TestCase public function testExecute() { $coordinates = new Coordinates(1, 2); - $bounds = new Bounds(1, 2, 3, 4); $country = new Country('France', 'FR'); - $address = new Address($coordinates, $bounds, '10', 'rue Gambetta', '75020', 'Paris', null, null, $country); + $address = Address::createFromArray([ + 'coordinates' => $coordinates, + 'streetNumber'=>'10', + 'streetName'=> 'rue Gambetta', + 'zipCode' => '75020', + 'locality'=> 'Paris', + 'countryName' => $country->getName(), + 'countryCode' => $country->getCode(), + ]); $geocoder = $this->getMockBuilder('Geocoder\\ProviderAggregator')->getMock(); $geocoder->expects($this->once()) diff --git a/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php b/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php deleted file mode 100644 index 537f3061..00000000 --- a/Tests/DependencyInjection/BazingaGeocoderExtensionTest.php +++ /dev/null @@ -1,121 +0,0 @@ - - */ -class BazingaGeocoderExtensionTest extends \PHPUnit_Framework_TestCase -{ - public function testLoad() - { - $configs = Yaml::parse(file_get_contents(__DIR__.'/Fixtures/config.yml')); - unset($configs['bazinga_geocoder']['default_provider']); - - $container = new ContainerBuilder(); - $extension = new BazingaGeocoderExtension(); - - $container->setParameter('fixtures_dir', __DIR__.'/Fixtures'); - - $container->set('doctrine.apc.cache', new ArrayCache()); - - $container->addCompilerPass(new AddDumperPass()); - $container->addCompilerPass(new AddProvidersPass()); - $container->addCompilerPass(new LoggablePass()); - - $extension->load($configs, $container); - $container->compile(); - - $this->assertInstanceOf( - 'Bazinga\Bundle\GeocoderBundle\EventListener\FakeRequestListener', - $container->get('bazinga_geocoder.event_listener.fake_request') - ); - $this->assertNotNull( - $container->get('bazinga_geocoder.event_listener.fake_request')->getFakeIp() - ); - - $dumperManager = $container->get('bazinga_geocoder.dumper_manager'); - - foreach (array('geojson', 'gpx', 'kmp', 'wkb', 'wkt') as $name) { - $this->assertTrue($dumperManager->has($name)); - } - - $this->assertFalse($container->hasParameter('bazinga_geocoder.default_provider')); - - $geocoder = $container->get('bazinga_geocoder.geocoder'); - $providers = $geocoder->getProviders(); - foreach (array( - 'bing_maps' => 'Geocoder\\Provider\\BingMaps', - 'cache' => 'Bazinga\\Bundle\\GeocoderBundle\\Provider\\Cache', - 'ip_info_db' => 'Geocoder\\Provider\\IpInfoDb', - 'google_maps' => 'Geocoder\\Provider\\GoogleMaps', - 'arcgis_online' => 'Geocoder\\Provider\\ArcGISOnline', - 'google_maps_business' => 'Geocoder\\Provider\\GoogleMapsBusiness', - 'openstreetmap' => 'Geocoder\\Provider\\OpenStreetMap', - 'host_ip' => 'Geocoder\\Provider\\HostIp', - 'free_geo_ip' => 'Geocoder\\Provider\\FreeGeoIp', - 'map_quest' => 'Geocoder\\Provider\\MapQuest', - 'yandex' => 'Geocoder\\Provider\\Yandex', - 'geo_ips' => 'Geocoder\\Provider\\GeoIps', - 'geo_plugin' => 'Geocoder\\Provider\\GeoPlugin', - 'maxmind' => 'Geocoder\\Provider\\Maxmind', - 'chain' => 'Geocoder\\Provider\\Chain', - 'maxmind_binary' => 'Geocoder\\Provider\\MaxmindBinary', - 'opencage' => 'Geocoder\\Provider\\OpenCage', - ) as $name => $class) { - $this->assertInstanceOf($class, $providers[$name], sprintf('-> Assert that %s is instance of %s', $name, $class)); - } - } - - public function testDefaultProvider() - { - $configs = Yaml::parse(file_get_contents(__DIR__.'/Fixtures/config.yml')); - $container = new ContainerBuilder(); - $extension = new BazingaGeocoderExtension(); - - $container->setParameter('fixtures_dir', __DIR__.'/Fixtures'); - - $container->set('doctrine.apc.cache', new ArrayCache()); - - $container->addCompilerPass(new AddProvidersPass()); - $extension->load($configs, $container); - - $container->compile(); - - $this->assertEquals('bing_maps', $container->getParameter('bazinga_geocoder.default_provider')); - } - - public function testLoadingFakeIpOldWay() - { - $configs = Yaml::parse(file_get_contents(__DIR__.'/Fixtures/old_fake_ip.yml')); - $container = new ContainerBuilder(); - $extension = new BazingaGeocoderExtension(); - - $container->setParameter('fixtures_dir', __DIR__.'/Fixtures'); - - $container->set('doctrine.apc.cache', new ArrayCache()); - - $container->addCompilerPass(new AddDumperPass()); - $container->addCompilerPass(new AddProvidersPass()); - - $extension->load($configs, $container); - $container->compile(); - - $this->assertInstanceOf( - 'Bazinga\Bundle\GeocoderBundle\EventListener\FakeRequestListener', - $container->get('bazinga_geocoder.event_listener.fake_request') - ); - - $this->assertNotNull( - $container->get('bazinga_geocoder.event_listener.fake_request')->getFakeIp() - ); - } -} diff --git a/Tests/DependencyInjection/Compiler/AddDumperPassTest.php b/Tests/DependencyInjection/Compiler/AddDumperPassTest.php deleted file mode 100644 index 99c1175c..00000000 --- a/Tests/DependencyInjection/Compiler/AddDumperPassTest.php +++ /dev/null @@ -1,39 +0,0 @@ - - */ -class AddDumperPassTest extends \PHPUnit_Framework_TestCase -{ - public function testProcess() - { - $builder = new ContainerBuilder(); - $builder->setDefinition('bazinga_geocoder.dumper_manager', new Definition('Bazinga\Bundle\GeocoderBundle\DumperManager')); - - $dumper = new Definition('Geocoder\Dumper\GeoJson'); - $dumper->addTag('bazinga_geocoder.dumper', array('alias' => 'geojson')); - - $builder->setDefinition('bazinga_geocoder.dumper.geojson', $dumper); - - $compiler = new AddDumperPass(); - $compiler->process($builder); - - $manager = $builder->get('bazinga_geocoder.dumper_manager'); - - $this->assertTrue($manager->has('geojson')); - } - - public function testProcessWithoutManager() - { - $builder = new ContainerBuilder(); - $compiler = new AddDumperPass(); - - $this->assertNull($compiler->process($builder)); - } -} diff --git a/Tests/DependencyInjection/ConfigurationTest.php b/Tests/DependencyInjection/ConfigurationTest.php index 89162209..25f28155 100644 --- a/Tests/DependencyInjection/ConfigurationTest.php +++ b/Tests/DependencyInjection/ConfigurationTest.php @@ -15,7 +15,7 @@ public function testGetConfigTreeBuilder() { $config = Yaml::parse(file_get_contents(__DIR__.'/Fixtures/config.yml')); - $configuration = new Configuration(); + $configuration = new Configuration(true); $treeBuilder = $configuration->getConfigTreeBuilder(); $processor = new Processor(); diff --git a/Tests/DependencyInjection/Fixtures/config.yml b/Tests/DependencyInjection/Fixtures/config.yml index 0b376990..f5a8c257 100644 --- a/Tests/DependencyInjection/Fixtures/config.yml +++ b/Tests/DependencyInjection/Fixtures/config.yml @@ -1,49 +1,71 @@ bazinga_geocoder: - default_provider: bing_maps fake_ip: ip: 33.33.33.11 priority: 128 - adapter: bazinga_geocoder.geocoder.default_adapter providers: bing_maps: + factory: Bazinga\Bundle\GeocoderBundle\ProviderFactory\GoogleMapsFactory + options: api_key: 123 locale: en_US - cache: - adapter: doctrine.apc.cache - provider: bing_maps - locale: en_US - lifetime: 86400 ip_info_db: + factory: Bazinga\Bundle\GeocoderBundle\ProviderFactory\GoogleMapsFactory + options: api_key: 123 - arcgis_online: ~ + arcgis_online: + factory: Bazinga\Bundle\GeocoderBundle\ProviderFactory\GoogleMapsFactory + options: google_maps: + factory: Bazinga\Bundle\GeocoderBundle\ProviderFactory\GoogleMapsFactory + options: locale: en_US region: en_US api_key: 123 google_maps_business: + factory: Bazinga\Bundle\GeocoderBundle\ProviderFactory\GoogleMapsFactory + options: client_id: 123 api_key: 123 locale: en_US region: en_US openstreetmap: + factory: Bazinga\Bundle\GeocoderBundle\ProviderFactory\GoogleMapsFactory + options: locale: en_US - host_ip: ~ + host_ip: + factory: Bazinga\Bundle\GeocoderBundle\ProviderFactory\GoogleMapsFactory # geoip: ~ - free_geo_ip: ~ + free_geo_ip: + factory: Bazinga\Bundle\GeocoderBundle\ProviderFactory\GoogleMapsFactory mapquest: + factory: Bazinga\Bundle\GeocoderBundle\ProviderFactory\GoogleMapsFactory + options: api_key: 123 yandex: + factory: Bazinga\Bundle\GeocoderBundle\ProviderFactory\GoogleMapsFactory + options: locale: en-US toponym: locality geo_ips: + factory: Bazinga\Bundle\GeocoderBundle\ProviderFactory\GoogleMapsFactory + options: api_key: 123 - geo_plugin: ~ + geo_plugin: + factory: Bazinga\Bundle\GeocoderBundle\ProviderFactory\GoogleMapsFactory maxmind: + factory: Bazinga\Bundle\GeocoderBundle\ProviderFactory\GoogleMapsFactory + options: api_key: 123 maxmind_binary: + factory: Bazinga\Bundle\GeocoderBundle\ProviderFactory\GoogleMapsFactory + options: binary_file: "%fixtures_dir%/maxmind.dat" opencage: + factory: Bazinga\Bundle\GeocoderBundle\ProviderFactory\GoogleMapsFactory + options: locale: en_US api_key: 123 chain: + factory: Bazinga\Bundle\GeocoderBundle\ProviderFactory\ChainFactory + options: providers: [free_geo_ip, host_ip] diff --git a/Tests/DependencyInjection/Fixtures/old_fake_ip.yml b/Tests/DependencyInjection/Fixtures/old_fake_ip.yml deleted file mode 100644 index eb475972..00000000 --- a/Tests/DependencyInjection/Fixtures/old_fake_ip.yml +++ /dev/null @@ -1,2 +0,0 @@ -bazinga_geocoder: - fake_ip: 33.33.33.01 diff --git a/Tests/Doctrine/ORM/GeocoderListenerTest.php b/Tests/Doctrine/ORM/GeocoderListenerTest.php index 1fdab420..b8c3df07 100644 --- a/Tests/Doctrine/ORM/GeocoderListenerTest.php +++ b/Tests/Doctrine/ORM/GeocoderListenerTest.php @@ -10,8 +10,9 @@ use Doctrine\ORM\EntityManager; use Doctrine\ORM\Tools\SchemaTool; use Doctrine\Tests\OrmTestCase; -use Ivory\HttpAdapter\CurlHttpAdapter; -use Geocoder\Provider\GoogleMaps; +use Geocoder\Provider\GoogleMaps\GoogleMaps; +use Http\Client\Curl\Client; + /** * @author Markus Bachmann @@ -23,6 +24,11 @@ class GeocoderListenerTest extends OrmTestCase */ private $em; + /** + * @var GeocoderListener + */ + private $listener; + protected function setUp() { AnnotationRegistry::registerLoader('class_exists'); @@ -40,7 +46,7 @@ protected function setUp() $driver = new AnnotationDriver($reader); - $geocoder = new GoogleMaps(new CurlHttpAdapter()); + $geocoder = new GoogleMaps(new Client()); $this->listener = new GeocoderListener($geocoder, $driver); diff --git a/Tests/DumperManagerTest.php b/Tests/DumperManagerTest.php deleted file mode 100644 index 76798ea4..00000000 --- a/Tests/DumperManagerTest.php +++ /dev/null @@ -1,64 +0,0 @@ - - */ -class DumperManagerTest extends \PHPUnit_Framework_TestCase -{ - /** - * @var DumperManager - */ - private $manager; - - protected function setup() - { - $this->manager = new DumperManager(); - } - - public function testSet() - { - $this->assertNull($this->manager->set('test', $this->getMockBuilder('Geocoder\\Dumper\\Dumper')->getMock())); - } - - public function testGet() - { - $dumper = $this->getMockBuilder('Geocoder\\Dumper\\Dumper')->getMock(); - $this->manager->set('test', $dumper); - - $this->assertEquals($dumper, $this->manager->get('test')); - } - - /** - * @expectedException \RuntimeException - */ - public function testGetNotExistDumper() - { - $this->manager->get('not-exist'); - } - - public function testHas() - { - $this->assertFalse($this->manager->has('test')); - $this->manager->set('test', $this->getMockBuilder('Geocoder\\Dumper\\Dumper')->getMock()); - $this->assertTrue($this->manager->has('test')); - } - - public function testRemove() - { - $this->manager->set('test', $this->getMockBuilder('Geocoder\\Dumper\\Dumper')->getMock()); - $this->manager->remove('test'); - $this->assertFalse($this->manager->has('test')); - } - - /** - * @expectedException \RuntimeException - */ - public function testRemoveNotExistDumper() - { - $this->manager->remove('not-exist'); - } -} diff --git a/Tests/Logger/GeocoderLoggerTest.php b/Tests/Logger/GeocoderLoggerTest.php index b327b6b2..9bf090be 100644 --- a/Tests/Logger/GeocoderLoggerTest.php +++ b/Tests/Logger/GeocoderLoggerTest.php @@ -36,16 +36,39 @@ public function setUp() $this->geocoderLogger = new GeocoderLogger($logger); - $coordinates = new Coordinates(1, 2); - $bounds = new Bounds(1, 2, 3, 4); - $country = new Country('France', 'FR'); - $this->result = new Address($coordinates, $bounds, '10', 'rue Gambetta', '75020', 'Paris', null, null, $country); - - $coordinates = new Coordinates(3, 4); - $bounds = new Bounds(5, 6, 7, 8); - $country = new Country('France', 'FR'); - $otherResult = new Address($coordinates, $bounds, '3', 'avenue Secrétan', '75019', 'Paris', null, null, $country); - + $this->result = Address::createFromArray([ + 'latitude' => 1, + 'longitude' => 2, + 'bounds' => [ + 'south' => 1, + 'west' => 2, + 'north' => 3, + 'east' => 4, + ], + 'streetNumber' => '10', + 'streetName' => 'rue Gambetta', + 'locality' => 'Paris', + 'postalCode' => '75020', + 'country' => 'France', + 'countryCode' => 'FR', + ]); + + $otherResult = Address::createFromArray([ + 'latitude' => 3, + 'longitude' => 4, + 'bounds' => [ + 'south' => 5, + 'west' => 6, + 'north' => 7, + 'east' => 8, + ], + 'streetNumber' => '3', + 'streetName' => 'avenue Secrétan', + 'locality' => 'Paris', + 'postalCode' => '75019', + 'country' => 'France', + 'countryCode' => 'FR', + ]); $this->results = new AddressCollection(array($this->result, $otherResult)); } @@ -72,7 +95,16 @@ public function testLogResults() $this->assertSame($request['value'], 'copenhagen'); $this->assertSame($request['duration'], 0.123); $this->assertSame($request['providerClass'], 'FooProvider'); - $this->assertSame($request['result'], '[{"latitude":1,"longitude":2,"bounds":{"south":1,"west":2,"north":3,"east":4},"streetNumber":"10","streetName":"rue Gambetta","postalCode":"75020","locality":"Paris","subLocality":null,"adminLevels":[],"country":"France","countryCode":"FR","timezone":null},{"latitude":3,"longitude":4,"bounds":{"south":5,"west":6,"north":7,"east":8},"streetNumber":"3","streetName":"avenue Secr\u00e9tan","postalCode":"75019","locality":"Paris","subLocality":null,"adminLevels":[],"country":"France","countryCode":"FR","timezone":null}]'); + + $this->assertContains('"latitude":1', $request['result']); + $this->assertContains('"longitude":2', $request['result']); + $this->assertContains('"streetNumber":"10"', $request['result']); + $this->assertContains('"streetName":"rue Gambetta"', $request['result']); + $this->assertContains('"postalCode":"75020"', $request['result']); + $this->assertContains('"locality":"Paris"', $request['result']); + $this->assertContains('"locality":"Paris"', $request['result']); + $this->assertContains('"country":"France"', $request['result']); + $this->assertContains('"countryCode":"FR"', $request['result']); $this->assertCount(2, json_decode($request['result'])); } @@ -104,6 +136,15 @@ public function testLogRequestsWithoutLogger() $this->assertSame($request['value'], 'copenhagen'); $this->assertSame($request['duration'], 0.123); $this->assertSame($request['providerClass'], 'FooProvider'); - $this->assertSame($request['result'], '[{"latitude":1,"longitude":2,"bounds":{"south":1,"west":2,"north":3,"east":4},"streetNumber":"10","streetName":"rue Gambetta","postalCode":"75020","locality":"Paris","subLocality":null,"adminLevels":[],"country":"France","countryCode":"FR","timezone":null},{"latitude":3,"longitude":4,"bounds":{"south":5,"west":6,"north":7,"east":8},"streetNumber":"3","streetName":"avenue Secr\u00e9tan","postalCode":"75019","locality":"Paris","subLocality":null,"adminLevels":[],"country":"France","countryCode":"FR","timezone":null}]'); + + $this->assertContains('"latitude":1', $request['result']); + $this->assertContains('"longitude":2', $request['result']); + $this->assertContains('"streetNumber":"10"', $request['result']); + $this->assertContains('"streetName":"rue Gambetta"', $request['result']); + $this->assertContains('"postalCode":"75020"', $request['result']); + $this->assertContains('"locality":"Paris"', $request['result']); + $this->assertContains('"locality":"Paris"', $request['result']); + $this->assertContains('"country":"France"', $request['result']); + $this->assertContains('"countryCode":"FR"', $request['result']); } } diff --git a/Tests/Provider/CacheProviderTest.php b/Tests/Provider/CacheProviderTest.php deleted file mode 100644 index d641320d..00000000 --- a/Tests/Provider/CacheProviderTest.php +++ /dev/null @@ -1,86 +0,0 @@ - - */ -class CacheProviderTest extends \PHPUnit_Framework_TestCase -{ - public function testGeocode() - { - $address = 'Paris, France'; - $coordinates = array('lat' => 48.857049,'lng' => 2.35223); - $cacheKey = 'geocoder_'.sha1($address); - - $delegate = $this->getMockBuilder('Geocoder\\Provider\\Provider')->getMock(); - $delegate->expects($this->once()) - ->method('geocode') - ->with($address) - ->will($this->returnValue($coordinates)); - - $cache = $this->getMockBuilder('Doctrine\\Common\\Cache\\Cache')->getMock(); - $cache->expects($this->once()) - ->method('fetch') - ->with($cacheKey) - ->will($this->returnValue(false)); - - $cache->expects($this->once()) - ->method('save') - ->with($cacheKey, serialize($coordinates), 0); - - $provider = new Cache($cache, $delegate); - $this->assertEquals($coordinates, $provider->geocode($address)); - } - - public function testCachedGeocode() - { - $address = 'Paris, France'; - $coordinates = array('lat' => 48.857049,'lng' => 2.35223); - $cacheKey = 'geocoder_'.sha1($address); - - $delegate = $this->getMockBuilder('Geocoder\\Provider\\Provider')->getMock(); - $delegate->expects($this->once()) - ->method('geocode') - ->with($address) - ->will($this->returnValue($coordinates)); - - $provider = new Cache($cache = new ArrayCache(), $delegate); - - $provider->geocode($address); - $provider->geocode($address); - - $this->assertTrue($cache->contains($cacheKey)); - } - - public function testReverse() - { - $coordinates = array('lat' => 48.857049, 'lon' => 2.35223); - - $delegate = $this->getMockBuilder('Geocoder\\Provider\\Provider')->getMock(); - $delegate->expects($this->once()) - ->method('reverse') - ->with($coordinates['lat'], $coordinates['lon']) - ->will($this->returnValue('Paris, France')); - - $cache = new ArrayCache(); - - $provider = new Cache($cache, $delegate); - - $this->assertEquals('Paris, France', $provider->reverse($coordinates['lat'], $coordinates['lon'])); - $this->assertEquals('Paris, France', $provider->reverse($coordinates['lat'], $coordinates['lon'])); - } - - public function testGetName() - { - $delegate = $this->getMockBuilder('Geocoder\\Provider\\Provider')->getMock(); - $cache = $this->getMockBuilder('Doctrine\\Common\\Cache\\Cache')->getMock(); - - $provider = new Cache($cache, $delegate); - - $this->assertEquals('cache', $provider->getName()); - } -} diff --git a/Tests/bootstrap.php b/Tests/bootstrap.php index be9b3157..6e76f23b 100644 --- a/Tests/bootstrap.php +++ b/Tests/bootstrap.php @@ -10,4 +10,6 @@ require_once __DIR__.'/../vendor/geoip/geoip/src/geoip.inc'; require_once __DIR__.'/../vendor/geoip/geoip/src/geoipcity.inc'; +Http\Discovery\ClassDiscovery::prependStrategy(\Nyholm\Psr7\Httplug\DiscoveryStrategy::class); + $loader->add('Doctrine\Tests', __DIR__.'/../vendor/doctrine/orm/tests'); diff --git a/composer.json b/composer.json index c9ee0b4e..a21913b1 100644 --- a/composer.json +++ b/composer.json @@ -11,27 +11,35 @@ } ], "require": { - "symfony/framework-bundle": "~2.1|~3.0", - "willdurand/geocoder": "~3.1", - "symfony/console": "~2.1|~3.0" + "php": "^7.0", + "symfony/framework-bundle": "^3.3", + "willdurand/geocoder": "^4.0", + "symfony/console": "^3.3" }, "require-dev": { - "php": ">=5.4", - "symfony/yaml": "~2.1|~3.0", + "phpunit/phpunit": "^5.7", + "symfony/yaml": "^3.2", "geoip/geoip": "~1.17", "doctrine/cache": "~1.3", - "doctrine/orm": "~2.3" + "doctrine/orm": "~2.3", + "php-http/message": "^1.5", + "geocoder-php/google-maps-provider": "^4.0", + "php-http/curl-client": "^1.7", + "nyholm/psr7": "^0.2.2" }, "conflict": { "willdurand/geocoder": "3.2" }, "autoload": { - "psr-0": { "Bazinga\\Bundle\\GeocoderBundle": "" } + "psr-4": { + "Bazinga\\Bundle\\GeocoderBundle\\": "" + } }, - "target-dir": "Bazinga/Bundle/GeocoderBundle", + "minimum-stability": "beta", + "prefer-stable": true, "extra": { "branch-alias": { - "dev-master": "4.1-dev" + "dev-master": "5.0-dev" } } } From 22df444f5af70cee15ac39f4d4171e5b57fa8fd3 Mon Sep 17 00:00:00 2001 From: Tobias Nyholm Date: Sat, 15 Jul 2017 00:37:19 +0200 Subject: [PATCH 060/235] Added tests, bugfixes and profiler (#131) * Added tests and fixed some bugs * More tests and bugfixes * Updated deps * Removed stuff not used * Allow us to test on symfony 4.0 * Typo * Use PHPunit 6 * Working on the profiler page * Fixed profiler * Minor * Using older PHPUnit version * added a word * Text fix * Reduce the number of travis build --- .travis.yml | 20 ++- DataCollector/GeocoderDataCollector.php | 72 +++++--- DataCollector/ProfilingProvider.php | 65 ++++--- .../BazingaGeocoderExtension.php | 18 +- DependencyInjection/Compiler/ProfilerPass.php | 5 +- Logger/GeocoderLogger.php | 74 -------- Resources/config/profiling.yml | 1 - Resources/config/services.yml | 19 +-- Resources/views/Collector/geocoder.html.twig | 158 +++++++++++------- Tests/Command/GeocodeCommandTest.php | 3 +- .../DependencyInjection/ConfigurationTest.php | 3 +- .../EventListener/FakeRequestListenerTest.php | 3 +- Tests/Doctrine/ORM/GeocoderListenerTest.php | 14 ++ Tests/Functional/BundleInitializationTest.php | 63 +++++++ Tests/Functional/Helper/CacheHelper.php | 56 +++++++ Tests/Functional/config/cache.yml | 13 ++ Tests/Functional/config/simple.yml | 7 + Tests/Logger/GeocoderLoggerTest.php | 150 ----------------- Tests/Mapping/Driver/AnnotationDriverTest.php | 3 +- Tests/bootstrap.php | 9 +- composer.json | 17 +- 21 files changed, 399 insertions(+), 374 deletions(-) delete mode 100644 Logger/GeocoderLogger.php create mode 100644 Tests/Functional/BundleInitializationTest.php create mode 100644 Tests/Functional/Helper/CacheHelper.php create mode 100644 Tests/Functional/config/cache.yml create mode 100644 Tests/Functional/config/simple.yml delete mode 100644 Tests/Logger/GeocoderLoggerTest.php diff --git a/.travis.yml b/.travis.yml index 45b415ed..28c992ed 100644 --- a/.travis.yml +++ b/.travis.yml @@ -11,18 +11,24 @@ php: - 7.1 env: + matrix: - SYMFONY_VERSION=3.3.* - - SYMFONY_VERSION=dev-master matrix: - allow_failures: - - env: SYMFONY_VERSION=dev-master + fast_finish: true + allow_failures: + - php: 7.1 + env: SYMFONY_VERSION=4.0.* + include: + - php: 7.0 + env: COMPOSER_FLAGS="--prefer-stable --prefer-lowest" SYMFONY_VERSION=3.3.* TEST_COMMAND="phpunit --coverage-text --coverage-clover=build/coverage.xml" + - php: 7.1 + env: SYMFONY_VERSION=4.0.* before_script: - - composer require symfony/framework-bundle:${SYMFONY_VERSION} --no-update - # This command must be run with `--prefer-source`, otherwise the `Doctrine\Tests\OrmTestCase` class - # won't be found. + - composer require symfony/symfony:${SYMFONY_VERSION} --no-update + # This command must be run with `--prefer-source`, otherwise the `Doctrine\Tests\OrmTestCase` class won't be found. - composer update --prefer-source script: - - phpunit --coverage-text --coverage-clover=build/coverage.xml + - phpunit diff --git a/DataCollector/GeocoderDataCollector.php b/DataCollector/GeocoderDataCollector.php index 1f16c425..81ce5762 100644 --- a/DataCollector/GeocoderDataCollector.php +++ b/DataCollector/GeocoderDataCollector.php @@ -7,9 +7,9 @@ * * @license MIT License */ + namespace Bazinga\Bundle\GeocoderBundle\DataCollector; -use Bazinga\Bundle\GeocoderBundle\Logger\GeocoderLogger; use Symfony\Component\HttpKernel\DataCollector\DataCollector; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; @@ -20,16 +20,15 @@ class GeocoderDataCollector extends DataCollector { /** - * @var GeocoderLogger + * @var ProfilingProvider[] */ - private $logger; + private $instances = []; - /** - * @param GeocoderLogger $logger - */ - public function __construct(GeocoderLogger $logger) + + public function __construct() { - $this->logger = $logger; + $this->data['queries'] = []; + $this->data['providers'] = []; } /** @@ -37,9 +36,13 @@ public function __construct(GeocoderLogger $logger) */ public function collect(Request $request, Response $response, \Exception $exception = null) { - $this->data = array( - 'requests' => $this->logger->getRequests(), - ); + foreach ($this->instances as $instance) { + foreach ($instance->getQueries() as $query) { + $query['query'] = $this->cloneVar($query['query']); + $query['result'] = $this->cloneVar($query['result']); + $this->data['queries'][] = $query; + } + } } /** @@ -47,19 +50,9 @@ public function collect(Request $request, Response $response, \Exception $except * * @return array */ - public function getRequests() + public function getQueries(): array { - return $this->data['requests']; - } - - /** - * Returns the number of collected requests. - * - * @return int - */ - public function getRequestsCount() - { - return count($this->data['requests']); + return $this->data['queries']; } /** @@ -67,16 +60,45 @@ public function getRequestsCount() * * @return float */ - public function getTime() + public function getTotalDuration() { $time = 0; - foreach ($this->data['requests'] as $command) { + foreach ($this->data['queries'] as $command) { $time += $command['duration']; } return $time; } + /** + * @return array + */ + public function getProviders(): array + { + return $this->data['providers']; + } + + /** + * @param string $provider + * + * @return array + */ + public function getProviderQueries($provider):array + { + return array_filter($this->data['queries'], function ($data) use ($provider) { + return $data['providerName'] === $provider; + }); + } + + /** + * @param ProfilingProvider $instance + */ + public function addInstance(ProfilingProvider $instance) + { + $this->instances[] = $instance; + $this->data['providers'][] = $instance->getName(); + } + /** * {@inheritdoc} */ diff --git a/DataCollector/ProfilingProvider.php b/DataCollector/ProfilingProvider.php index ac975ea2..c1aac17a 100644 --- a/DataCollector/ProfilingProvider.php +++ b/DataCollector/ProfilingProvider.php @@ -2,8 +2,9 @@ namespace Bazinga\Bundle\GeocoderBundle\DataCollector; -use Bazinga\Bundle\GeocoderBundle\Logger\GeocoderLogger; use Geocoder\Collection; +use Geocoder\Exception\LogicException; +use Geocoder\Location; use Geocoder\Provider\Provider; use Geocoder\Query\GeocodeQuery; use Geocoder\Query\ReverseQuery; @@ -19,56 +20,76 @@ class ProfilingProvider implements Provider private $realProvider; /** - * @var GeocoderLogger + * @var array */ - private $logger; + private $queries = []; /** * @param Provider $realProvider - * @param GeocoderLogger $logger */ - public function __construct(Provider $realProvider, GeocoderLogger $logger) + public function __construct(Provider $realProvider) { $this->realProvider = $realProvider; - $this->logger = $logger; } public function geocodeQuery(GeocodeQuery $query): Collection { $startTime = microtime(true); try { - $results = $this->realProvider->geocodeQuery($query); + $result = $this->realProvider->geocodeQuery($query); } finally { $duration = (microtime(true) - $startTime) * 1000; - $this->logger->logRequest( - sprintf('[Geocoding] %s', $query), - $duration, - $this->getName(), - $results - ); + $this->logQuery($query, $duration, $result); } - return $results; + return $result; } public function reverseQuery(ReverseQuery $query): Collection { $startTime = microtime(true); try { - $results = $this->realProvider->reverseQuery($query); + $result = $this->realProvider->reverseQuery($query); } finally { $duration = (microtime(true) - $startTime) * 1000; - $this->logger->logRequest( - sprintf('[Geocoding] %s', $query), - $duration, - $this->getName(), - $results - ); + $this->logQuery($query, $duration, $result); } - return $results; + return $result; + } + + /** + * @param GeocodeQuery|ReverseQuery $query + * @param float $duration geocoding duration + * @param Collection $result + */ + private function logQuery($query, float $duration, Collection $result = null) + { + if ($query instanceof GeocodeQuery) { + $queryString = $query->getText(); + } elseif ($query instanceof ReverseQuery) { + $queryString = sprintf('(%s, %s)', $query->getCoordinates()->getLongitude(), $query->getCoordinates()->getLongitude()); + } else { + throw new LogicException('First parameter to ProfilingProvider::logQuery must be a query'); + } + + $this->queries[] = array( + 'query' => $query, + 'queryString' => $queryString, + 'duration' => $duration, + 'providerName' => $this->getName(), + 'result' => $result, + ); + } + + /** + * @return array + */ + public function getQueries(): array + { + return $this->queries; } public function __call($method, $args) diff --git a/DependencyInjection/BazingaGeocoderExtension.php b/DependencyInjection/BazingaGeocoderExtension.php index b796f6f4..d84cbd0f 100644 --- a/DependencyInjection/BazingaGeocoderExtension.php +++ b/DependencyInjection/BazingaGeocoderExtension.php @@ -10,6 +10,7 @@ namespace Bazinga\Bundle\GeocoderBundle\DependencyInjection; use Bazinga\Bundle\GeocoderBundle\ProviderFactory\ProviderFactoryInterface; +use Geocoder\Provider\Cache\ProviderCache; use Geocoder\Provider\Provider; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use Symfony\Component\HttpKernel\DependencyInjection\Extension; @@ -34,7 +35,7 @@ public function load(array $configs, ContainerBuilder $container) $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.yml'); - if ($config['profiling']) { + if (true === $config['profiling']['enabled']) { $loader->load('profiling.yml'); } $this->loadProviders($container, $config); @@ -88,15 +89,16 @@ private function loadProviders(ContainerBuilder $container, array $config) */ private function configureCache(ContainerBuilder $container, string $serviceId, array $providerConfig) { - if ( - (null !== $providerConfig['cache'] || null !== $providerConfig['cache_lifetime']) && - !class_exists(ProviderCache::class) - ) { - throw new \LogicException('You must install "geocoder-php/chain-provider" to use cache.'); + if (null === $providerConfig['cache'] && null === $providerConfig['cache_lifetime']) { + return; } - if (null !== $cacheServiceId = $providerConfig['cache']) { - if (!$container->has('app.cache\'')) { + if (!class_exists(ProviderCache::class)) { + throw new \LogicException('You must install "geocoder-php/cache-provider" to use cache.'); + } + + if (null === $cacheServiceId = $providerConfig['cache']) { + if (!$container->has('app.cache')) { throw new \LogicException('You need to specify a service for cache.'); } $cacheServiceId = 'app.cache'; diff --git a/DependencyInjection/Compiler/ProfilerPass.php b/DependencyInjection/Compiler/ProfilerPass.php index a9367681..7ef028b1 100644 --- a/DependencyInjection/Compiler/ProfilerPass.php +++ b/DependencyInjection/Compiler/ProfilerPass.php @@ -11,7 +11,6 @@ use Bazinga\Bundle\GeocoderBundle\DataCollector\GeocoderDataCollector; use Bazinga\Bundle\GeocoderBundle\DataCollector\ProfilingProvider; -use Bazinga\Bundle\GeocoderBundle\Logger\GeocoderLogger; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; @@ -32,13 +31,15 @@ public function process(ContainerBuilder $container) return; } + $dataCollector = $container->getDefinition(GeocoderDataCollector::class); + foreach ($container->findTaggedServiceIds('bazinga_geocoder.provider') as $providerId => $attributes) { $container->register($providerId.'.debug', ProfilingProvider::class) ->setDecoratedService($providerId) ->setArguments([ new Reference($providerId.'.debug.inner'), - new Reference(GeocoderLogger::class) ]); + $dataCollector->addMethodCall('addInstance', [new Reference($providerId)]); } } } diff --git a/Logger/GeocoderLogger.php b/Logger/GeocoderLogger.php deleted file mode 100644 index 0f89655e..00000000 --- a/Logger/GeocoderLogger.php +++ /dev/null @@ -1,74 +0,0 @@ - - */ -class GeocoderLogger -{ - /** - * @var LoggerInterface - */ - private $logger; - - /** - * @var array - */ - private $requests = array(); - - /** - * @param LoggerInterface $logger - */ - public function __construct(LoggerInterface $logger = null) - { - $this->logger = $logger; - } - - /** - * @param string $value value to geocode - * @param float $duration geocoding duration - * @param string $providerClass Geocoder provider class name - * @param Collection $results - */ - public function logRequest(string $value, float $duration, string $providerClass, Collection $results) - { - if (null !== $this->logger) { - $this->logger->info(sprintf('%s %0.2f ms (%s)', $value, $duration, $providerClass)); - } - - $data = array(); - /** @var Location $result */ - foreach ($results as $result) { - $data[] = $result->toArray(); - } - - $this->requests[] = array( - 'value' => $value, - 'duration' => $duration, - 'providerClass' => $providerClass, - 'result' => json_encode($data), - ); - } - - /** - * Returns an array of the logged requests. - * - * @return array - */ - public function getRequests() - { - return $this->requests; - } -} diff --git a/Resources/config/profiling.yml b/Resources/config/profiling.yml index 2d601eed..4b60377a 100644 --- a/Resources/config/profiling.yml +++ b/Resources/config/profiling.yml @@ -1,7 +1,6 @@ services: Bazinga\Bundle\GeocoderBundle\DataCollector\GeocoderDataCollector: class: Bazinga\Bundle\GeocoderBundle\DataCollector\GeocoderDataCollector - arguments: ['@Bazinga\Bundle\GeocoderBundle\Logger\GeocoderLogger'] public: false tags: - { name: data_collector, template: "BazingaGeocoderBundle:Collector:geocoder", id: "geocoder" } diff --git a/Resources/config/services.yml b/Resources/config/services.yml index 479026c2..72b8d7c8 100644 --- a/Resources/config/services.yml +++ b/Resources/config/services.yml @@ -1,6 +1,6 @@ services: Geocoder\Dumper\: - resource: '%kernel.root_dir%/../vendor/willdurand/geocoder/Dumper' + resource: '%kernel.project_dir%/vendor/willdurand/geocoder/Dumper' public: true tags: ['bazinga_geocoder.dumper'] @@ -11,18 +11,15 @@ services: Geocoder\ProviderAggregator: class: Geocoder\ProviderAggregator - bazinga_geocoder.geocoder: - alias: "Geocoder\\ProviderAggregator" - - geocoder: - alias: "Geocoder\\ProviderAggregator" - - Bazinga\Bundle\GeocoderBundle\Logger\GeocoderLogger: - class: Bazinga\Bundle\GeocoderBundle\Logger\GeocoderLogger - arguments: ['@?logger'] - Bazinga\Bundle\GeocoderBundle\EventListener\FakeRequestListener: class: Bazinga\Bundle\GeocoderBundle\EventListener\FakeRequestListener arguments: ['127.0.0.1'] tags: - { name: kernel.event_listener, event: "kernel.request", method: "onKernelRequest" } + + # Keep these aliases for BC purpose + bazinga_geocoder.geocoder: + alias: "Geocoder\\ProviderAggregator" + + geocoder: + alias: "Geocoder\\ProviderAggregator" diff --git a/Resources/views/Collector/geocoder.html.twig b/Resources/views/Collector/geocoder.html.twig index ed1e9410..a1c5e9d8 100644 --- a/Resources/views/Collector/geocoder.html.twig +++ b/Resources/views/Collector/geocoder.html.twig @@ -1,80 +1,110 @@ {% extends 'WebProfilerBundle:Profiler:layout.html.twig' %} {% block toolbar %} - {% set icon %} - {{ include('@BazingaGeocoder/Collector/icon.svg') }} - - {{ collector.requestscount }} - - {% endset %} - {% set text %} -
- Requests - {{ collector.requestsCount }} -
-
- Total time - {{ '%0.2f'|format(collector.time) }} ms -
- {% endset %} - {% include 'WebProfilerBundle:Profiler:toolbar_item.html.twig' with { 'link': profiler_url } %} + {% set queryLabel = collector.queries|length == 1 ? 'query' : 'queries' %} + {% if collector.queries|length > 0 %} + {% set icon %} + {{ include('@BazingaGeocoder/Collector/icon.svg') }} + {{ collector.queries|length }} + {{ queryLabel }} in + {{ collector.totalDuration|number_format }} + ms + {% endset %} + {% set text %} +
+ {{ collector.queries|length }} {{ queryLabel }} +
+
+ + + + + + + + + + {% for query in collector.queries %} + + + + + + {% endfor %} + +
ProviderQueryTime
{{ query.providerName|humanize }}{{ query.queryString }}{{ query.duration == 0 ? 'n/a' : query.duration|number_format ~ ' ms'}}
+
+ {% endset %} + + {% include 'WebProfilerBundle:Profiler:toolbar_item.html.twig' with { 'link': profiler_url } %} +{% endif %} {% endblock %} {% block menu %} - - Geocoder - Geocoder - - {{ collector.requestsCount }} - {{ '%0.0f'|format(collector.time) }} ms + {# This left-hand menu appears when using the full-screen profiler. #} + + + {{ include('@BazingaGeocoder/Collector/icon.svg') }} + + Geocoder - {% endblock %} {% block panel %} -

Geocoder Requests

- - {% if not collector.requestsCount %} -

No requests.

- {% else %} -