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

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