Handles Kernel View events

@param GetResponseForControllerResultEvent $event
437194
public function onKernelView(GetResponseForControllerResultEvent $event)
    {
        $request    = $event->getRequest();
        $response   = $event->getResponse();
        $parameters = $event->getControllerResult();

        if (!$response instanceof Response && $template = $request->attributes->get('_template')) {
            return $event->setControllerResult($this->templating->render($template, $parameters));
        }
    }
1218292
public function handleLoadDataContainer(LoadDataContainerEvent $event)
    {
        /** @var Controller $controllerAdapter */
        $controllerAdapter = $this->framework->getAdapter(Controller::class);

        $controllerAdapter->loadDataContainer($event->getName(), $event->isCacheIgnored());
    }
398740
public function onKernelException(GetResponseForExceptionEvent $event)
    {
        if ($this->isProfilerRequest($event->getRequest())) {
            return;
        }

        $exception = $event->getException();

        if ($exception instanceof DatabaseExceptionInterface) {
            $html = $this->renderDatabaseException($exception);
        } elseif ($exception instanceof AbstractSystemValidationException) {
            $html = $this->renderSystemValidationException($exception);
        } else {
            $html = $this->renderException($exception);
        }

        $statusCode = $exception instanceof HttpExceptionInterface ?
            $exception->getStatusCode() :
            Response::HTTP_INTERNAL_SERVER_ERROR;
        $response = new Response($html, $statusCode, ['X-Debug-Exception-Handled' => time()]);

        $event->setResponse($response);
    }
152839
public function onKernelView(GetResponseForControllerResultEvent $event): void
    {
        $request = $event->getRequest();
        if ($request->isMethodSafe(false) || !($attributes = RequestAttributesExtractor::extractAttributes($request)) || !$attributes['persist']) {
            return;
        }

        $controllerResult = $event->getControllerResult();
        if (!$this->dataPersister->supports($controllerResult, $attributes)) {
            return;
        }

        switch ($request->getMethod()) {
            case 'PUT':
            case 'PATCH':
            case 'POST':
                $persistResult = $this->dataPersister->persist($controllerResult, $attributes);

                if (null === $persistResult) {
                    @trigger_error(sprintf('Returning void from %s::persist() is deprecated since API Platform 2.3 and will not be supported in API Platform 3, an object should always be returned.', DataPersisterInterface::class), E_USER_DEPRECATED);
                } else {
                    $controllerResult = $persistResult;
                    $event->setControllerResult($controllerResult);
                }

                if (null === $this->iriConverter) {
                    return;
                }

                $hasOutput = true;
                if (null !== $this->resourceMetadataFactory) {
                    $resourceMetadata = $this->resourceMetadataFactory->create($attributes['resource_class']);
                    $outputMetadata = $resourceMetadata->getOperationAttribute($attributes, 'output', ['class' => $attributes['resource_class']], true);
                    $hasOutput = \array_key_exists('class', $outputMetadata) && null !== $outputMetadata['class'] && $controllerResult instanceof $outputMetadata['class'];
                }

                if ($hasOutput) {
                    $request->attributes->set('_api_write_item_iri', $this->iriConverter->getIriFromItem($controllerResult));
                }
            break;
            case 'DELETE':
                $this->dataPersister->remove($controllerResult);
                $event->setControllerResult(null);
                break;
        }
    }
441149
public function onCoreException(GetResponseForExceptionEvent $event)
    {
        $exception = $event->getException();
        $request = $event->getRequest();

        if ($request->isXmlHttpRequest()
            && get_class($exception) == 'Symfony\Component\Security\Core\Exception\AccessDeniedException') {
            $form = $this->templating->render(
                'ClarolineCoreBundle:Authentication:loginAjaxForm.html.twig'
            );

            //@see https://github.com/gillest/HackSessionBundle
            if (!$request->hasPreviousSession()) {
                $request->cookies->set(session_name(), 'tmp');
                $request->setSession($this->session);
            }

            $event->setResponse(new Response($form, 403));
        }
    }
