getAcceptableContentTypes() публичный Метод

Gets a list of content types acceptable by the client browser.
public getAcceptableContentTypes ( ) : array
Результат array List of content types in preferable order
Пример #1
0
 /**
  * @return bool
  */
 private function shouldHandleRequest()
 {
     if ($this->handleNonJsonRequests) {
         return true;
     }
     return in_array('application/json', $this->request->getAcceptableContentTypes());
 }
Пример #2
0
 /**
  * Extracts the requested media type from $request
  * @todo refactor, maybe to a REST Request with an accepts('content-type') method
  *
  * @return string
  */
 protected function getMediaType()
 {
     foreach ($this->request->getAcceptableContentTypes() as $mimeType) {
         if (preg_match('(^([a-z0-9-/.]+)\\+.*$)', strtolower($mimeType), $matches)) {
             return $matches[1];
         }
     }
     return 'unknown/unknown';
 }
Пример #3
0
 /**
  * @param ViewHandler $viewHandler
  * @param View $view
  * @param Request $request
  * @param string $format
  *
  * @return Response
  */
 public function handleExtension(ViewHandler $handler, View $view, Request $request, $format)
 {
     if (in_array("application/vnd.bpi.api+xml", $request->getAcceptableContentTypes())) {
         $view->setHeader("Content-Type", "application/vnd.bpi.api+xml");
     }
     return $handler->createResponse($view, $request, "xml");
 }
 /**
  * {@inheritdoc}
  */
 public function filter(RouteCollection $collection, Request $request)
 {
     // Generates a list of Symfony formats matching the acceptable MIME types.
     // @todo replace by proper content negotiation library.
     $acceptable_mime_types = $request->getAcceptableContentTypes();
     $acceptable_formats = array_filter(array_map(array($request, 'getFormat'), $acceptable_mime_types));
     $primary_format = $request->getRequestFormat();
     foreach ($collection as $name => $route) {
         // _format could be a |-delimited list of supported formats.
         $supported_formats = array_filter(explode('|', $route->getRequirement('_format')));
         if (empty($supported_formats)) {
             // No format restriction on the route, so it always matches. Move it to
             // the end of the collection by re-adding it.
             $collection->add($name, $route);
         } elseif (in_array($primary_format, $supported_formats)) {
             // Perfect match, which will get a higher priority by leaving the route
             // on top of the list.
         } elseif (in_array('*/*', $acceptable_mime_types) || array_intersect($acceptable_formats, $supported_formats)) {
             // Move it to the end of the list.
             $collection->add($name, $route);
         } else {
             // Remove the route if it does not match at all.
             $collection->remove($name);
         }
     }
     if (count($collection)) {
         return $collection;
     }
     // We do not throw a
     // \Symfony\Component\Routing\Exception\ResourceNotFoundException here
     // because we don't want to return a 404 status code, but rather a 406.
     throw new NotAcceptableHttpException(SafeMarkup::format('No route found for the specified formats @formats.', array('@formats' => implode(' ', $acceptable_mime_types))));
 }
 /**
  * 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';
 }
Пример #6
0
 /**
  * Exports the given data to a given format
  *
  * @Routing\Route("/api/export", defaults={"method" = "post","_format" = "json"})
  * @View()
  *
  * @return array
  */
 public function exportAction(Request $request)
 {
     $contentTypes = $request->getAcceptableContentTypes();
     $exporter = false;
     $file = tempnam(sys_get_temp_dir(), "partkeepr_export");
     unlink($file);
     foreach ($contentTypes as $contentType) {
         switch ($contentType) {
             case "text/comma-separated-values":
                 $exporter = new CsvWriter($file, ',', '"', '\\', false);
                 break;
             case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
                 $exporter = new XmlExcelWriter($file, false);
                 break;
         }
     }
     if ($exporter === false) {
         throw new \Exception("No or invalid format specified");
     }
     $content = json_decode($request->getContent(), true);
     $exporter->open();
     foreach ($content as $item) {
         $exporter->write($item);
     }
     $exporter->close();
     $exportData = file_get_contents($file);
     return new Response($exportData, 200);
 }
 /**
  * Replaces the default controller action with one that provides data in one of the requested formats
  *
  * @param FilterControllerEvent $event
  */
 public function onController(FilterControllerEvent $event)
 {
     $this->event = $event;
     $types = $this->request->getAcceptableContentTypes();
     $controller = null;
     foreach ($types as $type) {
         if ($controller = $this->findControllerForContentType($type)) {
             $this->event->setController($controller);
             break;
         }
     }
     if (null === $controller) {
         header('HTTP/1.0 406 Not Acceptable');
         die;
     }
     $controller = $event->getController();
     $this->logger->debug('Chose controller action "' . array_pop($controller) . '"');
 }
