getMimeType() public method

Gets the mime type associated with the format.
public getMimeType ( string $format ) : string
$format string The format
return string The associated mime type (null if not found)
Example #1
0
 protected function doKernelResponse(Request $request, Response $response)
 {
     if (!$response instanceof DataResponse) {
         return;
     }
     $routeName = $request->attributes->get('_route');
     $route = $this->routes->get($routeName);
     if (!$route) {
         return;
     }
     $acceptedFormat = $route->getOption(RouteOptions::ACCEPTED_FORMAT);
     if (!$acceptedFormat) {
         $response->setContent('');
         $response->setStatusCode(406);
     }
     if ($this->encoder->supportsEncoding($acceptedFormat) && $acceptedFormat === 'json') {
         $contentType = $request->getMimeType($acceptedFormat);
         $jsonResponse = new JsonResponse($response->getContent());
         $response->setContent($jsonResponse->getContent());
         $response->headers->set('Content-Type', $contentType);
     } elseif ($this->encoder->supportsEncoding($acceptedFormat)) {
         $contentType = $request->getMimeType($acceptedFormat);
         $content = $this->encoder->encode($response->getContent(), $acceptedFormat);
         $response->setContent($content);
         $response->headers->set('Content-Type', $contentType);
     }
 }
Example #2
0
 /**
  * Detect the request format based on the priorities and the Accept header
  *
  * Note: Request "_format" parameter is considered the preferred Accept header
  *
  * @param   Request     $request          The request
  * @param   array       $priorities       Ordered array of formats (highest priority first)
  * @param   Boolean     $preferExtension  If to consider the extension last or first
  *
  * @return  void|string                 The format string
  */
 public function getBestFormat(Request $request, array $priorities, $preferExtension = false)
 {
     $mimetypes = $request->splitHttpAcceptHeader($request->headers->get('Accept'));
     $extension = $request->get('_format');
     if (null !== $extension && $request->getMimeType($extension)) {
         $mimetypes[$request->getMimeType($extension)] = $preferExtension ? reset($mimetypes) + 1 : end($mimetypes) - 1;
         arsort($mimetypes);
     }
     if (empty($mimetypes)) {
         return null;
     }
     $catchAllEnabled = in_array('*/*', $priorities);
     return $this->getFormatByPriorities($request, $mimetypes, $priorities, $catchAllEnabled);
 }
 /**
  * indexAction action.
  */
 public function indexAction(Request $request, $_format)
 {
     if (version_compare(Kernel::VERSION, '2.1.0-dev', '<')) {
         if (null !== ($session = $request->getSession())) {
             // keep current flashes for one more request
             $session->setFlashes($session->getFlashes());
         }
     } else {
         $session = $request->getSession();
         if (null !== $session && $session->getFlashBag() instanceof AutoExpireFlashBag) {
             // keep current flashes for one more request if using AutoExpireFlashBag
             $session->getFlashBag()->setAll($session->getFlashBag()->peekAll());
         }
     }
     $cache = new ConfigCache($this->cacheDir . '/fosJsRouting.json', $this->debug);
     if (!$cache->isFresh()) {
         $content = $this->serializer->serialize(new RoutesResponse($this->exposedRoutesExtractor->getBaseUrl(), $this->exposedRoutesExtractor->getRoutes()), 'json');
         $cache->write($content, $this->exposedRoutesExtractor->getResources());
     }
     $content = file_get_contents((string) $cache);
     if ($callback = $request->query->get('callback')) {
         $content = $callback . '(' . $content . ');';
     }
     return new Response($content, 200, array('Content-Type' => $request->getMimeType($_format)));
 }
 /**
  * Action point for js translation resource
  *
  * @param Request $request
  * @param string $_locale
  * @return Response
  */
 public function indexAction(Request $request, $_locale)
 {
     $domains = isset($this->options['domains']) ? $this->options['domains'] : [];
     $debug = isset($this->options['debug']) ? (bool) $this->options['debug'] : false;
     $content = $this->renderJsTranslationContent($domains, $_locale, $debug);
     return new Response($content, 200, ['Content-Type' => $request->getMimeType('js')]);
 }
 function get(Request $req)
 {
     $resourceName = $req->get('resource');
     if (!isset($this->module["resourceEntityMappings"][$resourceName])) {
         throw new NotFoundHttpException();
     }
     $entityClass = $this->module["namespace"] . $this->module["resourceEntityMappings"][$resourceName];
     // Filterer entities queried?
     if ($req->getQueryString() != null) {
         $querystring = $req->getQueryString();
         $criteria = array();
         $queryParts = \explode('&', $querystring);
         foreach ($queryParts as $queryPart) {
             $key_value = \explode('=', $queryPart);
             $criteria[$key_value[0]] = urldecode($key_value[1]);
         }
         $entities = $this->em->getRepository($entityClass)->findBy($criteria);
         // Single entity queried?
     } elseif ($req->get('id') != null) {
         $id = $req->get('id');
         $entity = $this->em->getRepository($entityClass)->find($id);
         $entities = array($entity);
     } else {
         $entities = $this->em->getRepository($entityClass)->findAll();
     }
     return new Response($this->serializer->serialize(array($resourceName => $entities), 'json'), 200, array('Content-Type' => $req->getMimeType('json')));
 }
 /**
  * @param ApiResponse $apiResponse to convert to a Symfony Response.
  * @param Request $request that needs this Response.
  *
  * @return Response
  */
 public function toSymfonyResponse(ApiResponse $apiResponse, Request $request)
 {
     $format = $request->getRequestFormat($this->defaultResponseFormat);
     $serialized = $this->serializer->serialize($apiResponse->getData(), $format);
     $response = new Response($serialized, $apiResponse->getStatusCode(), $apiResponse->getHeaders());
     $response->headers->set('Content-Type', $request->getMimeType($format));
     return $response;
 }
 /**
  * Deliver the result of the query.
  */
 public function handle(RouteMatchInterface $route_match, Request $request)
 {
     $query = new RestEntityQuery($request, $this->container);
     $serializer = $this->container->get('serializer');
     $format = $request->getMimeType() ?: 'json';
     $headers = ['Content-Type' => $format, 'Access-Control-Allow-Origin' => '*', 'Access-Control-Allow-Methods' => 'GET'];
     $content = $query->execute();
     if ($query->hasError()) {
         return new Response($serializer->serialize($query->getLastError(), $format), 400, $headers);
     }
     return new Response($serializer->serialize($content, 'json'), 200, $headers);
 }
 /**
  * indexAction action.
  */
 public function indexAction(Request $request, $_format)
 {
     $cache = new ConfigCache($this->cacheDir . '/fosJsRouting.json', $this->debug);
     if (!$cache->isFresh()) {
         $content = $this->serializer->serialize(new RoutesResponse($this->exposedRoutesExtractor->getBaseUrl(), $this->exposedRoutesExtractor->getRoutes()), 'json');
         $cache->write($content, $this->exposedRoutesExtractor->getResources());
     }
     $content = file_get_contents((string) $cache);
     if ($callback = $request->query->get('callback')) {
         $content = $callback . '(' . $content . ')';
     }
     return new Response($content, 200, array('Content-Type' => $request->getMimeType($_format)));
 }
 /**
  * Detect the request format based on the priorities and the Accept header
  *
  * Note: Request "_format" parameter is considered the preferred Accept header
  *
  * @param   Request     $request          The request
  * @param   array       $priorities       Ordered array of formats (highest priority first)
  * @param   Boolean     $preferExtension  If to consider the extension last or first
  *
  * @return  void|string                 The format string
  */
 public function getBestFormat(Request $request, array $priorities, $preferExtension = false)
 {
     // BC - Maintain this while 2.0 and 2.1 dont reach their end of life
     // Note: Request::splitHttpAcceptHeader is deprecated since version 2.2, to be removed in 2.3.
     if (class_exists('Symfony\\Component\\HttpFoundation\\AcceptHeader')) {
         $mimetypes = array();
         foreach (AcceptHeader::fromString($request->headers->get('Accept'))->all() as $item) {
             $mimetypes[$item->getValue()] = $item->getQuality();
         }
     } else {
         $mimetypes = $request->splitHttpAcceptHeader($request->headers->get('Accept'));
     }
     $extension = $request->get('_format');
     if (null !== $extension && $request->getMimeType($extension)) {
         $mimetypes[$request->getMimeType($extension)] = $preferExtension ? reset($mimetypes) + 1 : end($mimetypes) - 1;
         arsort($mimetypes);
     }
     if (empty($mimetypes)) {
         return null;
     }
     $catchAllEnabled = in_array('*/*', $priorities);
     return $this->getFormatByPriorities($request, $mimetypes, $priorities, $catchAllEnabled);
 }
