vendor/api-platform/core/src/Symfony/EventListener/AddFormatListener.php line 45

  1. <?php
  2. /*
  3.  * This file is part of the API Platform project.
  4.  *
  5.  * (c) Kévin Dunglas <dunglas@gmail.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. declare(strict_types=1);
  11. namespace ApiPlatform\Symfony\EventListener;
  12. use ApiPlatform\Api\FormatMatcher;
  13. use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
  14. use ApiPlatform\Util\OperationRequestInitiatorTrait;
  15. use Negotiation\Negotiator;
  16. use Symfony\Component\HttpFoundation\Request;
  17. use Symfony\Component\HttpKernel\Event\RequestEvent;
  18. use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException;
  19. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  20. /**
  21.  * Chooses the format to use according to the Accept header and supported formats.
  22.  *
  23.  * @author Kévin Dunglas <dunglas@gmail.com>
  24.  */
  25. final class AddFormatListener
  26. {
  27.     use OperationRequestInitiatorTrait;
  28.     public function __construct(private readonly Negotiator $negotiator, ?ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory null, private readonly array $formats = [])
  29.     {
  30.         $this->resourceMetadataCollectionFactory $resourceMetadataCollectionFactory;
  31.     }
  32.     /**
  33.      * Sets the applicable format to the HttpFoundation Request.
  34.      *
  35.      * @throws NotFoundHttpException
  36.      * @throws NotAcceptableHttpException
  37.      */
  38.     public function onKernelRequest(RequestEvent $event): void
  39.     {
  40.         $request $event->getRequest();
  41.         $operation $this->initializeOperation($request);
  42.         if (!(
  43.             $request->attributes->has('_api_resource_class')
  44.             || $request->attributes->getBoolean('_api_respond'false)
  45.             || $request->attributes->getBoolean('_graphql'false)
  46.         )) {
  47.             return;
  48.         }
  49.         $formats $operation?->getOutputFormats() ?? $this->formats;
  50.         $this->addRequestFormats($request$formats);
  51.         // Empty strings must be converted to null because the Symfony router doesn't support parameter typing before 3.2 (_format)
  52.         if (null === $routeFormat $request->attributes->get('_format') ?: null) {
  53.             $flattenedMimeTypes $this->flattenMimeTypes($formats);
  54.             $mimeTypes array_keys($flattenedMimeTypes);
  55.         } elseif (!isset($formats[$routeFormat])) {
  56.             throw new NotFoundHttpException(sprintf('Format "%s" is not supported'$routeFormat));
  57.         } else {
  58.             $mimeTypes Request::getMimeTypes($routeFormat);
  59.             $flattenedMimeTypes $this->flattenMimeTypes([$routeFormat => $mimeTypes]);
  60.         }
  61.         // First, try to guess the format from the Accept header
  62.         /** @var string|null $accept */
  63.         $accept $request->headers->get('Accept');
  64.         if (null !== $accept) {
  65.             if (null === $mediaType $this->negotiator->getBest($accept$mimeTypes)) {
  66.                 throw $this->getNotAcceptableHttpException($accept$flattenedMimeTypes);
  67.             }
  68.             $formatMatcher = new FormatMatcher($formats);
  69.             $request->setRequestFormat($formatMatcher->getFormat($mediaType->getType()));
  70.             return;
  71.         }
  72.         // Then use the Symfony request format if available and applicable
  73.         $requestFormat $request->getRequestFormat('') ?: null;
  74.         if (null !== $requestFormat) {
  75.             $mimeType $request->getMimeType($requestFormat);
  76.             if (isset($flattenedMimeTypes[$mimeType])) {
  77.                 return;
  78.             }
  79.             throw $this->getNotAcceptableHttpException($mimeType$flattenedMimeTypes);
  80.         }
  81.         // Finally, if no Accept header nor Symfony request format is set, return the default format
  82.         foreach ($formats as $format => $mimeType) {
  83.             $request->setRequestFormat($format);
  84.             return;
  85.         }
  86.     }
  87.     /**
  88.      * Adds the supported formats to the request.
  89.      *
  90.      * This is necessary for {@see Request::getMimeType} and {@see Request::getMimeTypes} to work.
  91.      */
  92.     private function addRequestFormats(Request $request, array $formats): void
  93.     {
  94.         foreach ($formats as $format => $mimeTypes) {
  95.             $request->setFormat($format, (array) $mimeTypes);
  96.         }
  97.     }
  98.     /**
  99.      * Retries the flattened list of MIME types.
  100.      */
  101.     private function flattenMimeTypes(array $formats): array
  102.     {
  103.         $flattenedMimeTypes = [];
  104.         foreach ($formats as $format => $mimeTypes) {
  105.             foreach ($mimeTypes as $mimeType) {
  106.                 $flattenedMimeTypes[$mimeType] = $format;
  107.             }
  108.         }
  109.         return $flattenedMimeTypes;
  110.     }
  111.     /**
  112.      * Retrieves an instance of NotAcceptableHttpException.
  113.      */
  114.     private function getNotAcceptableHttpException(string $accept, array $mimeTypes): NotAcceptableHttpException
  115.     {
  116.         return new NotAcceptableHttpException(sprintf(
  117.             'Requested format "%s" is not supported. Supported MIME types are "%s".',
  118.             $accept,
  119.             implode('", "'array_keys($mimeTypes))
  120.         ));
  121.     }
  122. }