Пример #8
0
 private function getFormatFromHeaders(Request $request)
 {
     foreach ($request->getAcceptableContentTypes() as $acceptableContentType) {
         foreach ($this->contentTypeMapping as $contentType => $format) {
             if ($acceptableContentType === $contentType) {
                 return $format;
             }
         }
     }
 }
Пример #9
0
 /**
  * Returns acceptance type based on given request.
  *
  * @param Request $request
  *
  * @return string
  */
 public function checkAcceptHeader(Request $request)
 {
     $headers = $request->getAcceptableContentTypes();
     if (array_intersect($headers, ['application/json', 'text/json'])) {
         return 'json';
     } elseif (array_intersect($headers, ['application/xml', 'text/xml'])) {
         return 'xml';
     }
     return $this->defaultAcceptType;
 }
 /**
  * @param $request Request
  *
  * @return void
  */
 protected function setTargetPath(Request $request)
 {
     // Do not save target path for non HTML requests
     // Note that non-GET requests are already ignored
     $acceptableContentTypes = array_map('strtolower', $request->getAcceptableContentTypes());
     if (!in_array('text/html', $acceptableContentTypes) || $request->isXmlHttpRequest()) {
         return;
     }
     parent::setTargetPath($request);
 }
Пример #11
0
 public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
 {
     if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
         $data = json_decode($request->getContent(), true);
         $request->request->replace(is_array($data) ? $data : []);
     }
     if (in_array('application/json', $request->getAcceptableContentTypes())) {
         $request->setRequestFormat('json');
     }
     return $response = $this->app->handle($request, $type, $catch);
 }
Пример #12
0
 /**
  * @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]);
     }
 }
Пример #13
0
 public function createContexts(Request $request)
 {
     $map = array('request_method' => $request->getMethod(), 'request_uri' => $request->getRequestUri(), 'request_route' => $request->attributes->get('_route'), 'request_host' => $request->getHost(), 'request_port' => $request->getPort(), 'request_scheme' => $request->getScheme(), 'request_client_ip' => $request->getClientIp(), 'request_content_type' => $request->getContentType(), 'request_acceptable_content_types' => $request->getAcceptableContentTypes(), 'request_etags' => $request->getETags(), 'request_charsets' => $request->getCharsets(), 'request_languages' => $request->getLanguages(), 'request_locale' => $request->getLocale(), 'request_auth_user' => $request->getUser(), 'request_auth_has_password' => !is_null($request->getPassword()));
     // Attributes from newer versions.
     if (method_exists($request, 'getEncodings')) {
         $map['request_encodings'] = $request->getEncodings();
     }
     if (method_exists($request, 'getClientIps')) {
         $map['request_client_ips'] = $request->getClientIps();
     }
     return $map;
 }
 /**
  * Dispatches a visitable result to the mapped visitor
  *
  * @param \Symfony\Component\HttpFoundation\Request $request
  * @param mixed $result
  *
  * @throws NowViewFoundException
  *
  * @return Response
  */
 public function dispatch(Request $request, $result)
 {
     foreach ($request->getAcceptableContentTypes() as $mimeType) {
         /** @var \eZ\Publish\Core\REST\Common\Output\Visitor $visitor */
         foreach ($this->mapping as $regexp => $visitor) {
             if (preg_match($regexp, $mimeType)) {
                 return $visitor->visit($result);
             }
         }
     }
     throw new NowViewFoundException("No view mapping found.");
 }
 protected function logRequest(Request $request)
 {
     $msg = 'Request "{request_method} {request_uri}"';
     $map = array('request_method' => $request->getMethod(), 'request_uri' => $request->getRequestUri(), 'request_host' => $request->getHost(), 'request_port' => $request->getPort(), 'request_scheme' => $request->getScheme(), 'request_client_ip' => $request->getClientIp(), 'request_content_type' => $request->getContentType(), 'request_acceptable_content_types' => $request->getAcceptableContentTypes(), 'request_etags' => $request->getETags(), 'request_charsets' => $request->getCharsets(), 'request_languages' => $request->getLanguages(), 'request_locale' => $request->getLocale(), 'request_auth_user' => $request->getUser(), 'request_auth_has_password' => !is_null($request->getPassword()));
     // Attributes from newer versions.
     if (method_exists($request, 'getEncodings')) {
         $map['request_encodings'] = $request->getEncodings();
     }
     if (method_exists($request, 'getClientIps')) {
         $map['request_client_ips'] = $request->getClientIps();
     }
     $this->logger->log($this->logLevel, $msg, $map);
 }
