本文整理汇总了PHP中Symfony\Component\HttpFoundation\Request::getContentType方法的典型用法代码示例。如果您正苦于以下问题:PHP Request::getContentType方法的具体用法?PHP Request::getContentType怎么用?PHP Request::getContentType使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Symfony\Component\HttpFoundation\Request
的用法示例。
在下文中一共展示了Request::getContentType方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: getPostData
/**
* @return array
*/
public function getPostData()
{
if ('json' === $this->_internalRequest->getContentType()) {
return (array) json_decode($this->_internalRequest->getContent(), true);
} else {
return $this->_internalRequest->request->all();
}
}
示例2: filter
/**
* {@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') . '"');
}
示例3: createRequest
/**
* @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']);
}
示例4: apply
/**
* {@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;
}
示例5: testGetContentType
public function testGetContentType()
{
$request = new Request();
$contentType = $request->getContentType();
$this->assertNull($contentType);
}
示例6: handle
/**
* 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;
}
示例7: prepareOptions
/**
* @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;
}
示例8: processRequest
/**
* {@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);
}
}
}
示例9: processRequest
/**
* {@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 [];
}
示例10: formError
/**
* 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;
}
示例11: apply
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);
}
示例12: filterInput
/**
* 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);
}
示例13: prepareRequest
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);
}
示例14: getPayload
/**
* 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);
}
}
示例15: setHttpRequest
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();
}