getContentType() public method

Gets the format associated with the request.
public getContentType ( ) : string | null
return string | null The format (null if no content type is present)
Example #1
0
 /**
  * @return array
  */
 public function getPostData()
 {
     if ('json' === $this->_internalRequest->getContentType()) {
         return (array) json_decode($this->_internalRequest->getContent(), true);
     } else {
         return $this->_internalRequest->request->all();
     }
 }
 /**
  * {@inheritdoc}
  */
 public function filter(RouteCollection $collection, Request $request)
 {
     // The Content-type header does not make sense on GET requests, because GET
     // requests do not carry any content. Nothing to filter in this case.
     if ($request->isMethod('GET')) {
         return $collection;
     }
     $format = $request->getContentType();
     foreach ($collection as $name => $route) {
         $supported_formats = array_filter(explode('|', $route->getRequirement('_content_type_format')));
         if (empty($supported_formats)) {
             // No restriction on the route, so we move the route to the end of the
             // collection by re-adding it. That way generic routes sink down in the
             // list and exact matching routes stay on top.
             $collection->add($name, $route);
         } elseif (!in_array($format, $supported_formats)) {
             $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 415.
     throw new UnsupportedMediaTypeHttpException('No route found that matches "Content-Type: ' . $request->headers->get('Content-Type') . '"');
 }
Example #3
0
 /**
  * @param Request $request
  * @return JsonRpcRequest
  * @throws RpcException
  */
 public function createRequest(Request $request)
 {
     if (!$request->isMethod('POST')) {
         throw new InvalidRequestException(self::MESSAGE_INVALID_HTTP_METHOD);
     }
     if ($request->getContentType() != 'json') {
         throw new InvalidRequestException(self::MESSAGE_INVALID_CONTENT_TYPE);
     }
     $data = json_decode($request->getContent(), true);
     if (empty($data)) {
         throw new RequestParseException(self::MESSAGE_INVALID_BODY);
     }
     if (empty($data['jsonrpc'])) {
         throw new InvalidRequestException(self::MESSAGE_JSON_RPC_REQUIRED);
     }
     if (empty($data['id'])) {
         throw new InvalidRequestException(self::MESSAGE_ID_REQUIRED);
     }
     if (empty($data['method'])) {
         throw new InvalidRequestException(self::MESSAGE_METHOD_REQUIRED);
     }
     if (!isset($data['params'])) {
         throw new InvalidRequestException(self::MESSAGE_METHOD_PARAMS_REQUIRED);
     }
     if (!is_array($data['params'])) {
         throw new InvalidRequestException(self::MESSAGE_METHOD_PARAMS_TYPE);
     }
     return new JsonRpcRequest($request, $data['jsonrpc'], $data['id'], $data['method'], $data['params']);
 }
 /**
  * {@inheritdoc}
  */
 public function apply(Request $request, ParamConverter $configuration)
 {
     $options = (array) $configuration->getOptions();
     if (isset($options['deserializationContext']) && is_array($options['deserializationContext'])) {
         $arrayContext = array_merge($this->context, $options['deserializationContext']);
     } else {
         $arrayContext = $this->context;
     }
     $this->configureContext($context = new Context(), $arrayContext);
     try {
         $object = $this->serializer->deserialize($request->getContent(), $configuration->getClass(), $request->getContentType(), $context);
     } catch (UnsupportedFormatException $e) {
         throw new UnsupportedMediaTypeHttpException($e->getMessage(), $e);
     } catch (JMSSerializerException $e) {
         throw new BadRequestHttpException($e->getMessage(), $e);
     } catch (SymfonySerializerException $e) {
         throw new BadRequestHttpException($e->getMessage(), $e);
     }
     $request->attributes->set($configuration->getName(), $object);
     if (null !== $this->validator) {
         $validatorOptions = $this->getValidatorOptions($options);
         $errors = $this->validator->validate($object, null, $validatorOptions['groups']);
         $request->attributes->set($this->validationErrorsArgument, $errors);
     }
     return true;
 }
Example #5
0
    public function testGetContentType()
    {
        $request = new Request();
        $contentType = $request->getContentType();

        $this->assertNull($contentType);
    }
 /**
  * Handles a web API request.
  *
  * @param Symfony\Component\HttpFoundation\Request $request
  *   The HTTP request object.
  *
  * @return \Symfony\Component\HttpFoundation\Response
  *   The response object.
  */
 public function handle(Request $request)
 {
     $route = $request->attributes->get(RouteObjectInterface::ROUTE_OBJECT);
     $plugin = $route->getDefault('_plugin');
     $operation = $route->getRequirement('_operation');
     $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');
         $enabled_formats = isset($config[$plugin][$request->getMethod()]) ? $config[$plugin][$request->getMethod()] : array();
         if (empty($enabled_formats) || isset($enabled_formats[$format])) {
             $unserialized = json_decode($received);
             //        $definition = $resource->getDefinition();
             //        $class = $definition['serialization_class'];
             //        try {
             //          $unserialized = $serializer->deserialize($received, $class, $format);
             //        }
             //        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();
         }
     }
     // 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 HAL.
     $format = $request->attributes->get(RouteObjectInterface::ROUTE_OBJECT)->getRequirement('_format') ?: 'hal_json';
     try {
         $operation_annotation = $resource->getMethodAnnotation($operation);
         $arguments = $this->getArguments($operation_annotation, $request, $unserialized);
         $response = $resource->{$operation}($arguments, $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);
     }
     // Serialize the outgoing data for the response, if available.
     $data = $response->getResponseData();
     if ($data != NULL) {
         $output = $serializer->serialize($data, $format);
         $response->setContent($output);
         $response->headers->set('Content-Type', $request->getMimeType($format));
     }
     return $response;
 }
 /**
  * @param Request $request
  * @return array
  */
 private function prepareOptions(Request $request)
 {
     $options = array(CURLOPT_POST => 1, CURLOPT_HEADER => 0, CURLOPT_URL => $request->getSchemeAndHttpHost() . $request->getRequestUri(), CURLOPT_FRESH_CONNECT => 1, CURLOPT_RETURNTRANSFER => 1, CURLOPT_FORBID_REUSE => 1, CURLOPT_TIMEOUT => 20, CURLOPT_POSTFIELDS => $request->getContent(), CURLOPT_SSL_VERIFYHOST => false, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_HTTPHEADER => array('Content-Type: ' . $request->getContentType(), 'Content-Length: ' . strlen($request->getContent())));
     foreach ($this->options as $key => $value) {
         $options[$key] = $value;
     }
     return $options;
 }
Example #8
0
 /**
  * {@inheritdoc}
  */
 public function processRequest(Request $request, Route $route)
 {
     if (in_array($request->getMethod(), ['POST', 'PUT']) && 'json' === $request->getContentType()) {
         $parameters = json_decode($request->getContent(), true);
         if (is_array($parameters)) {
             $request->request->replace($parameters);
         }
     }
 }
Example #9
0
 /**
  * {@inheritdoc}
  */
 public function processRequest(Request $request, RouteMatchInterface $route_match, SerializerInterface $serializer)
 {
     if ($serializer instanceof DecoderInterface) {
         $content = $serializer->decode($request->getContent(), $request->getContentType());
     } else {
         throw new HttpException(500, $this->t("The appropriate DecoderInterface was not found."));
     }
     if (!isset($content)) {
         throw new HttpException(500, $this->t("The content of the request was empty."));
     }
     $flood_config = $this->configFactory->get('user.flood');
     $username = $content['username'];
     $password = $content['password'];
     // Flood protection: this is very similar to the user login form code.
     // @see \Drupal\user\Form\UserLoginForm::validateAuthentication()
     // Do not allow any login from the current user's IP if the limit has been
     // reached. Default is 50 failed attempts allowed in one hour. This is
     // independent of the per-user limit to catch attempts from one IP to log
     // in to many different user accounts.  We have a reasonably high limit
     // since there may be only one apparent IP for all users at an institution.
     if ($this->flood->isAllowed('services.failed_login_ip', $flood_config->get('ip_limit'), $flood_config->get('ip_window'))) {
         $accounts = $this->entityManager->getStorage('user')->loadByProperties(array('name' => $username, 'status' => 1));
         $account = reset($accounts);
         if ($account) {
             if ($flood_config->get('uid_only')) {
                 // Register flood events based on the uid only, so they apply for any
                 // IP address. This is the most secure option.
                 $identifier = $account->id();
             } else {
                 // The default identifier is a combination of uid and IP address. This
                 // is less secure but more resistant to denial-of-service attacks that
                 // could lock out all users with public user names.
                 $identifier = $account->id() . '-' . $request->getClientIP();
             }
             // Don't allow login if the limit for this user has been reached.
             // Default is to allow 5 failed attempts every 6 hours.
             if ($this->flood->isAllowed('services.failed_login_user', $flood_config->get('user_limit'), $flood_config->get('user_window'), $identifier)) {
                 $uid = $this->userAuth->authenticate($username, $password);
                 if ($uid) {
                     $this->flood->clear('services.failed_login_user', $identifier);
                     $this->session->start();
                     user_login_finalize($account);
                     drupal_set_message(t('User succesffully logged in'), 'status', FALSE);
                     return ['id' => $this->session->getId(), 'name' => $this->session->getName()];
                     //return $this->entityManager->getStorage('user')->load($uid);
                 } else {
                     // Register a per-user failed login event.
                     $this->flood->register('services.failed_login_user', $flood_config->get('user_window'), $identifier);
                 }
             }
         }
     }
     // Always register an IP-based failed login event.
     $this->flood->register('services.failed_login_ip', $flood_config->get('ip_window'));
     return [];
 }
 /**
  * Avoid return 2xx if the body is empty and form isn't submit
  *
  * @param Request $request
  * @param Form    $form
  *
  * @return Form|JsonResponse
  */
 protected function formError(Request $request, Form $form)
 {
     if (empty(json_decode($request->getContent(), true))) {
         return new JsonResponse(['errors' => [$this->t('core.error.empty_json')]], JsonResponse::HTTP_BAD_REQUEST);
     }
     if ('json' !== $request->getContentType()) {
         return $this->createJsonError('core.error.bad_content_type', JsonResponse::HTTP_BAD_REQUEST);
     }
     return $form;
 }
 public function apply(Request $request, ParamConverter $configuration)
 {
     $contentType = $request->getContentType();
     if (empty($contentType) || !isset($this->decoders[$contentType])) {
         return;
     }
     $content = $request->getContent();
     $decoded = $this->decoders[$contentType]->decode($content);
     $body = new Body($decoded);
     $request->attributes->set($configuration->getName(), $body);
 }
 /**
  * Method to filter the request
  *
  * @param Request $request            
  * @param Form $form            
  */
 public function filterInput(Request $request, Form $form)
 {
     $requestParams = array();
     if ($request->getContentType() == 'json') {
         $requestParams = json_decode($request->getContent(), true);
     } else {
         $requestParams = $request->request->all();
     }
     $filteredInput = $this->sanitizeInput($requestParams, $form);
     $request->request->set($form->getName(), $filteredInput);
 }
Example #13
0
 protected function prepareRequest(Request $request)
 {
     $session = $this->container->get(Session::class);
     $request->setSession($session);
     if ($request->getContentType() == 'json') {
         if ($data = json_decode($request->getContent(), true)) {
             $request->request->replace($data);
         }
     }
     $this->container->add(Request::class, $request);
 }
 /**
  * Get the notification payload data.
  *
  * @param Request $request The request.
  * @param string $payloadDataClass The deserialization class.
  * @return NotificationPayloadInterface
  */
 protected function getPayload(Request $request, $payloadDataClass)
 {
     if ('json' !== $request->getContentType()) {
         throw new UnsupportedMediaTypeHttpException();
     }
     try {
         return $this->get('speicher210_fastbill.serializer')->deserialize($request->getContent(), $payloadDataClass, 'json');
     } catch (\Exception $e) {
         throw new BadRequestHttpException('Invalid hook payload.', $e);
     }
 }
Example #15
0
 public function setHttpRequest(Request $request)
 {
     $this->httpRequest = $request;
     if (!$request->isMethod('POST')) {
         throw new JsonRpcParseException('Invalid method, method should be POST');
     }
     if ($request->getContentType() != 'json') {
         throw new JsonRpcParseException('Content-Type should by application/json');
     }
     $this->jsonRequestRaw = $request->getContent();
     $this->parseJsonRequest();
 }
Example #16
0
 /**
  * @param Request $request
  * @param array   $operationDefinition
  *
  * @return mixed|null
  * @throws MalformedContentException
  * @throws UnsupportedContentTypeException
  */
 public function decodeContent(Request $request, array $operationDefinition)
 {
     if ($content = $request->getContent()) {
         $type = $this->typeResolver ? $this->typeResolver->resolve($operationDefinition) : null;
         try {
             return $this->serializer->deserialize($content, $type, $request->getContentType());
         } catch (\Exception $e) {
             throw new MalformedContentException("Unable to decode payload", 400, $e);
         }
     }
     return null;
 }
 /**
  * {@inheritdoc}
  *
  * @return \Drupal\Core\Entity\EntityInterface|array
  */
 public function processRequest(Request $request, RouteMatchInterface $route_match, SerializerInterface $serializer)
 {
     // Unserialize the content of the request if there is any.
     $content = $request->getContent();
     if (!empty($content)) {
         $entity_type_id = $this->getDerivativeId();
         /** @var $entity_type \Drupal\Core\Entity\EntityTypeInterface */
         $entity_type = $this->manager->getDefinition($entity_type_id);
         return $serializer->deserialize($content, $entity_type->getClass(), $request->getContentType(), ['entity_type' => $entity_type_id]);
     }
     return [];
 }
 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;
 }
 /**
  * {@inheritdoc}
  */
 public function createToken(Request $request, $providerKey)
 {
     if (!$request->isMethod('POST')) {
         throw new MethodNotAllowedHttpException(['POST']);
     }
     if ($request->getContentType() != 'json') {
         throw new UnsupportedMediaTypeHttpException('Content-Type must be "application/json".');
     }
     $body = json_decode($request->getContent(), true);
     list($username, $password) = array_values($body + ['username' => null, 'password' => null]);
     return new UsernamePasswordToken($username, $password, $providerKey);
 }
 /**
  * @param Request $request
  *
  * @return JsonResponse
  */
 public function defaultAction(Request $request)
 {
     $service = $request->attributes->get('service');
     $method = $request->attributes->get('method');
     $arguments = $request->getContentType() === 'json' ? $request->getContent() : '{}';
     if (empty($service) or empty($method) or empty($arguments)) {
         throw new \RuntimeException('Must define a service a method and arguments.');
     }
     $service = $this->container->get($service);
     $arguments = array_merge($request->query->all(), $request->request->all(), json_decode($arguments, true));
     $result = call_user_func_array([$service, $method], $arguments);
     return new JsonResponse($result);
 }
 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);
 }