Example #10
0
 /**
  * Prepares the Response before it is sent to the client.
  *
  * This method tweaks the Response to ensure that it is
  * compliant with RFC 2616. Most of the changes are based on
  * the Request that is "associated" with this Response.
  *
  * @param Request $request A Request instance
  *
  * @return Response The current response.
  */
 public function prepare(Request $request)
 {
     $headers = $this->headers;
     if ($this->isInformational() || $this->isEmpty()) {
         $this->setContent(null);
         $headers->remove('Content-Type');
         $headers->remove('Content-Length');
     } else {
         // Content-type based on the Request
         if (!$headers->has('Content-Type')) {
             $format = $request->getRequestFormat();
             if (null !== $format && ($mimeType = $request->getMimeType($format))) {
                 $headers->set('Content-Type', $mimeType);
             }
         }
         // Fix Content-Type
         $charset = $this->charset ?: 'UTF-8';
         if (!$headers->has('Content-Type')) {
             $headers->set('Content-Type', 'text/html; charset=' . $charset);
         } elseif (0 === stripos($headers->get('Content-Type'), 'text/') && false === stripos($headers->get('Content-Type'), 'charset')) {
             // add the charset
             $headers->set('Content-Type', $headers->get('Content-Type') . '; charset=' . $charset);
         }
         // Fix Content-Length
         if ($headers->has('Transfer-Encoding')) {
             $headers->remove('Content-Length');
         }
         if ($request->isMethod('HEAD')) {
             // cf. RFC2616 14.13
             $length = $headers->get('Content-Length');
             $this->setContent(null);
             if ($length) {
                 $headers->set('Content-Length', $length);
             }
         }
     }
     // Fix protocol
     if ('HTTP/1.0' != $request->server->get('SERVER_PROTOCOL')) {
         $this->setProtocolVersion('1.1');
     }
     // Check if we need to send extra expire info headers
     if ('1.0' == $this->getProtocolVersion() && 'no-cache' == $this->headers->get('Cache-Control')) {
         $this->headers->set('pragma', 'no-cache');
         $this->headers->set('expires', -1);
     }
     $this->ensureIEOverSSLCompatibility($request);
     return $this;
 }
 /**
  * Returns a response containing the given image after applying the given filter on it.
  *
  * @uses FilterManager::applyFilterSet
  *
  * @param Request $request
  * @param string $filter
  * @param ImageInterface $image
  * @param string $localPath
  *
  * @return Response
  */
 public function get(Request $request, $filter, ImageInterface $image, $localPath)
 {
     $config = $this->getFilterConfiguration()->get($filter);
     $image = $this->applyFilter($image, $filter);
     if (empty($config['format'])) {
         $format = pathinfo($localPath, PATHINFO_EXTENSION);
         $format = $format ?: 'png';
     } else {
         $format = $config['format'];
     }
     $quality = empty($config['quality']) ? 100 : $config['quality'];
     $image = $image->get($format, array('quality' => $quality));
     $contentType = $request->getMimeType($format);
     if (empty($contentType)) {
         $contentType = 'image/' . $format;
     }
     return new Response($image, 200, array('Content-Type' => $contentType));
 }
 /**
  * @Route("/js/filemanager.{_format}", name="novaway_filemanagement_routing_js", defaults={"_format"="js"})
  */
 public function indexAction(Request $request, $_format)
 {
     $serviceManagerId = $request->get('service_manager');
     if (empty($serviceManagerId)) {
         throw new \RuntimeException('service_manager argument is missing.');
     }
     if (!$this->has($serviceManagerId)) {
         throw new NotFoundHttpException(sprintf('The %s service does not exist.', $serviceManagerId));
     }
     /** @var \Novaway\Bundle\FileManagementBundle\Manager\BaseEntityWithImageManager $manager */
     $manager = $this->get($serviceManagerId);
     if (!$manager instanceof BaseEntityWithImageManager) {
         throw new \RuntimeException('The manager must be an instance of BaseEntityWithImageManager.');
     }
     $content = json_encode(['webpath' => $manager->getWebPath(), 'image_formats' => $manager->getImageFormatChoices()]);
     if (null !== ($jsManager = $request->query->get('manager'))) {
         $content = "var {$jsManager} = new novaway.FileManager(); {$jsManager}.setData({$content});";
     }
     return new Response($content, 200, array('Content-Type' => $request->getMimeType($_format)));
 }
 /**
  * Main action: renders the image cache and returns it to the browser
  *
  * @param Request $request
  * @param string $format A format name defined in config or a string [width]x[height]
  * @param string $path The path of the source file (@see Manager::downloadExternalImage for more info on external/remote images)
  *
  * @return Response
  */
 public function indexAction(Request $request, $format, $path)
 {
     /** @var $im \Snowcap\ImBundle\Manager */
     $im = $this->get("snowcap_im.manager");
     if (strpos($path, "http/") === 0 || strpos($path, "https/") === 0) {
         $newPath = $im->downloadExternalImage($format, $path);
         $im->mogrify($format, $newPath);
     } else {
         $im->convert($format, $path);
     }
     if (!$im->cacheExists($format, $path)) {
         throw new RuntimeException(sprintf("Caching of image failed for %s in %s format", $path, $format));
     } else {
         $extension = pathinfo($path, PATHINFO_EXTENSION);
         $contentType = $request->getMimeType($extension);
         if (empty($contentType)) {
             $contentType = 'image/' . $extension;
         }
         return new Response($im->getCacheContent($format, $path), 200, array('Content-Type' => $contentType));
     }
 }
