<?php
declare(strict_types=0);
/*
* WellCommerce Foundation
*
* This file is part of the WellCommerce package.
*
* (c) Adam Piotrowski <adam@wellcommerce.org>, Adrian Potepa <adrian@wellcommerce.org>
*
* For the full copyright and license information,
* please view the LICENSE file that was distributed with this source code.
*/
namespace WellCommerce\Bundle\AppBundle\EventListener;
use Doctrine\ORM\EntityManagerInterface;
use Geocoder\Geocoder;
use Geocoder\Model\Address;
use Geocoder\Provider\GoogleMaps;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use WellCommerce\Bundle\AppBundle\Entity\Pos;
use WellCommerce\Bundle\AppBundle\Service\Geocoder\Configuration\GeocoderSystemConfigurator;
use WellCommerce\Bundle\AppBundle\Service\Geocoder\Provider\GeocoderProvider;
use WellCommerce\Bundle\CoreBundle\Doctrine\Event\EntityEvent;
class PosSubscriber implements EventSubscriberInterface
{
protected EntityManagerInterface $entityManager;
protected GeocoderProvider $geocoderProvider;
protected GeocoderSystemConfigurator $geocoderSystemConfigurator;
public function __construct(
EntityManagerInterface $entityManager,
GeocoderProvider $geocoderProvider,
GeocoderSystemConfigurator $geocoderSystemConfigurator
) {
$this->entityManager = $entityManager;
$this->geocoderProvider = $geocoderProvider;
$this->geocoderSystemConfigurator = $geocoderSystemConfigurator;
}
public static function getSubscribedEvents()
{
return [
'pos.pre_create' => ['onPosPreSave', 10],
'pos.pre_update' => ['onPosPreSave', 10],
];
}
public function onPosPreSave(EntityEvent $event)
{
$resource = $event->getEntity();
if ($resource instanceof Pos) {
if ($this->geocoderSystemConfigurator->isPosEnabled()) {
$geocoder = $this->getGeocoder();
$geocodeAddress = $geocoder->geocode($resource->getGeocodableAddress())->first();
if ($geocodeAddress instanceof Address) {
$coordinates = $geocodeAddress->getCoordinates();
$resource->setLongitude($coordinates->getLongitude());
$resource->setLatitude($coordinates->getLatitude());
}
}
}
}
private function getGeocoder(): Geocoder
{
return $this->geocoderProvider->createGeocoder();
}
}