1279300
public function onKernelException(GetResponseForExceptionEvent $event): void
    {
        $exception = $event->getException();
        if (!$exception instanceof ValidationException) {
            return;
        }

        $format = ErrorFormatGuesser::guessErrorFormat($event->getRequest(), $this->errorFormats);

        $event->setResponse(new Response(
                $this->serializer->serialize($exception->getConstraintViolationList(), $format['key']),
                Response::HTTP_BAD_REQUEST,
                [
                    'Content-Type' => sprintf('%s; charset=utf-8', $format['value'][0]),
                    'X-Content-Type-Options' => 'nosniff',
                    'X-Frame-Options' => 'deny',
                ]
        ));
    }
338611
public function onKernelResponse(KernelEvent $event)
    {
        if ($event->getRequestType() === HttpKernelInterface::MASTER_REQUEST
            && $this->wasTxStarted
            && $this->doctrine->getConnection()->getTransactionIsolation() > 0) {

            if ($this->doctrine->getConnection()->isRollbackOnly()) {
                $this->doctrine->getConnection()->rollback();
            } else {
                $this->doctrine->getConnection()->commit();
            }
            $this->wasTxStarted = false;
        }
    }
501798
public function onKernelResponse(FilterResponseEvent $event)
	{
		$result = parent::onKernelResponse($event);
		$content = ob_get_contents();

		if ($this->request_stack->getCurrentRequest()->getMethod() === 'POST' && empty($content))
		{
			$event->stopPropagation();
		}

		return $result;
	}
224488
public function onKernelView(GetResponseForControllerResultEvent $event)
    {
        $controllerResult = $event->getControllerResult();

        if (!$controllerResult instanceof ResponseInterface) {
            return;
        }

        $event->setResponse($this->httpFoundationFactory->createResponse($controllerResult));
    }
594229
public function onKernelView(GetResponseForControllerResultEvent $event): void
    {
        $presentation = $event->getControllerResult();

        if (!$presentation instanceof PresentationInterface) {
            // Not the presentation instance
            return;
        }

        $data = null;
        $headers = [];

        if ($presentation->getResource()) {
            $acceptableMediaTypes = $event->getRequest()->getAcceptableContentTypes();
            $serializer = $this->serializerResolver->resolveByMediaTypes(
                get_class($presentation->getResource()),
                $acceptableMediaTypes,
                $acceptableMediaType
            );

            $serializationContext = $this->serializationContextCollector->collect();
            $data = $serializer->serialize($presentation->getResource(), $serializationContext);
            $headers = [
                'Content-Type' => $acceptableMediaType,
            ];
        }

        $response = new Response($data, $presentation->getStatusCode());
        $response->headers->add($headers);

        $event->setResponse($response);
    }