Example #14
0
 public function showAction(Request $request)
 {
     $showid = $request->query->get('showid');
     $type = $request->query->get('type');
     if ($type != 'json') {
         $type = 'xml';
     }
     $repo = $this->getDoctrine()->getManager()->getRepository('ActsCamdramBundle:Show');
     $show = $repo->findOneBySlug($showid);
     if (!$show) {
         if (is_numeric($showid)) {
             $show = $repo->find($showid);
         }
     }
     if (!$show) {
         throw $this->createNotFoundException('That show does not exist.');
     }
     $apiShow = new ApiShow($show, $this->get('router'));
     $serializer = $this->get('jms_serializer');
     $response = new Response($serializer->serialize($apiShow, $type));
     $response->headers->set('content-type', $request->getMimeType($type));
     return $response;
 }
Example #15
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]);
 }
 /**
  * exposeTranslationAction action.
  */
 public function exposeTranslationAction(Request $request, $domain_name, $_locale, $_format)
 {
     $cache = new ConfigCache($this->cacheDir . '/' . $domain_name . '.' . $_locale . "." . $_format, $this->debug);
     if (!$cache->isFresh()) {
         $files = $this->translationFinder->getResources($domain_name, $_locale);
         $resources = array();
         $catalogues = array();
         foreach (iterator_to_array($files) as $file) {
             $extension = pathinfo($file->getFilename(), \PATHINFO_EXTENSION);
             if (isset($this->loaders[$extension])) {
                 $resources[] = new FileResource($file->getPath());
                 $catalogues[] = $this->loaders[$extension]->load($file, $_locale, $domain_name);
             }
         }
         $messages = array();
         foreach ($catalogues as $catalogue) {
             $messages = array_merge_recursive($messages, $catalogue->all());
         }
         $content = $this->engine->render('BazingaExposeTranslationBundle::exposeTranslation.' . $_format . '.twig', array('messages' => $messages, 'locale' => $_locale, 'defaultDomains' => $this->defaultDomains));
         $cache->write($content, $resources);
     }
     $content = file_get_contents((string) $cache);
     return new Response($content, 200, array('Content-Type' => $request->getMimeType($_format)));
 }
 /**
  * Transform the format (json, html, ...) to their mimeType form (application/json, text/html, ...).
  *
  * @param Request $request
  * @param array   $priorities
  *
  * @return array formated priorities
  */
 protected function normalizePriorities(Request $request, $priorities)
 {
     $priorities = $this->sanitize($priorities);
     $mimeTypes = array();
     foreach ($priorities as $priority) {
         if (strpos($priority, '/')) {
             $mimeTypes[] = $priority;
             continue;
         }
         if (isset($this->mimeTypes[$priority])) {
             foreach ($this->mimeTypes[$priority] as $mimeType) {
                 $mimeTypes[] = $mimeType;
             }
         } elseif (($mimeType = $request->getMimeType($priority)) !== null) {
             $mimeTypes[] = $mimeType;
         }
     }
     return $mimeTypes;
 }
 /**
  * Display authorized applications that can access user information
  *
  * @param Request        $request
  * @param ApiApplication $application
  *
  * @return JsonResponse
  */
 public function grantAccess(Request $request, ApiApplication $application)
 {
     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 (null === ($account = $this->getApiAccountRepository()->findByUserAndApplication($this->getAuthenticatedUser(), $application))) {
         return $this->app->json(['success' => false]);
     }
     $manipulator = $this->getApiAccountManipulator();
     if (false === (bool) $request->query->get('revoke')) {
         $manipulator->authorizeAccess($account);
     } else {
         $manipulator->revokeAccess($account);
     }
     return $this->app->json(['success' => true]);
 }
