src/WellCommerce/Bundle/AppBundle/EventListener/PosSubscriber.php line 51

Open in your IDE?
  1. <?php
  2. declare(strict_types=0);
  3. /*
  4.  * WellCommerce Foundation
  5.  *
  6.  * This file is part of the WellCommerce package.
  7.  *
  8.  * (c) Adam Piotrowski <adam@wellcommerce.org>, Adrian Potepa <adrian@wellcommerce.org>
  9.  *
  10.  * For the full copyright and license information,
  11.  * please view the LICENSE file that was distributed with this source code.
  12.  */
  13. namespace WellCommerce\Bundle\AppBundle\EventListener;
  14. use Doctrine\ORM\EntityManagerInterface;
  15. use Geocoder\Geocoder;
  16. use Geocoder\Model\Address;
  17. use Geocoder\Provider\GoogleMaps;
  18. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  19. use WellCommerce\Bundle\AppBundle\Entity\Pos;
  20. use WellCommerce\Bundle\AppBundle\Service\Geocoder\Configuration\GeocoderSystemConfigurator;
  21. use WellCommerce\Bundle\AppBundle\Service\Geocoder\Provider\GeocoderProvider;
  22. use WellCommerce\Bundle\CoreBundle\Doctrine\Event\EntityEvent;
  23. class PosSubscriber implements EventSubscriberInterface
  24. {
  25.     protected EntityManagerInterface     $entityManager;
  26.     protected GeocoderProvider           $geocoderProvider;
  27.     protected GeocoderSystemConfigurator $geocoderSystemConfigurator;
  28.     public function __construct(
  29.         EntityManagerInterface $entityManager,
  30.         GeocoderProvider $geocoderProvider,
  31.         GeocoderSystemConfigurator $geocoderSystemConfigurator
  32.     ) {
  33.         $this->entityManager              $entityManager;
  34.         $this->geocoderProvider           $geocoderProvider;
  35.         $this->geocoderSystemConfigurator $geocoderSystemConfigurator;
  36.     }
  37.     public static function getSubscribedEvents()
  38.     {
  39.         return [
  40.             'pos.pre_create' => ['onPosPreSave'10],
  41.             'pos.pre_update' => ['onPosPreSave'10],
  42.         ];
  43.     }
  44.     public function onPosPreSave(EntityEvent $event)
  45.     {
  46.         $resource $event->getEntity();
  47.         if ($resource instanceof Pos) {
  48.             if ($this->geocoderSystemConfigurator->isPosEnabled()) {
  49.                 $geocoder       $this->getGeocoder();
  50.                 $geocodeAddress $geocoder->geocode($resource->getGeocodableAddress())->first();
  51.                 if ($geocodeAddress instanceof Address) {
  52.                     $coordinates $geocodeAddress->getCoordinates();
  53.                     $resource->setLongitude($coordinates->getLongitude());
  54.                     $resource->setLatitude($coordinates->getLatitude());
  55.                 }
  56.             }
  57.         }
  58.     }
  59.     private function getGeocoder(): Geocoder
  60.     {
  61.         return $this->geocoderProvider->createGeocoder();
  62.     }
  63. }