<?php
namespace App\EventSubscriber;
use ApiPlatform\Symfony\EventListener\EventPriorities;
use ApiPlatform\Util\RequestAttributesExtractor;
use App\Entity\Category;
use App\Entity\MediaObject;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Vich\UploaderBundle\Storage\StorageInterface;
final class ResolveCategoryParentNameSubscriber implements EventSubscriberInterface
{
public function __construct(private readonly StorageInterface $storage)
{
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::VIEW => ['onPreSerialize', EventPriorities::PRE_SERIALIZE],
];
}
public function onPreSerialize(ViewEvent $event): void
{
$controllerResult = $event->getControllerResult();
$request = $event->getRequest();
if ($controllerResult instanceof Response || !$request->attributes->getBoolean('_api_respond', true)) {
return;
}
if (!($attributes = RequestAttributesExtractor::extractAttributes($request)) || !\is_a($attributes['resource_class'], Category::class, true)) {
return;
}
$categories = $controllerResult;
if (!is_iterable($categories)) {
$categories = [$categories];
}
foreach ($categories as $category) {
if (!$category instanceof Category) {
continue;
}
$parent = $category->getParent();
if(!$parent)
$category->parentName = null;
else
$category->parentName = $parent->getName();
}
}
}