Example #19
0
 public function testGetMimeTypesFromInexistentFormat()
 {
     $request = new Request();
     $this->assertNull($request->getMimeType('foo'));
     $this->assertEquals(array(), Request::getMimeTypes('foo'));
 }
Example #20
0
 /**
  * Display authorized applications that can access user informations
  *
  * @param Application $app            A Silex application where the controller is mounted on
  * @param Request     $request        The current request
  * @param Integer     $application_id The application id
  *
  * @return JsonResponse
  */
 public function grantAccess(Application $app, Request $request, $application_id)
 {
     if (!$request->isXmlHttpRequest() || !array_key_exists($request->getMimeType('json'), array_flip($request->getAcceptableContentTypes()))) {
         $app->abort(400, $app->trans('Bad request format, only JSON is allowed'));
     }
     $error = false;
     try {
         $account = \API_OAuth2_Account::load_with_user($app, new \API_OAuth2_Application($app, $application_id), $app['authentication']->getUser());
         $account->set_revoked((bool) $request->query->get('revoke'), false);
     } catch (NotFoundHttpException $e) {
         $error = true;
     }
     return $app->json(['success' => !$error]);
 }
 /**
  * deleteId Autor
  *
  */
 public function deleteId(Application $app, Request $request, $id)
 {
     $em = $app['db.orm.em'];
     $entity = $em->getRepository('Entity\\Autor')->find($id);
     if (!$entity) {
         $app->abort(404, 'No entity found for id ' . $id);
     }
     $em->remove($entity);
     $em->flush();
     return new Response($app['serializer']->serialize(['success' => true], 'json'), 200, array('Content-Type' => $request->getMimeType('json')));
 }
 /**
  * @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');
     }
 }
Example #23
0
 /**
  * @covers Symfony\Component\HttpFoundation\Request::getMimeType
  * @dataProvider getFormatToMimeTypeMapProvider
  */
 public function testGetMimeTypeFromFormat($format, $mimeTypes)
 {
     if (null !== $format) {
         $request = new Request();
         $this->assertEquals($mimeTypes[0], $request->getMimeType($format));
     }
 }