936403
public function onKernelView(GetResponseForControllerResultEvent $event) :? Response
    {
        $request = $event->getRequest();
        $result = $event->getControllerResult();

        // If the event already has a response, do not override it.
        if ($event->hasResponse()) {
            return $event->getResponse();
        }

        // If the request format is not supported, nothing more can be done
        // without the serializer throwing an exception.
        if (!$this->encoder->supportsEncoding($request->getRequestFormat())) {
            return null;
        }

        if (is_iterable($result)) {
            $data = $result;

            // Convert objects to arrays.
            if ($result instanceof \Traversable) {
                $data = iterator_to_array($result);
            }

            // Determine if array is a collection or just a standard array.
            $bad = array_filter($data, function ($item) use ($request) {
                if (!is_object($item)) {
                    return true;
                }

                if (!$this->normalizer->supportsNormalization($item, $request->getRequestFormat())) {
                    return true;
                }

                return false;
            });

            // If array is a collection and everything can be normalized,
            // normalize each item before serialization.
            if (!count($bad)) {
                $result = array_map(function ($item) use ($request) {
                    return $this->normalizer->normalize($item, $request->getRequestFormat(), [
                        'groups' => $this->groupResolver->resolve($request, $item),
                        'enable_max_depth' => true,
                    ]);
                }, $data);
            }
        }

        // If the normalizer cannot normalize the result, then there is nothing
        // more than can be done without the serializer throwing an exception.
        if (is_object($result) && !$this->normalizer->supportsNormalization($result, $request->getRequestFormat())) {
            return null;
        }

        $status = Response::HTTP_OK;
        switch ($request->getMethod()) {
            case Request::METHOD_POST:
                $status = Response::HTTP_CREATED;
                break;
            case Request::METHOD_DELETE:
                $status = Response::HTTP_NO_CONTENT;
                break;
        }

        $groups = null;
        if (is_object($result)) {
            $groups = $this->groupResolver->resolve($request, $result);
        }

        $serializeEvent = new SerializeEvent(
            $result,
            $request->getRequestFormat(),
            [
                'groups' => $groups,
                'enable_max_depth' => true,
            ],
            $request
        );

        $this->eventDispatcher->dispatch(SerializeEvent::NAME, $serializeEvent);

        $response = new Response(
            $this->serializer->serialize(
                $serializeEvent->getData(),
                $serializeEvent->getFormat(),
                $serializeEvent->getContext()
            ),
            $status
        );
        $event->setResponse($response);

        return $response;
    }
439714
public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $exception = $event->getException();

        if ($exception instanceof HttpException) {
            return;
        }

        $this->client->notifyOnException($exception);
        error_log($exception->getMessage().' in: '.$exception->getFile().':'.$exception->getLine());
    }
997148
public function onKernelExceptionView(GetResponseForExceptionEvent $event)
    {
        if (!$event->getRequest()->attributes->get('is_rest_request')) {
            return;
        }

        $event->setResponse(
            $this->viewDispatcher->dispatch(
                $event->getRequest(),
                $event->getException()
            )
        );
        $event->stopPropagation();
    }
827225
public function onKernelRequest(GetResponseEvent $event): void
    {
        $request = $event->getRequest();
        if (
            !($attributes = RequestAttributesExtractor::extractAttributes($request))
            || !$attributes['receive']
        ) {
            return;
        }

        if (null === $filters = $request->attributes->get('_api_filters')) {
            $queryString = RequestParser::getQueryString($request);
            $filters = $queryString ? RequestParser::parseRequestParams($queryString) : null;
        }

        $context = null === $filters ? [] : ['filters' => $filters];
        if ($this->serializerContextBuilder) {
            // Builtin data providers are able to use the serialization context to automatically add join clauses
            $context += $normalizationContext = $this->serializerContextBuilder->createFromRequest($request, true, $attributes);
            $request->attributes->set('_api_normalization_context', $normalizationContext);
        }

        if (isset($attributes['collection_operation_name'])) {
            $request->attributes->set('data', $request->isMethod('POST') ? null : $this->getCollectionData($attributes, $context));

            return;
        }

        $data = [];

        if ($this->identifierConverter) {
            $context[IdentifierConverterInterface::HAS_IDENTIFIER_CONVERTER] = true;
        }

        try {
            $identifiers = $this->extractIdentifiers($request->attributes->all(), $attributes);

            if (isset($attributes['item_operation_name'])) {
                $data = $this->getItemData($identifiers, $attributes, $context);
            } elseif (isset($attributes['subresource_operation_name'])) {
                // Legacy
                if (null === $this->subresourceDataProvider) {
                    throw new RuntimeException('No subresource data provider.');
                }

                $data = $this->getSubresourceData($identifiers, $attributes, $context);
            }
        } catch (InvalidIdentifierException $e) {
            throw new NotFoundHttpException('Not found, because of an invalid identifier configuration', $e);
        }

        if (null === $data) {
            throw new NotFoundHttpException('Not Found');
        }

        $request->attributes->set('data', $data);
    }
