<?php
/*
* This file is part of the FOSRestBundle package.
*
* (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace FOS\RestBundle\EventListener;
use FOS\RestBundle\Controller\Annotations\View as ViewAnnotation;
use FOS\RestBundle\FOSRestBundle;
use FOS\RestBundle\View\View;
use FOS\RestBundle\View\ViewHandlerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* The ViewResponseListener class handles the View core event as well as the "@extra:Template" annotation.
*
* @author Lukas Kahwe Smith <smith@pooteeweet.org>
*
* @internal
*/
class ViewResponseListener implements EventSubscriberInterface
{
private $viewHandler;
private $forceView;
public function __construct(ViewHandlerInterface $viewHandler, bool $forceView)
{
$this->viewHandler = $viewHandler;
$this->forceView = $forceView;
}
public function onKernelView(ViewEvent $event): void
{
$request = $event->getRequest();
if (!$request->attributes->get(FOSRestBundle::ZONE_ATTRIBUTE, true)) {
return;
}
$configuration = $request->attributes->get('_template');
$view = $event->getControllerResult();
if (!$view instanceof View) {
if (!$configuration instanceof ViewAnnotation && !$this->forceView) {
return;
}
$view = new View($view);
}
if ($configuration instanceof ViewAnnotation) {
if (null !== $configuration->getStatusCode() && (null === $view->getStatusCode() || Response::HTTP_OK === $view->getStatusCode())) {
$view->setStatusCode($configuration->getStatusCode());
}
$context = $view->getContext();
if ($configuration->getSerializerGroups()) {
if (null === $context->getGroups()) {
$context->setGroups($configuration->getSerializerGroups());
} else {
$context->setGroups(array_merge($context->getGroups(), $configuration->getSerializerGroups()));
}
}
if (true === $configuration->getSerializerEnableMaxDepthChecks()) {
$context->enableMaxDepth();
} elseif (false === $configuration->getSerializerEnableMaxDepthChecks()) {
$context->disableMaxDepth();
}
}
if (null === $view->getFormat()) {
$view->setFormat($request->getRequestFormat());
}
$response = $this->viewHandler->handle($view, $request);
$event->setResponse($response);
}
public static function getSubscribedEvents(): array
{
// Must be executed before SensioFrameworkExtraBundle's listener
return array(
KernelEvents::VIEW => array('onKernelView', 30),
);
}
}