Example #24
0
 /**
  * Handles creation of a Response using either redirection or the templating/serializer service.
  *
  * @param View    $view
  * @param Request $request
  * @param string  $format
  *
  * @return Response
  */
 public function createResponse(View $view, Request $request, $format)
 {
     $route = $view->getRoute();
     $location = $route ? $this->urlGenerator->generate($route, (array) $view->getRouteParameters(), UrlGeneratorInterface::ABSOLUTE_URL) : $view->getLocation();
     if ($location) {
         return $this->createRedirectResponse($view, $location, $format);
     }
     $response = $this->initResponse($view, $format);
     if (!$response->headers->has('Content-Type')) {
         $response->headers->set('Content-Type', $request->getMimeType($format));
     }
     return $response;
 }
Example #25
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]);
 }
Example #26
0
 /**
  * Handles creation of a Response using either redirection or the templating/serializer service
  *
  * @param View    $view
  * @param Request $request
  * @param string  $format
  *
  * @return Response
  */
 public function createResponse(View $view, Request $request, $format)
 {
     $headers = $view->getHeaders();
     if (empty($headers['Content-Type'])) {
         $view->setHeader('Content-Type', $request->getMimeType($format));
     }
     $route = $view->getRoute();
     $location = $route ? $this->getRouter()->generate($route, (array) $view->getData(), true) : $view->getLocation();
     if ($location) {
         return $this->createRedirectResponse($view, $location, $format);
     }
     if ($this->isFormatTemplating($format)) {
         $content = $this->renderTemplate($view, $format);
     } else {
         $serializer = $this->getSerializer($view);
         $content = $serializer->serialize($view->getData(), $format);
     }
     return new Response($content, $this->getStatusCode($view), $view->getHeaders());
 }
