<?php
declare(strict_types=1);
namespace Hitso\Bundle\CatalogBundle\EventListener;
use Hitso\Bundle\CatalogBundle\Entity\Category;
use Hitso\Bundle\CatalogBundle\Repository\CategoryRepository;
use Hitso\Bundle\CommonBundle\Doctrine\Event\EntityEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class SetSubcategorySubscriber implements EventSubscriberInterface
{
/**
* @var RequestStack
*/
private $request;
/**
* @var CategoryRepository
*/
private $catalogCategory;
/**
* AddSubcategorySubscriber constructor.
*
* @param RequestStack $request
* @param CategoryRepository $catalogCategory
*/
public function __construct(RequestStack $request, CategoryRepository $catalogCategory)
{
$this->request = $request;
$this->catalogCategory = $catalogCategory;
}
public static function getSubscribedEvents()
{
return [
'category.post_init' => 'onPostInit',
];
}
public function onPostInit(EntityEvent $event)
{
$category = $event->getEntity();
if (!$category instanceof Category) {
return;
}
$request = $this->request->getMasterRequest();
if (!$request) {
return;
}
$parentId = $request->query->get('parentId');
if (!$parentId) {
return;
}
$parent = $this->catalogCategory->find($parentId);
if (!$parent) {
throw new NotFoundHttpException();
}
$category->setParent($parent);
}
}