Пример #16
0
 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);
         }
     }
 }
Пример #17
0
 private function getRendererFromRequest(Request $request)
 {
     if (null === ($contentType = $request->attributes->get('_content_type', null))) {
         $contentType = current($request->getAcceptableContentTypes());
     }
     if (null !== ($name = $request->attributes->get('_renderer', null))) {
         return $this->getRendererFromName($name);
     }
     if (0 === count($this->contentTypes)) {
         return $this->getRendererFromContentType($contentType);
     }
     if (false === array_key_exists($contentType, $this->contentTypes)) {
         return $this->getRendererFromContentType($contentType);
     }
     return $this->getRendererFromName($this->contentTypes[$contentType]);
 }
Пример #18
0
 private function parseResponseType()
 {
     if (trim($this->request->get('callback')) !== '') {
         return $this->responseType = self::FORMAT_JSONP;
     }
     $responseTypes = array_map('strtolower', $this->request->getAcceptableContentTypes());
     if (in_array('application/json', $responseTypes)) {
         return $this->responseType = self::FORMAT_JSON;
     }
     if (in_array('application/yaml', $responseTypes)) {
         return $this->responseType = self::FORMAT_YAML;
     }
     if (in_array('text/yaml', $responseTypes)) {
         return $this->responseType = self::FORMAT_YAML;
     }
     return $this->responseType = self::FORMAT_JSON;
 }