Example #27
0
 /**
  * Handles a web API request.
  *
  * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
  *   The route match.
  * @param \Symfony\Component\HttpFoundation\Request $request
  *   The HTTP request object.
  *
  * @return \Symfony\Component\HttpFoundation\Response
  *   The response object.
  */
 public function handle(RouteMatchInterface $route_match, Request $request)
 {
     $plugin = $route_match->getRouteObject()->getDefault('_plugin');
     $method = strtolower($request->getMethod());
     // Symfony is built to transparently map HEAD requests to a GET request. In
     // the case of the REST module's RequestHandler though, we essentially have
     // our own light-weight routing system on top of the Drupal/symfony routing
     // system. So, we have to do the same as what the UrlMatcher does: map HEAD
     // requests to the logic for GET. This also guarantees response headers for
     // HEAD requests are identical to those for GET requests, because we just
     // return a GET response. Response::prepare() will transform it to a HEAD
     // response at the very last moment.
     // @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4
     // @see \Symfony\Component\Routing\Matcher\UrlMatcher::matchCollection()
     // @see \Symfony\Component\HttpFoundation\Response::prepare()
     if ($method === 'head') {
         $method = 'get';
     }
     $resource = $this->container->get('plugin.manager.rest')->getInstance(array('id' => $plugin));
     // Deserialize incoming data if available.
     $serializer = $this->container->get('serializer');
     $received = $request->getContent();
     $unserialized = NULL;
     if (!empty($received)) {
         $format = $request->getContentType();
         // Only allow serialization formats that are explicitly configured. If no
         // formats are configured allow all and hope that the serializer knows the
         // format. If the serializer cannot handle it an exception will be thrown
         // that bubbles up to the client.
         $config = $this->container->get('config.factory')->get('rest.settings')->get('resources');
         $method_settings = $config[$plugin][$request->getMethod()];
         if (empty($method_settings['supported_formats']) || in_array($format, $method_settings['supported_formats'])) {
             $definition = $resource->getPluginDefinition();
             $class = $definition['serialization_class'];
             try {
                 $unserialized = $serializer->deserialize($received, $class, $format, array('request_method' => $method));
             } catch (UnexpectedValueException $e) {
                 $error['error'] = $e->getMessage();
                 $content = $serializer->serialize($error, $format);
                 return new Response($content, 400, array('Content-Type' => $request->getMimeType($format)));
             }
         } else {
             throw new UnsupportedMediaTypeHttpException();
         }
     }
     // Determine the request parameters that should be passed to the resource
     // plugin.
     $route_parameters = $route_match->getParameters();
     $parameters = array();
     // Filter out all internal parameters starting with "_".
     foreach ($route_parameters as $key => $parameter) {
         if ($key[0] !== '_') {
             $parameters[] = $parameter;
         }
     }
     // Invoke the operation on the resource plugin.
     // All REST routes are restricted to exactly one format, so instead of
     // parsing it out of the Accept headers again, we can simply retrieve the
     // format requirement. If there is no format associated, just pick JSON.
     $format = $route_match->getRouteObject()->getRequirement('_format') ?: 'json';
     try {
         $response = call_user_func_array(array($resource, $method), array_merge($parameters, array($unserialized, $request)));
     } catch (HttpException $e) {
         $error['error'] = $e->getMessage();
         $content = $serializer->serialize($error, $format);
         // Add the default content type, but only if the headers from the
         // exception have not specified it already.
         $headers = $e->getHeaders() + array('Content-Type' => $request->getMimeType($format));
         return new Response($content, $e->getStatusCode(), $headers);
     }
     if ($response instanceof ResourceResponse) {
         $data = $response->getResponseData();
         // Serialization can invoke rendering (e.g., generating URLs), but the
         // serialization API does not provide a mechanism to collect the
         // bubbleable metadata associated with that (e.g., language and other
         // contexts), so instead, allow those to "leak" and collect them here in
         // a render context.
         // @todo Add test coverage for language negotiation contexts in
         //   https://www.drupal.org/node/2135829.
         $context = new RenderContext();
         $output = $this->container->get('renderer')->executeInRenderContext($context, function () use($serializer, $data, $format) {
             return $serializer->serialize($data, $format);
         });
         $response->setContent($output);
         if (!$context->isEmpty()) {
             $response->addCacheableDependency($context->pop());
         }
         $response->headers->set('Content-Type', $request->getMimeType($format));
         // Add rest settings config's cache tags.
         $response->addCacheableDependency($this->container->get('config.factory')->get('rest.settings'));
     }
     return $response;
 }
