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