src/Hitso/Bundle/CatalogBundle/EventListener/SetSubcategorySubscriber.php line 44

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Hitso\Bundle\CatalogBundle\EventListener;
  4. use Hitso\Bundle\CatalogBundle\Entity\Category;
  5. use Hitso\Bundle\CatalogBundle\Repository\CategoryRepository;
  6. use Hitso\Bundle\CommonBundle\Doctrine\Event\EntityEvent;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\HttpFoundation\RequestStack;
  9. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  10. class SetSubcategorySubscriber implements EventSubscriberInterface
  11. {
  12.     /**
  13.      * @var RequestStack
  14.      */
  15.     private $request;
  16.     /**
  17.      * @var CategoryRepository
  18.      */
  19.     private $catalogCategory;
  20.     /**
  21.      * AddSubcategorySubscriber constructor.
  22.      *
  23.      * @param RequestStack       $request
  24.      * @param CategoryRepository $catalogCategory
  25.      */
  26.     public function __construct(RequestStack $requestCategoryRepository $catalogCategory)
  27.     {
  28.         $this->request         $request;
  29.         $this->catalogCategory $catalogCategory;
  30.     }
  31.     public static function getSubscribedEvents()
  32.     {
  33.         return [
  34.             'category.post_init' => 'onPostInit',
  35.         ];
  36.     }
  37.     public function onPostInit(EntityEvent $event)
  38.     {
  39.         $category $event->getEntity();
  40.         if (!$category instanceof Category) {
  41.             return;
  42.         }
  43.         $request $this->request->getMasterRequest();
  44.         if (!$request) {
  45.             return;
  46.         }
  47.         $parentId $request->query->get('parentId');
  48.         if (!$parentId) {
  49.             return;
  50.         }
  51.         $parent $this->catalogCategory->find($parentId);
  52.         if (!$parent) {
  53.             throw new NotFoundHttpException();
  54.         }
  55.         $category->setParent($parent);
  56.     }
  57. }