<?php
namespace NetInventors\NetiNextStoreLocator\Subscriber;
use NetInventors\NetiNextStoreLocator\Components\EntityFilter;
use NetInventors\NetiNextStoreLocator\Components\GeoLocation\GeoLocation;
use NetInventors\NetiNextStoreLocator\Components\GeoLocation\Struct\Address;
use NetInventors\NetiNextStoreLocator\Core\Content\Store\StoreEntity;
use NetInventors\NetiNextStoreLocator\Storefront\Framework\Seo\SeoUrlRoute\StorePageSeoUrlRoute;
use Psr\Log\LoggerInterface;
use Shopware\Core\Content\Seo\SeoUrlUpdater;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\Log\LoggingService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class EntitySubscriber implements EventSubscriberInterface
{
/**
* @var EntityFilter
*/
private $entityFilter;
/**
* @var GeoLocation
*/
private $geoLocation;
private $cnt;
/**
* @var EntityRepositoryInterface
*/
private $repository;
/**
* @var LoggerInterface
*/
private $logger;
/**
* @var SeoUrlUpdater
*/
private $seoUrlUpdater;
public function __construct(
EntityFilter $entityFilter,
GeoLocation $geoLocation,
EntityRepositoryInterface $repository,
LoggerInterface $logger,
SeoUrlUpdater $seoUrlUpdater
) {
$this->entityFilter = $entityFilter;
$this->geoLocation = $geoLocation;
$this->repository = $repository;
$this->logger = $logger;
$this->seoUrlUpdater = $seoUrlUpdater;
}
public static function getSubscribedEvents(): array
{
return [
'neti_store_locator.written' => 'onWritten',
];
}
public function onWritten(EntityWrittenEvent $event): void
{
$this->seoUrlUpdater->update(StorePageSeoUrlRoute::ROUTE_NAME, $event->getIds());
$ids = $this->entityFilter->getAffectedIDs($event);
if (!empty($ids)) {
/**
* @psalm-suppress MixedArgumentTypeCoercion
*
* This is the correct way to search for a specific ID
*/
$criteria = new Criteria($ids);
$entities = $this->repository->search($criteria, $event->getContext());
$updates = [];
/** @var StoreEntity $entity */
foreach ($entities as $entity) {
$address = Address::createFrom($entity);
try {
$coords = $this->geoLocation->getCoords($address);
$timezone = $this->geoLocation->getTimezone($coords);
$updates[] = [
'id' => $entity->getId(),
'longitude' => $coords->getLongitude(),
'latitude' => $coords->getLatitude(),
'googlePlaceID' => $coords->getPlaceId(),
'timezone' => $timezone,
];
} catch (\Exception $ex) {
$this->logger->notice(
'Unable to get the coordinates for the address of a store',
[
'exception' => $ex->getMessage(),
]
);
}
}
if (!empty($updates)) {
$this->repository->update($updates, $event->getContext());
}
}
}
}