Example #28
0
 /**
  * Transform the format (json, html, ...) to their mimeType form (application/json, text/html, ...).
  *
  * @param Request  $request
  * @param string[] $priorities
  *
  * @return string[] formatted priorities
  */
 private function normalizePriorities(Request $request, array $priorities)
 {
     $priorities = $this->sanitize($priorities);
     $mimeTypes = array();
     foreach ($priorities as $priority) {
         if (strpos($priority, '/')) {
             $mimeTypes[] = $priority;
             continue;
         }
         if (method_exists(Request::class, 'getMimeTypes')) {
             $mimeTypes = array_merge($mimeTypes, Request::getMimeTypes($priority));
         } elseif (null !== $request->getMimeType($priority)) {
             $class = new \ReflectionClass(Request::class);
             $properties = $class->getStaticProperties();
             $mimeTypes = array_merge($mimeTypes, $properties['formats'][$priority]);
         }
         if (isset($this->mimeTypes[$priority])) {
             foreach ($this->mimeTypes[$priority] as $mimeType) {
                 $mimeTypes[] = $mimeType;
             }
         }
     }
     return $mimeTypes;
 }
Example #29
0
 /**
  * indexAction action.
  */
 public function indexAction(Request $request, $_format)
 {
     $session = $request->getSession();
     if ($request->hasPreviousSession() && $session->getFlashBag() instanceof AutoExpireFlashBag) {
         // keep current flashes for one more request if using AutoExpireFlashBag
         $session->getFlashBag()->setAll($session->getFlashBag()->peekAll());
     }
     $cache = new ConfigCache($this->exposedRoutesExtractor->getCachePath($request->getLocale()), $this->debug);
     if (!$cache->isFresh()) {
         $exposedRoutes = $this->exposedRoutesExtractor->getRoutes();
         $serializedRoutes = $this->serializer->serialize($exposedRoutes, 'json');
         $cache->write($serializedRoutes, $this->exposedRoutesExtractor->getResources());
     } else {
         $serializedRoutes = file_get_contents((string) $cache);
         $exposedRoutes = $this->serializer->deserialize($serializedRoutes, 'Symfony\\Component\\Routing\\RouteCollection', 'json');
     }
     $routesResponse = new RoutesResponse($this->exposedRoutesExtractor->getBaseUrl(), $exposedRoutes, $this->exposedRoutesExtractor->getPrefix($request->getLocale()), $this->exposedRoutesExtractor->getHost(), $this->exposedRoutesExtractor->getScheme(), $request->getLocale());
     $content = $this->serializer->serialize($routesResponse, 'json');
     if (null !== ($callback = $request->query->get('callback'))) {
         $validator = new \JsonpCallbackValidator();
         if (!$validator->validate($callback)) {
             throw new HttpException(400, 'Invalid JSONP callback value');
         }
         $content = $callback . '(' . $content . ');';
     }
     $response = new Response($content, 200, array('Content-Type' => $request->getMimeType($_format)));
     $this->cacheControlConfig->apply($response);
     return $response;
 }
 /**
  * Handles creation of a Response using either redirection or the templating/serializer service
  *
  * @param View    $view
  * @param Request $request
  * @param string  $format
  *
  * @return Response
  */
 public function createResponse(View $view, Request $request, $format)
 {
     $route = $view->getRoute();
     $location = $route ? $this->getRouter()->generate($route, (array) $view->getData(), true) : $view->getLocation();
     if ($location) {
         return $this->createRedirectResponse($view, $location, $format);
     }
     $content = null;
     if ($this->isFormatTemplating($format)) {
         $content = $this->renderTemplate($view, $format);
     } elseif ($this->serializeNull || null !== $view->getData()) {
         $serializer = $this->getSerializer($view);
         if ($serializer instanceof Serializer) {
             $context = $this->getSerializationContext($view);
             $content = $serializer->serialize($view->getData(), $format, $context);
         } else {
             $content = $serializer->serialize($view->getData(), $format);
         }
     }
     $response = $view->getResponse();
     $response->setStatusCode($this->getStatusCode($view, $content));
     if (null !== $content) {
         $response->setContent($content);
     }
     if (!$response->headers->has('Content-Type')) {
         $response->headers->set('Content-Type', $request->getMimeType($format));
     }
     return $response;
 }