src/Hitso/Bundle/CatalogBundle/EventListener/ProductSubscriber.php line 67

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Hitso\Bundle\CatalogBundle\EventListener;
  4. use Faker\Factory;
  5. use Hitso\Bundle\CatalogBundle\Entity\Product;
  6. use Hitso\Bundle\CommonBundle\Doctrine\Event\EntityEvent;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Hitso\Bundle\SearchBundle\Manager\SearchManager;
  9. use Doctrine\Common\Collections\ArrayCollection;
  10. /**
  11.  * Class ProductSubscriber
  12.  *
  13.  * @package Hitso\Bundle\ContentBundle\EventListener
  14.  */
  15. class ProductSubscriber implements EventSubscriberInterface
  16. {
  17.     /**
  18.      * @var SearchManager
  19.      */
  20.     private $searchManager;
  21.     public function __construct(SearchManager $searchManager)
  22.     {
  23.         $this->searchManager $searchManager;
  24.     }
  25.     public static function getSubscribedEvents()
  26.     {
  27.         return [
  28.             'product.pre_create'  => 'onPreCreate',
  29.             'product.post_create' => 'onPostCreate',
  30.             'product.post_update' => 'onPostUpdate',
  31.         ];
  32.     }
  33.     public function onPreCreate(EntityEvent $event): void
  34.     {
  35.         $product $event->getEntity();
  36.         if ($product instanceof Product) {
  37.             if ('' === (string) $product->getSlug()) {
  38.                 $product->setSlug(Factory::create()->uuid);
  39.             }
  40.         }
  41.     }
  42.     public function onPostCreate(EntityEvent $event): void
  43.     {
  44.         $entity $event->getEntity();
  45.         if ($entity instanceof Product) {
  46.             try {
  47.                 $type $this->searchManager->getType('product');
  48.                 if ($type) {
  49.                     $documents = new ArrayCollection();
  50.                     $document  $type->createDocument($entity);
  51.                     $documents->add($document);
  52.                     $this->searchManager->addDocuments($documents$type->getName());
  53.                 }
  54.             } catch (\Exception $e) {
  55.             }
  56.         }
  57.     }
  58.     public function onPostUpdate(EntityEvent $event): void
  59.     {
  60.         $entity $event->getEntity();
  61.         if ($entity instanceof Product) {
  62.             try {
  63.                 $type $this->searchManager->getType('product');
  64.                 if ($type) {
  65.                     $document $type->createDocument($entity);
  66.                     $this->searchManager->updateDocument($document);
  67.                 }
  68.             } catch (\Exception $e) {
  69.             }
  70.         }
  71.     }
  72. }