Пример #19
0
 public function locate(Request $request)
 {
     $pathInfo = $request->getPathInfo();
     $matches = [];
     foreach ($this->resources as $path => $item) {
         if (preg_match($path, $pathInfo, $matches)) {
             $accepts = array_intersect($item->getContentTypes(), $request->getAcceptableContentTypes());
             if (empty($accepts)) {
                 throw new NotAcceptable();
             }
             /** @var callable $factory */
             $factory = $item->getFactory();
             /** @var \RestArc\Http\Resource $resource */
             $resource = $factory();
             if (!$resource instanceof Resource) {
                 throw new \DomainException('Cant handle non \\RestArc\\Http\\Resource');
             }
             $resource->setPathParameters(array_slice($matches, 1));
             return $resource;
         }
     }
     return null;
 }
 /**
  * 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();
 }
Пример #21
0
 public function testGetAcceptableContentTypes()
 {
     $request = new Request();
     $this->assertEquals(array(), $request->getAcceptableContentTypes());
     $request->headers->set('Accept', 'application/vnd.wap.wmlscriptc, text/vnd.wap.wml, application/vnd.wap.xhtml+xml, application/xhtml+xml, text/html, multipart/mixed, */*');
     $this->assertEquals(array(), $request->getAcceptableContentTypes());
     // testing caching
     $request = new Request();
     $request->headers->set('Accept', 'application/vnd.wap.wmlscriptc, text/vnd.wap.wml, application/vnd.wap.xhtml+xml, application/xhtml+xml, text/html, multipart/mixed, */*');
     $this->assertEquals(array('application/vnd.wap.wmlscriptc', 'text/vnd.wap.wml', 'application/vnd.wap.xhtml+xml', 'application/xhtml+xml', 'text/html', 'multipart/mixed', '*/*'), $request->getAcceptableContentTypes());
 }
 /**
  * Get classcontent.
  *
  * @param string $type type of the class content (ex: Element/text)
  * @param string $uid  identifier of the class content
  *
  * @return Symfony\Component\HttpFoundation\Response
  *
  * @Rest\QueryParam(name="mode", description="The render mode to use")
  * @Rest\QueryParam(name="page_uid", description="The page to set to application's renderer before rendering")
  *
  * @Rest\Security("is_fully_authenticated() & has_role('ROLE_API_USER')")
  */
 public function getAction($type, $uid, Request $request)
 {
     $this->granted('VIEW', $content = $this->getClassContentByTypeAndUid($type, $uid, true));
     $response = null;
     if (in_array('text/html', $request->getAcceptableContentTypes())) {
         if (false != ($pageUid = $request->query->get('page_uid'))) {
             if (null !== ($page = $this->getDoctrine()->getManager()->find('BackBee\\CoreDomain\\NestedNode\\Page', $pageUid))) {
                 $this->get('renderer')->setCurrentPage($page);
             }
         }
         $mode = $request->query->get('mode', null);
         $response = $this->createResponse($this->get('renderer')->render($content, $mode), 200, 'text/html');
     } else {
         $response = $this->createJsonResponse();
         $response->setData($this->getClassContentManager()->jsonEncode($content, $this->getFormatParam()));
     }
     return $response;
 }
Пример #23
0
 /**
  * Authorize application to use a grant password type.
  *
  * @param Application    $app
  * @param Request        $request
  * @param ApiApplication $application
  *
  * @return JsonResponse
  */
 public function authorizeGrantPassword(Application $app, Request $request, ApiApplication $application)
 {
     if (!$request->isXmlHttpRequest() || !array_key_exists($request->getMimeType('json'), array_flip($request->getAcceptableContentTypes()))) {
         $app->abort(400, 'Bad request format, only JSON is allowed');
     }
     $application->setGrantPassword((bool) $request->request->get('grant'));
     $app['manipulator.api-application']->update($application);
     return $app->json(['success' => true]);
 }
Пример #24
0
 /**
  * Gets the error-relevant format from the request.
  *
  * @param \Symfony\Component\HttpFoundation\Request $request
  *   The request object.
  *
  * @return string
  *   The format as which to treat the exception.
  */
 protected function getFormat(Request $request)
 {
     $format = $request->query->get(MainContentViewSubscriber::WRAPPER_FORMAT, $request->getRequestFormat());
     // These are all JSON errors for our purposes. Any special handling for
     // them can/should happen in earlier listeners if desired.
     if (in_array($format, ['drupal_modal', 'drupal_dialog', 'drupal_ajax'])) {
         $format = 'json';
     }
     // Make an educated guess that any Accept header type that includes "json"
     // can probably handle a generic JSON response for errors. As above, for
     // any format this doesn't catch or that wants custom handling should
     // register its own exception listener.
     foreach ($request->getAcceptableContentTypes() as $mime) {
         if (strpos($mime, 'html') === FALSE && strpos($mime, 'json') !== FALSE) {
             $format = 'json';
         }
     }
     return $format;
 }
 /**
  * @param  \Symfony\Component\HttpFoundation\Request $request
  * @return bool
  */
 protected function isJsonRequest(Request $request)
 {
     // If XmlHttpRequest, return true
     if ($request->isXmlHttpRequest()) {
         return true;
     }
     // Check if the request wants Json
     $acceptable = $request->getAcceptableContentTypes();
     return isset($acceptable[0]) && $acceptable[0] == 'application/json';
 }
