src/Profile/EventSubscriber/GeoLocationSubscriber.php line 30

Open in your IDE?
  1. <?php
  2. namespace App\Profile\EventSubscriber;
  3. use App\Core\Service\OpenStreetMapClient;
  4. use Pimcore\Event\DataObjectEvents;
  5. use Pimcore\Event\Model\DataObjectEvent;
  6. use Pimcore\Model\DataObject\Auctionhouse;
  7. use Pimcore\Model\DataObject\Data\GeoCoordinates;
  8. use Pimcore\Model\DataObject\Profile;
  9. use Pimcore\Model\DataObject\Racingtrack;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. class GeoLocationSubscriber implements EventSubscriberInterface
  12. {
  13.   protected $osm;
  14.   public function __construct(OpenStreetMapClient $osm)
  15.   {
  16.     $this->osm $osm;
  17.   }
  18.   public static function getSubscribedEvents()
  19.   {
  20.     return [
  21.         DataObjectEvents::PRE_UPDATE => 'onDataObjectPreUpdate',
  22.       ];
  23.   }
  24.   public function onDataObjectPreUpdate(DataObjectEvent $event)
  25.   {
  26.     $object $event->getObject();
  27.     $className = (new \ReflectionClass($object))->getShortName();
  28.     if (!in_array($className, ['Auctionhouse''Racingtrack''Profile'])) {
  29.       return;
  30.     }
  31.     if (!$object instanceof Auctionhouse && !$object instanceof Racingtrack && !$object instanceof Profile) {
  32.       throw new \Exception(sprintf('%s is not of type Auctionhouse, Racingtrack or Profile'get_class($object)), 1);
  33.     }
  34.     $geolocation $this->osm->getGeolocationByAddress($object->getStreet(), $object->getCity(), $object->getPostalCode(), $object->getCountry());
  35.     if (!$geolocation) {
  36.       $object->setGeolocation(null);
  37.     } else {
  38.       $point = new GeoCoordinates($geolocation->lat$geolocation->lon);
  39.       $object->setGeolocation($point);
  40.     }
  41.     if (method_exists($object'setGeolocationApprox')) {
  42.       $geolocationApprox $this->osm->getGeolocationByPostalCode($object->getPostalCode(), $object->getCountry());
  43.       if (!$geolocationApprox) {
  44.         $object->setGeolocationApprox(null);
  45.       } else {
  46.         $point = new GeoCoordinates($geolocationApprox->lat$geolocationApprox->lon);
  47.         $object->setGeolocationApprox($point);
  48.       }
  49.     }
  50.   }
  51. }