Example #22
0
 public function createAction($content, Request $request)
 {
     $this->forward400Unless('json' == $request->getContentType());
     $form = $this->formFactory->create('payum_gateway_config', null, ['data_class' => GatewayConfig::class, 'csrf_protection' => false]);
     $form->submit($content);
     if ($form->isValid()) {
         /** @var GatewayConfigInterface $gatewayConfig */
         $gatewayConfig = $form->getData();
         $this->gatewayConfigStorage->update($gatewayConfig);
         $getUrl = $this->urlGenerator->generate('gateway_get', array('name' => htmlspecialchars($gatewayConfig->getGatewayName())), $absolute = true);
         return new JsonResponse(array('gateway' => $this->gatewayConfigToJsonConverter->convert($gatewayConfig)), 201, array('Location' => $getUrl));
     }
     return new JsonResponse($this->formToJsonConverter->convertInvalid($form), 400);
 }
Example #23
0
 /**
  * @param Request $request
  *
  * @return JsonResponse
  */
 public function createAction($content, Request $request)
 {
     $this->forward400Unless('json' == $request->getContentType() || 'form' == $request->getContentType());
     $rawToken = ArrayObject::ensureArrayObject($content);
     $form = $this->formFactory->create(CreateTokenType::class);
     $form->submit((array) $rawToken);
     if (false == $form->isValid()) {
         return new JsonResponse($this->formToJsonConverter->convertInvalid($form), 400);
     }
     $data = $form->getData();
     /** @var Payment $payment */
     $this->forward400Unless($payment = $this->payum->getStorage(Payment::class)->find($data['paymentId']));
     if ($data['type'] == 'capture') {
         $token = $this->payum->getTokenFactory()->createCaptureToken('', $payment, $data['afterUrl'], ['payum_token' => null, 'paymentId' => $payment->getId()]);
     } else {
         if ($data['type'] == 'authorize') {
             $token = $this->payum->getTokenFactory()->createAuthorizeToken('', $payment, $data['afterUrl'], ['payum_token' => null, 'paymentId' => $payment->getId()]);
         } else {
             $this->forward400(sprintf('The token type %s is not supported', $data['type']));
         }
     }
     return new JsonResponse(['token' => $this->tokenToJsonConverter->convert($token)], 201);
 }
 /**
  * @param string  $endpoint
  * @param Request $request
  * @return Response
  */
 public function routerAction($endpoint, Request $request)
 {
     $request->setRequestFormat($request->getContentType());
     if ($request->getMethod() !== Request::METHOD_POST) {
         throw new MethodNotAllowedHttpException(array(Request::METHOD_POST));
     }
     try {
         $endpoint = $this->endpointManager->getEndpoint($endpoint);
     } catch (\InvalidArgumentException $e) {
         throw new NotFoundHttpException('Not Found', $e);
     }
     try {
         return $endpoint->handleRequest($request);
     } catch (BadRequestException $e) {
         throw new BadRequestHttpException('Bad Request', $e);
     }
 }
