/** * Gets the normalized type of a request. * * The normalized type is a short, lowercase version of the format, such as * 'html', 'json' or 'atom'. * * @param \Symfony\Component\HttpFoundation\Request $request * The request object from which to extract the content type. * * @return string * The normalized type of a given request. */ public function getContentType(Request $request) { // AJAX iframe uploads need special handling, because they contain a JSON // response wrapped in <textarea>. if ($request->get('ajax_iframe_upload', FALSE)) { return 'iframeupload'; } // Check all formats, if priority format is found return it. $first_found_format = FALSE; $priority = array('html', 'drupal_ajax', 'drupal_modal', 'drupal_dialog'); foreach ($request->getAcceptableContentTypes() as $mime_type) { $format = $request->getFormat($mime_type); if (in_array($format, $priority, TRUE)) { return $format; } if (!is_null($format) && !$first_found_format) { $first_found_format = $format; } } // No HTML found, return first found. if ($first_found_format) { return $first_found_format; } if ($request->isXmlHttpRequest()) { return 'ajax'; } // Do HTML last so that it always wins. return 'html'; }
/** * {@inheritdoc} */ public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) { if ($request->headers->has('Accept')) { $request->setRequestFormat($request->getFormat($request->headers->get('Accept'))); } return $this->httpKernel->handle($request, $type, $catch); }
/** * Get the format applying the supplied priorities to the mime types * * @param Request $request The request * @param array $mimetypes Ordered array of mimetypes as keys with priroties s values * @param array $priorities Ordered array of formats (highest priority first) * @param Boolean $catchAllEnabled If there is a catch all priority * * @return void|string The format string */ protected function getFormatByPriorities($request, $mimetypes, $priorities, $catchAllEnabled = false) { $max = reset($mimetypes); $keys = array_keys($mimetypes, $max); $formats = array(); foreach ($keys as $mimetype) { unset($mimetypes[$mimetype]); if ($mimetype === '*/*') { return reset($priorities); } $format = $request->getFormat($mimetype); if ($format) { $priority = array_search($format, $priorities); if (false !== $priority) { $formats[$format] = $priority; } elseif ($catchAllEnabled) { $formats[$format] = count($priorities); } } } if (empty($formats) && !empty($mimetypes)) { return $this->getFormatByPriorities($request, $mimetypes, $priorities); } asort($formats); return key($formats); }
/** * Returns response based on request content type * @param Request $request [description] * @param [type] $response_data [description] * @param integer $response_code [description] * @return [type] [description] */ protected function handleResponse(Request $request, $response_data, $response_code = 200) { $response = new Response(); $contentType = $request->headers->get('Content-Type'); $format = null === $contentType ? $request->getRequestFormat() : $request->getFormat($contentType); if ($format == 'json') { $serializer = $this->get('serializer'); $serialization_context = SerializationContext::create()->enableMaxDepthChecks()->setGroups(array('Default', 'detail', 'from_user', 'from_oauth')); $response->setContent($serializer->serialize($response_data, 'json', $serialization_context)); $response->headers->set('Content-Type', 'application/json'); } else { if (is_array($response_data)) { if (isset($response_data['message'])) { $response->setContent($response_data['message']); } else { $response->setContent(json_encode($response_data)); } } } if ($response_code == 0) { $response->setStatusCode(500); } else { $response->setStatusCode($response_code); } return $response; }
/** * @param Request $request The request * @param FlattenException $exception A FlattenException instance * @param DebugLoggerInterface $logger A DebugLoggerInterface instance * * @return Response */ public function showAction(Request $request, FlattenException $exception, DebugLoggerInterface $logger = null) { $status = $exception->getStatusCode(); $message = $exception->getMessage(); $previousUrl = $request->headers->get('referer'); if ($request->getFormat($request->getAcceptableContentTypes()[0]) == 'json') { return new JsonResponse(['status' => $status, 'message' => $message]); } else { return $this->render('exception/404.html.twig', ['status' => $status, 'message' => $message, 'previousUrl' => $previousUrl]); } }
protected function doKernelRequest(Request $request) { $routeName = $request->attributes->get('_route'); $route = $this->routes->get($routeName); if (!$route) { return; } $format = $request->getFormat($request->headers->get('Content-Type', null, true)); if ($this->decoderProvider->supports($format)) { /** @var \FOS\Rest\Decoder\DecoderInterface $decoder */ $decoder = $this->decoderProvider->getDecoder($format); $data = $decoder->decode($request->getContent()); $request->request->replace(is_array($data) ? $data : array()); } }
public function setBaseRequestFormat() { // Check headers for Accept $acceptHeaders = $this->request->getAcceptableContentTypes(); foreach ($acceptHeaders as $header) { $baseFormt = $this->request->getFormat($header); if ($baseFormt == Format::FORMAT_JSON) { $this->request->setRequestFormat($baseFormt); } // Override base HTML format with JSON (default) if ($baseFormt == 'html') { $this->request->setRequestFormat(Format::FORMAT_JSON); } } }
/** * @covers Symfony\Component\HttpFoundation\Request::getFormat */ public function testGetFormat() { $request = new Request(); $this->assertNull($request->getFormat(null), '->getFormat() returns null when mime-type is null'); $this->assertNull($request->getFormat('unexistant-mime-type'), '->getFormat() returns null when mime-type is unknown'); $this->assertEquals('txt', $request->getFormat('text/plain'), '->getFormat() returns correct format when mime-type have one format only'); $this->assertEquals('js', $request->getFormat('application/javascript'), '->getFormat() returns correct format when format have multiple mime-type (first)'); $this->assertEquals('js', $request->getFormat('application/x-javascript'), '->getFormat() returns correct format when format have multiple mime-type'); $this->assertEquals('js', $request->getFormat('text/javascript'), '->getFormat() returns correct format when format have multiple mime-type (last)'); }
/** * Extracts the format from the Content-Type header and check that it is supported. * * @param Request $request * * @throws NotAcceptableHttpException * * @return string */ private function getFormat(Request $request) : string { $contentType = $request->headers->get('CONTENT_TYPE'); if (null === $contentType) { throw new NotAcceptableHttpException('The "Content-Type" header must exist.'); } $format = $request->getFormat($contentType); if (!isset($this->formats[$format])) { $supportedMimeTypes = []; foreach ($this->formats as $mimeTypes) { foreach ($mimeTypes as $mimeType) { $supportedMimeTypes[] = $mimeType; } } throw new NotAcceptableHttpException(sprintf('The content-type "%s" is not supported. Supported MIME types are "%s".', $contentType, implode('", "', $supportedMimeTypes))); } return $format; }
/** * @covers Symfony\Component\HttpFoundation\Request::getFormat */ public function testGetFormatFromMimeTypeWithParameters() { $request = new Request(); $this->assertEquals('json', $request->getFormat('application/json; charset=utf-8')); }
/** * Determines the format to use for the response. * * @param Request $request * @param string $format * * @return string */ protected function getFormat(Request $request, $format) { try { $formatNegotiator = $this->container->get('fos_rest.exception_format_negotiator'); $accept = $formatNegotiator->getBest('', []); if ($accept) { $format = $request->getFormat($accept->getType()); } $request->attributes->set('_format', $format); } catch (StopFormatListenerException $e) { $format = $request->getRequestFormat(); } return $format; }
/** * @covers Symfony\Component\HttpFoundation\Request::getFormat * @covers Symfony\Component\HttpFoundation\Request::setFormat * @dataProvider getFormatToMimeTypeMapProvider */ public function testGetFormatFromMimeType($format, $mimeTypes) { $request = new Request(); foreach ($mimeTypes as $mime) { $this->assertEquals($format, $request->getFormat($mime)); } $request->setFormat($format, $mimeTypes); foreach ($mimeTypes as $mime) { $this->assertEquals($format, $request->getFormat($mime)); } }
public function testGetFormatWithCustomMimeType() { $request = new Request(); $request->setFormat('custom', 'application/vnd.foo.api;myversion=2.3'); $this->assertEquals('custom', $request->getFormat('application/vnd.foo.api;myversion=2.3')); }
/** * This before middleware validates whether the application will be able to * respond in a format that the client understands. * * @param Request $request * @throws NotAcceptableHttpException */ public function setRequestFormat(Request $request, Application $app) { // If there is no Accept header, do nothing if (!$request->headers->get("Accept")) { return; } // Check the Accept header for acceptable formats foreach ($request->getAcceptableContentTypes() as $contentType) { // If any format is acceptable, do nothing if ($contentType === "*/*") { return; } $format = $request->getFormat($contentType); if (in_array($format, $app["conneg.responseFormats"])) { // An acceptable format was found. Set it as the requestFormat // where it can be referenced later. $request->setRequestFormat($format); return; } } // No acceptable formats were found throw new NotAcceptableHttpException(); }