ApiPlatform\Core\EventListener\AddFormatListener::onKernelRequest PHP Method

onKernelRequest() public method

Sets the applicable format to the HttpFoundation Request.
public onKernelRequest ( GetResponseEvent $event )
$event Symfony\Component\HttpKernel\Event\GetResponseEvent
    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        if (!$request->attributes->has('_api_resource_class') && !$request->attributes->has('_api_respond')) {
            return;
        }
        $this->populateMimeTypes();
        $this->addRequestFormats($request, $this->formats);
        // Empty strings must be converted to null because the Symfony router doesn't support parameter typing before 3.2 (_format)
        if (null === ($routeFormat = $request->attributes->get('_format') ?: null)) {
            $mimeTypes = array_keys($this->mimeTypes);
        } elseif (!isset($this->formats[$routeFormat])) {
            throw new NotFoundHttpException('Not Found');
        } else {
            $mimeTypes = Request::getMimeTypes($routeFormat);
        }
        // First, try to guess the format from the Accept header
        $accept = $request->headers->get('Accept');
        if (null !== $accept) {
            if (null === ($acceptHeader = $this->negotiator->getBest($accept, $mimeTypes))) {
                throw $this->getNotAcceptableHttpException($accept, $mimeTypes);
            }
            $request->setRequestFormat($request->getFormat($acceptHeader->getType()));
            return;
        }
        // Then use the Symfony request format if available and applicable
        $requestFormat = $request->getRequestFormat(null) ?: null;
        if (null !== $requestFormat) {
            $mimeType = $request->getMimeType($requestFormat);
            if (isset($this->mimeTypes[$mimeType])) {
                return;
            }
            throw $this->getNotAcceptableHttpException($mimeType);
        }
        // Finally, if no Accept header nor Symfony request format is set, return the default format
        reset($this->formats);
        $request->setRequestFormat(each($this->formats)['key']);
    }

Usage Example

 /**
  * @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  * @expectedExceptionMessage Not Found
  */
 public function testInvalidRouteFormat()
 {
     $request = new Request([], [], ['_api_resource_class' => 'Foo', '_format' => 'invalid']);
     $eventProphecy = $this->prophesize(GetResponseEvent::class);
     $eventProphecy->getRequest()->willReturn($request)->shouldBeCalled();
     $event = $eventProphecy->reveal();
     $listener = new AddFormatListener(new Negotiator(), ['json' => ['application/json']]);
     $listener->onKernelRequest($event);
 }