<?php
declare(strict_types=1);
namespace Hitso\Bundle\CatalogBundle\EventListener;
use Faker\Factory;
use Hitso\Bundle\CatalogBundle\Entity\Product;
use Hitso\Bundle\CommonBundle\Doctrine\Event\EntityEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Hitso\Bundle\SearchBundle\Manager\SearchManager;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Class ProductSubscriber
*
* @package Hitso\Bundle\ContentBundle\EventListener
*/
class ProductSubscriber implements EventSubscriberInterface
{
/**
* @var SearchManager
*/
private $searchManager;
public function __construct(SearchManager $searchManager)
{
$this->searchManager = $searchManager;
}
public static function getSubscribedEvents()
{
return [
'product.pre_create' => 'onPreCreate',
'product.post_create' => 'onPostCreate',
'product.post_update' => 'onPostUpdate',
];
}
public function onPreCreate(EntityEvent $event): void
{
$product = $event->getEntity();
if ($product instanceof Product) {
if ('' === (string) $product->getSlug()) {
$product->setSlug(Factory::create()->uuid);
}
}
}
public function onPostCreate(EntityEvent $event): void
{
$entity = $event->getEntity();
if ($entity instanceof Product) {
try {
$type = $this->searchManager->getType('product');
if ($type) {
$documents = new ArrayCollection();
$document = $type->createDocument($entity);
$documents->add($document);
$this->searchManager->addDocuments($documents, $type->getName());
}
} catch (\Exception $e) {
}
}
}
public function onPostUpdate(EntityEvent $event): void
{
$entity = $event->getEntity();
if ($entity instanceof Product) {
try {
$type = $this->searchManager->getType('product');
if ($type) {
$document = $type->createDocument($entity);
$this->searchManager->updateDocument($document);
}
} catch (\Exception $e) {
}
}
}
}