vendor/friendsofsymfony/rest-bundle/EventListener/FormatListener.php line 36

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the FOSRestBundle package.
  4.  *
  5.  * (c) FriendsOfSymfony <http://friendsofsymfony.github.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. namespace FOS\RestBundle\EventListener;
  11. use FOS\RestBundle\FOSRestBundle;
  12. use FOS\RestBundle\Util\StopFormatListenerException;
  13. use FOS\RestBundle\Negotiation\FormatNegotiator;
  14. use Symfony\Component\HttpKernel\Event\RequestEvent;
  15. use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException;
  16. /**
  17.  * This listener handles Accept header format negotiations.
  18.  *
  19.  * @author Lukas Kahwe Smith <smith@pooteeweet.org>
  20.  *
  21.  * @internal
  22.  */
  23. class FormatListener
  24. {
  25.     private $formatNegotiator;
  26.     public function __construct(FormatNegotiator $formatNegotiator)
  27.     {
  28.         $this->formatNegotiator $formatNegotiator;
  29.     }
  30.     public function onKernelRequest(RequestEvent $event): void
  31.     {
  32.         $request $event->getRequest();
  33.         if (!$request->attributes->get(FOSRestBundle::ZONE_ATTRIBUTEtrue)) {
  34.             return;
  35.         }
  36.         try {
  37.             $format $request->getRequestFormat(null);
  38.             if (null === $format) {
  39.                 $accept $this->formatNegotiator->getBest('');
  40.                 if (null !== $accept && 0.0 $accept->getQuality()) {
  41.                     $format $request->getFormat($accept->getValue());
  42.                     if (null !== $format) {
  43.                         $request->attributes->set('media_type'$accept->getValue());
  44.                     }
  45.                 }
  46.             }
  47.             if (null === $format) {
  48.                 if ($event->isMainRequest()) {
  49.                     throw new NotAcceptableHttpException('No matching accepted Response format could be determined');
  50.                 }
  51.                 return;
  52.             }
  53.             $request->setRequestFormat($format);
  54.         } catch (StopFormatListenerException $e) {
  55.             // nothing to do
  56.         }
  57.     }
  58. }