Пример #26
0
 public function deleteStatusBitAction(Request $request, $databox_id, $bit)
 {
     if (!$request->isXmlHttpRequest() || !array_key_exists($request->getMimeType('json'), array_flip($request->getAcceptableContentTypes()))) {
         $this->app->abort(400, $this->app->trans('Bad request format, only JSON is allowed'));
     }
     if (!$this->getAclForUser()->has_right_on_sbas($databox_id, 'bas_modify_struct')) {
         $this->app->abort(403);
     }
     $databox = $this->findDataboxById($databox_id);
     $error = false;
     try {
         $this->app['status.provider']->deleteStatus($databox->getStatusStructure(), $bit);
     } catch (\Exception $e) {
         $error = true;
     }
     return $this->app->json(['success' => !$error]);
 }
Пример #27
0
 /**
  * Get classcontent.
  *
  * @param string $type type of the class content (ex: Element/text)
  * @param string $uid  identifier of the class content
  *
  * @return Symfony\Component\HttpFoundation\Response
  *
  * @Rest\QueryParam(name="mode", description="The render mode to use")
  * @Rest\QueryParam(name="page_uid", description="The page to set to application's renderer before rendering")
  *
  * @Rest\ParamConverter(
  *   name="page", id_name="page_uid", id_source="query", class="BackBee\NestedNode\Page", required=false
  * )
  *
  * @Rest\Security("is_fully_authenticated() & has_role('ROLE_API_USER')")
  */
 public function getAction($type, $uid, Request $request)
 {
     $this->granted('VIEW', $content = $this->getClassContentByTypeAndUid($type, $uid, true));
     $response = null;
     if (in_array('text/html', $request->getAcceptableContentTypes())) {
         if (null !== ($page = $this->getEntityFromAttributes('page'))) {
             $this->getApplication()->getRenderer()->setCurrentPage($page);
         }
         $mode = $request->query->get('mode', null);
         $response = $this->createResponse($this->getApplication()->getRenderer()->render($content, $mode), 200, 'text/html');
     } else {
         $response = $this->createJsonResponse();
         $response->setData($this->getClassContentManager()->jsonEncode($content, $this->getFormatParam()));
     }
     return $response;
 }
Пример #28
0
 protected function getWriter(Request $request)
 {
     $attribute = $request->attributes->get(Context::RESPONSE_FORMAT);
     $query = $request->query->get('format');
     if (!empty($attribute)) {
         $writer = $this->writerFactory->getWriterByFormat($attribute);
     } elseif (!empty($query)) {
         $writer = $this->writerFactory->getWriterByFormat($query);
     } else {
         $writer = $this->writerFactory->getWriterByContentType(implode(', ', $request->getAcceptableContentTypes()));
     }
     if ($writer === null) {
         $writer = $this->writerFactory->getDefaultWriter();
     }
     return $writer;
 }
Пример #29
0
 /**
  * @param Request $request
  * @param Route $route
  * @return bool
  */
 private function matchContentType(Request $request, Route $route)
 {
     return !$route->getPattern()->getContentType() || in_array($route->getPattern()->getContentType(), $request->getAcceptableContentTypes());
 }
Пример #30
0
 /**
  * @param Request $request
  * @throws HttpException
  */
 private function assertJsonRequestFormat(Request $request)
 {
     if (!$request->isXmlHttpRequest() || !array_key_exists($request->getMimeType('json'), array_flip($request->getAcceptableContentTypes()))) {
         $this->app->abort(400, 'Bad request format, only JSON is allowed');
     }
 }