Example #25
0
 public function extractDataFromRequest(Request $request)
 {
     if (in_array($request->getContentType(), ['json', 'application/json']) === true) {
         $input = (array) json_decode($request->getContent(), true);
     } else {
         $input = $request->request->all();
     }
     // set empty strings to null
     return array_map(function ($x) {
         if (is_string($x) === true) {
             $x = preg_replace('/(^\\s+)|(\\s+$)/us', '', $x);
             if (mb_strlen($x) === 0) {
                 return null;
             }
         }
         return $x;
     }, $input);
 }
Example #26
0
 /**
  * @param Request $request
  * @return XmlRpcRequest
  * @throws RpcException
  */
 public function createRequest(Request $request)
 {
     if (!$request->isMethod('POST')) {
         throw new InvalidRequestException(self::MESSAGE_INVALID_HTTP_METHOD);
     }
     if ($request->getContentType() != 'xml') {
         throw new InvalidRequestException(self::MESSAGE_INVALID_CONTENT_TYPE);
     }
     $params = xmlrpc_decode_request($request->getContent(), $method, 'UTF-8');
     if (is_null($method)) {
         throw new RequestParseException(self::MESSAGE_INVALID_BODY);
     }
     if (empty($method)) {
         throw new InvalidRequestException(self::MESSAGE_METHOD_REQUIRED);
     }
     if (!is_array($params)) {
         throw new InvalidRequestException(self::MESSAGE_METHOD_PARAMS_TYPE);
     }
     return new XmlRpcRequest($request, $method, $params);
 }
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;
 }
 public function update(Request $request, $id)
 {
     $class = $this->getEntityClassFromType($this->apiRecordType);
     $entity = $this->getEntityManager()->find($class, $id);
     if (!$entity) {
         return new Response('', Response::HTTP_NOT_FOUND);
     }
     $data = $request->getContent();
     if ($request->getContentType() === 'application/json') {
         $data = json_decode($data, true);
     }
     $entity = $this->getEntityPopulator()->updateFromArray($entity, $data);
     $this->getEntityManager()->flush();
     return new JsonResponse($this->getApiWriter()->writeObject($entity), Response::HTTP_OK);
 }
Example #29
0
 /**
  * Finds and displays a User entity.
  *
  * @Route("/{id}", name="user_show")
  * @Method("GET")
  * @Template()
  */
 public function showAction($id, Request $request)
 {
     $em = $this->getDoctrine()->getManager();
     $entity = $em->getRepository('AppBundle:User')->find($id);
     if (!$entity) {
         throw $this->createNotFoundException('Unable to find User entity.');
     }
     if ($request->getContentType() == "json") {
         return new JsonResponse($entity);
     }
     $deleteForm = $this->createDeleteForm($id);
     return array('entity' => $entity, 'delete_form' => $deleteForm->createView());
 }
 protected function isJsonRequest(Request $request)
 {
     return $request->getContentType() === 'json';
 }