|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Bazinga\Bundle\GeocoderBundle\Doctrine\ORM; |
| 4 | + |
| 5 | +use Doctrine\Common\EventSubscriber; |
| 6 | +use Doctrine\ORM\Events; |
| 7 | +use Doctrine\ORM\Event\OnFlushEventArgs; |
| 8 | + |
| 9 | +use Bazinga\Bundle\GeocoderBundle\Mapping\Driver\DriverInterface; |
| 10 | +use Geocoder\Geocoder; |
| 11 | + |
| 12 | +/** |
| 13 | + * @author Markus Bachmann <markus.bachmann@bachi.biz> |
| 14 | + */ |
| 15 | +class GeocoderListener implements EventSubscriber |
| 16 | +{ |
| 17 | + private $driver; |
| 18 | + |
| 19 | + private $geocoder; |
| 20 | + |
| 21 | + public function __construct(Geocoder $geocoder, DriverInterface $driver) |
| 22 | + { |
| 23 | + $this->driver = $driver; |
| 24 | + $this->geocoder = $geocoder; |
| 25 | + } |
| 26 | + |
| 27 | + /** |
| 28 | + * {@inheritDoc} |
| 29 | + */ |
| 30 | + public function getSubscribedEvents() |
| 31 | + { |
| 32 | + return array( |
| 33 | + Events::onFlush |
| 34 | + ); |
| 35 | + } |
| 36 | + |
| 37 | + public function onFlush(OnFlushEventArgs $args) |
| 38 | + { |
| 39 | + $em = $args->getEntityManager(); |
| 40 | + $uow = $em->getUnitOfWork(); |
| 41 | + |
| 42 | + foreach ($uow->getScheduledEntityInsertions() as $entity) { |
| 43 | + if (!$this->driver->isGeocodeable($entity)) { |
| 44 | + continue; |
| 45 | + } |
| 46 | + |
| 47 | + $this->geocodeEntity($entity); |
| 48 | + |
| 49 | + $uow->recomputeSingleEntityChangeSet( |
| 50 | + $em->getClassMetadata(get_class($entity)), |
| 51 | + $entity |
| 52 | + ); |
| 53 | + } |
| 54 | + |
| 55 | + foreach ($uow->getScheduledEntityUpdates() as $entity) { |
| 56 | + if (!$this->driver->isGeocodeable($entity)) { |
| 57 | + continue; |
| 58 | + } |
| 59 | + |
| 60 | + $this->geocodeEntity($entity); |
| 61 | + |
| 62 | + $uow->recomputeSingleEntityChangeSet( |
| 63 | + $em->getClassMetadata(get_class($entity)), |
| 64 | + $entity |
| 65 | + ); |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + private function geocodeEntity($entity) |
| 70 | + { |
| 71 | + $metadata = $this->driver->loadMetadataFromObject($entity); |
| 72 | + $address = $metadata->addressProperty->getValue($entity); |
| 73 | + $result = $this->geocoder->geocode($address); |
| 74 | + |
| 75 | + $metadata->latitudeProperty->setValue($entity, $result['latitude']); |
| 76 | + $metadata->longitudeProperty->setValue($entity, $result['longitude']); |
| 77 | + } |
| 78 | +} |
0 commit comments