<?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\Article;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Hitso\Bundle\SearchBundle\Manager\SearchManager;
use Doctrine\Common\Collections\ArrayCollection;
class ArticleSubscriber implements EventSubscriberInterface
{
/**
* @var SearchManager
*/
private $searchManager;
public function __construct(SearchManager $searchManager)
{
$this->searchManager = $searchManager;
}
public static function getSubscribedEvents()
{
return [
'article.post_create' => 'onPostCreate',
'article.post_update' => 'onPostUpdate',
];
}
public function onPostCreate(EntityEvent $event): void
{
$entity = $event->getEntity();
if ($entity instanceof Article) {
try {
$type = $this->searchManager->getType('article');
$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 Article) {
try {
$type = $this->searchManager->getType('article');
$document = $type->createDocument($entity);
$this->searchManager->updateDocument($document);
} catch (\Exception $e) {
}
}
}
}