<?php
namespace Aqarmap\Bundle\ListingBundle\EventListener;
use Aqarmap\Bundle\ListingBundle\Constant\PhotoTypes;
use Aqarmap\Bundle\ListingBundle\Entity\ListingPhoto;
use Aqarmap\Bundle\ListingBundle\Event\ListingEvent;
use Aqarmap\Bundle\ListingBundle\Service\ListingManager;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ListingSlugListener implements EventSubscriberInterface
{
/**
* @var ListingManager
*/
private $listingManager;
/**
* @var EntityManagerInterface
*/
private $entityManager;
public function __construct(ListingManager $listingManager, EntityManagerInterface $entityManager)
{
$this->listingManager = $listingManager;
$this->entityManager = $entityManager;
}
public function afterSaveListingEvent(ListingEvent $event): void
{
$listing = $event->getListing();
$slug = null;
// Add parent Slug
if ($listing->getParent() && !$listing->getCustomSlug()) {
$listing->setSlug($listing->getParent()->getSlug());
} else {
// Add Section Slug
// Todo: This doesn't support 3 levels listings
if ($listing->getSection()) {
$slug .= $listing->getSection()->getSlug();
}
// Add Custom Slug Or add -{property-type}-{location}
if ($listing->getCustomSlug()) {
$slug .= '-'.$listing->getCustomSlug();
} else {
// Add Property Type Slug
if ($propertyType = $listing->getPropertyType()) {
while ($propertyType->getParent() && $propertyType->getLevel() > 1) {
$propertyType = $propertyType->getParent();
}
}
// Add Location Slug
if ($location = $listing->getLocation()) {
if (!$location->getSearchable() && $location->getParent()) {
while ($location && !$location->getSearchable()) {
$location = $location->getParent();
}
}
if (!empty($listing->getLocation())) {
$slug .= '-'.$listing->getLocation()->getSlug();
}
}
}
$slug = str_replace('/', '-', $slug);
$listing->setSlug(trim($slug, '-'));
}
$mainPhoto = $listing->getMainPhoto();
if ($mainPhoto instanceof ListingPhoto) {
if (PhotoTypes::MAIN_PHOTO == !$mainPhoto->getType()) {
$mainPhoto->setType(PhotoTypes::MAIN_PHOTO);
$this->getEntityManager()->persist($mainPhoto);
$this->getEntityManager()->flush($mainPhoto);
}
}
/** @var $em \Doctrine\ORM\EntityManager */
$em = $this->getEntityManager();
$em->persist($listing);
$em->flush();
$this->listingManager->syncSlug($listing);
}
/**
* @return \Doctrine\ORM\EntityManager
*/
public function getEntityManager()
{
return $this->entityManager;
}
public static function getSubscribedEvents()
{
return [
'aqarmap.listing.after_save' => ['afterSaveListingEvent'],
];
}
}