<?php
namespace App\Profile\EventSubscriber;
use App\Core\Service\OpenStreetMapClient;
use Pimcore\Event\DataObjectEvents;
use Pimcore\Event\Model\DataObjectEvent;
use Pimcore\Model\DataObject\Auctionhouse;
use Pimcore\Model\DataObject\Data\GeoCoordinates;
use Pimcore\Model\DataObject\Profile;
use Pimcore\Model\DataObject\Racingtrack;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class GeoLocationSubscriber implements EventSubscriberInterface
{
protected $osm;
public function __construct(OpenStreetMapClient $osm)
{
$this->osm = $osm;
}
public static function getSubscribedEvents()
{
return [
DataObjectEvents::PRE_UPDATE => 'onDataObjectPreUpdate',
];
}
public function onDataObjectPreUpdate(DataObjectEvent $event)
{
$object = $event->getObject();
$className = (new \ReflectionClass($object))->getShortName();
if (!in_array($className, ['Auctionhouse', 'Racingtrack', 'Profile'])) {
return;
}
if (!$object instanceof Auctionhouse && !$object instanceof Racingtrack && !$object instanceof Profile) {
throw new \Exception(sprintf('%s is not of type Auctionhouse, Racingtrack or Profile', get_class($object)), 1);
}
$geolocation = $this->osm->getGeolocationByAddress($object->getStreet(), $object->getCity(), $object->getPostalCode(), $object->getCountry());
if (!$geolocation) {
$object->setGeolocation(null);
} else {
$point = new GeoCoordinates($geolocation->lat, $geolocation->lon);
$object->setGeolocation($point);
}
if (method_exists($object, 'setGeolocationApprox')) {
$geolocationApprox = $this->osm->getGeolocationByPostalCode($object->getPostalCode(), $object->getCountry());
if (!$geolocationApprox) {
$object->setGeolocationApprox(null);
} else {
$point = new GeoCoordinates($geolocationApprox->lat, $geolocationApprox->lon);
$object->setGeolocationApprox($point);
}
}
}
}