655905
public function viewResponseEvent(ViewEvent $event)
    {
        /** @var \Rcm\EventListener\ViewEventListener $viewEventListener */
        $viewEventListener
            = $this->serviceLocator->get(\Rcm\EventListener\ViewEventListener::class);

        $return = $viewEventListener->processRcmResponses($event);

        if (!empty($return)) {
            return $return;
        }

        return null;
    }
1069488
public function onKernelView(GetResponseForControllerResultEvent $event): void
    {
        $controllerResult = $event->getControllerResult();
        $request = $event->getRequest();

        if ($controllerResult instanceof Response || !(($attributes = RequestAttributesExtractor::extractAttributes($request))['respond'] ?? $request->attributes->getBoolean('_api_respond', false))) {
            return;
        }

        if (!$attributes) {
            $this->serializeRawData($event, $request, $controllerResult);

            return;
        }

        $context = $this->serializerContextBuilder->createFromRequest($request, true, $attributes);

        if (isset($context['output']) && \array_key_exists('class', $context['output']) && null === $context['output']['class']) {
            $event->setControllerResult(null);

            return;
        }

        if ($included = $request->attributes->get('_api_included')) {
            $context['api_included'] = $included;
        }
        $resources = new ResourceList();
        $context['resources'] = &$resources;

        $resourcesToPush = new ResourceList();
        $context['resources_to_push'] = &$resourcesToPush;

        $request->attributes->set('_api_normalization_context', $context);

        $event->setControllerResult($this->serializer->serialize($controllerResult, $request->getRequestFormat(), $context));

        $request->attributes->set('_resources', $request->attributes->get('_resources', []) + (array) $resources);
        if (!\count($resourcesToPush)) {
            return;
        }

        $linkProvider = $request->attributes->get('_links', new GenericLinkProvider());
        foreach ($resourcesToPush as $resourceToPush) {
            $linkProvider = $linkProvider->withLink(new Link('preload', $resourceToPush));
        }
        $request->attributes->set('_links', $linkProvider);
    }
1330278
public function onKernelView(GetResponseForControllerResultEvent $event)
    {
        $request = $event->getRequest();

        if (!$request->attributes->get(FOSRestBundle::ZONE_ATTRIBUTE, true)) {
            return false;
        }

        $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 ($configuration->getTemplateVar()) {
                $view->setTemplateVar($configuration->getTemplateVar());
            }
            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 ($configuration->getSerializerEnableMaxDepthChecks()) {
                $context->setMaxDepth(0, false);
            }
            if (true === $configuration->getSerializerEnableMaxDepthChecks()) {
                $context->enableMaxDepth();
            } elseif (false === $configuration->getSerializerEnableMaxDepthChecks()) {
                $context->disableMaxDepth();
            }

            list($controller, $action) = $configuration->getOwner();
            $vars = $this->getDefaultVars($configuration, $controller, $action);
        } else {
            $vars = null;
        }

        if (null === $view->getFormat()) {
            $view->setFormat($request->getRequestFormat());
        }

        if ($this->viewHandler->isFormatTemplating($view->getFormat())
            && !$view->getRoute()
            && !$view->getLocation()
        ) {
            if (null !== $vars && 0 !== count($vars)) {
                $parameters = (array) $this->viewHandler->prepareTemplateParameters($view);
                foreach ($vars as $var) {
                    if (!array_key_exists($var, $parameters)) {
                        $parameters[$var] = $request->attributes->get($var);
                    }
                }
                $view->setData($parameters);
            }

            if ($configuration && ($template = $configuration->getTemplate()) && !$view->getTemplate()) {
                if ($template instanceof TemplateReferenceInterface) {
                    $template->set('format', null);
                }

                $view->setTemplate($template);
            }
        }

        $response = $this->viewHandler->handle($view, $request);

        $event->setResponse($response);
    }