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

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. use Symfony\Component\HttpKernel\HttpKernelInterface;
  17. /**
  18. * This listener handles Accept header format negotiations.
  19. *
  20. * @author Lukas Kahwe Smith <smith@pooteeweet.org>
  21. *
  22. * @internal
  23. */
  24. class FormatListener
  25. {
  26. private $formatNegotiator;
  27. public function __construct(FormatNegotiator $formatNegotiator)
  28. {
  29. $this->formatNegotiator = $formatNegotiator;
  30. }
  31. public function onKernelRequest(RequestEvent $event): void
  32. {
  33. $request = $event->getRequest();
  34. if (!$request->attributes->get(FOSRestBundle::ZONE_ATTRIBUTE, true)) {
  35. return;
  36. }
  37. try {
  38. $format = $request->getRequestFormat(null);
  39. if (null === $format) {
  40. $accept = $this->formatNegotiator->getBest('');
  41. if (null !== $accept && 0.0 < $accept->getQuality()) {
  42. $format = $request->getFormat($accept->getValue());
  43. if (null !== $format) {
  44. $request->attributes->set('media_type', $accept->getValue());
  45. }
  46. }
  47. }
  48. if (null === $format) {
  49. if (HttpKernelInterface::MASTER_REQUEST === $event->getRequestType()) {
  50. throw new NotAcceptableHttpException('No matching accepted Response format could be determined');
  51. }
  52. return;
  53. }
  54. $request->setRequestFormat($format);
  55. } catch (StopFormatListenerException $e) {
  56. // nothing to do
  57. }
  58. }
  59. }