<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use ApiPlatform\Core\Util\RequestAttributesExtractor;
use App\Entity\GalerieGroupe;
use App\Entity\Galery;
use App\Entity\Image;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Vich\UploaderBundle\Storage\StorageInterface;
class GaleryContentUrlSubscriber implements EventSubscriberInterface
{
private $storage;
public function __construct(StorageInterface $storage)
{
$this->storage = $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();
$mediaObjects = $controllerResult;
if ($controllerResult instanceof Response || !$request->attributes->getBoolean('_api_respond', true)) {
return;
}
if($request->getMethod() === Request::METHOD_DELETE){
return ;
}
if (($attributes = RequestAttributesExtractor::extractAttributes($request)) && \is_a($attributes['resource_class'], Galery::class, true)) {
foreach ($mediaObjects as $mediaObject) {
if (!$mediaObject instanceof Galery) {
continue;
}
$url = $_SERVER['HTTP_HOST'];
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
$schema = "https://";
} else {
$schema = "http://";
}
$mediaObject->contentUrl = $schema.$url.$this->storage->resolveUri($mediaObject, 'file');
}
}elseif (($attributes = RequestAttributesExtractor::extractAttributes($request)) && \is_a($attributes['resource_class'], GalerieGroupe::class, true)) {
foreach ($mediaObjects as $mediaObject) {
if (!$mediaObject instanceof GalerieGroupe) {
continue;
}
$url = $_SERVER['HTTP_HOST'];
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
$schema = "https://";
} else {
$schema = "http://";
}
$galeries = $mediaObject->getGaleries();
foreach ($galeries as $galery){
$galery->contentUrl = $schema.$url.$this->storage->resolveUri($galery, 'file');
}
}
}
}
}