本文整理汇总了PHP中Psr\Http\Message\RequestInterface::getBody方法的典型用法代码示例。如果您正苦于以下问题:PHP RequestInterface::getBody方法的具体用法?PHP RequestInterface::getBody怎么用?PHP RequestInterface::getBody使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Psr\Http\Message\RequestInterface
的用法示例。
在下文中一共展示了RequestInterface::getBody方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: logRequest
/**
* @param RequestInterface $request
* @param string $type
*/
protected function logRequest(RequestInterface $request, $type = 'http')
{
$args = [ucfirst($type), $request->getMethod(), $request->getUri()];
/** @noinspection PrintfScanfArgumentsInspection */
$this->log(sprintf(' ==> (%s) %s %s', ...$args));
$headers = $this->removeTokenFromLogs($request->getHeaders());
$this->log(' Request headers: ' . json_encode($headers), Logger::DEBUG);
$size = strlen($request->getBody());
if ($size > 0) {
$this->log(sprintf(' Request body (%sb): %s', $size, $request->getBody()), Logger::DEBUG);
}
}
示例2: initPost
/**
* Initialise les valeurs des champs POST
* @return void
*/
private function initPost()
{
$this->post = array();
if (!$this->request->getBody()->getSize()) {
return;
}
if (trim($this->request->getBody()->read($this->request->getBody()->getSize()))) {
foreach (explode('&', $this->request->getBody()) as $couple) {
$vals = explode('=', $couple);
$this->post[$vals[0]] = rawurldecode($vals[1]);
}
}
}
示例3: send
public function send(RequestInterface $request)
{
switch ($request->getUri()->getPath()) {
case '/documents/1':
if ('GET' === $request->getMethod()) {
return new Response(200, ['Content-Type' => 'application/hal+json'], file_get_contents(__DIR__ . '/fixtures/documents_1.json'));
}
break;
case '/documents/2':
if ('GET' === $request->getMethod()) {
return new Response(200, ['Content-Type' => 'application/hal+json'], file_get_contents(__DIR__ . '/fixtures/documents_2.json'));
}
break;
case '/documents/3':
if ('GET' === $request->getMethod()) {
return new Response(200, ['Content-Type' => 'application/hal+json'], file_get_contents(__DIR__ . '/fixtures/documents_3.json'));
}
break;
case '/documents/4':
if ('DELETE' === $request->getMethod()) {
return new Response(204, ['Content-Type' => 'text/html']);
}
if ('PUT' === $request->getMethod()) {
if ('{"title":"Test 4 changed","body":"Lorem ipsum"}' === $request->getBody()->getContents()) {
return new Response(200, ['Content-Type' => 'application/hal+json'], file_get_contents(__DIR__ . '/fixtures/documents_4_changed.json'));
}
}
if ('GET' === $request->getMethod()) {
return new Response(200, ['Content-Type' => 'application/hal+json'], file_get_contents(__DIR__ . '/fixtures/documents_4.json'));
}
break;
case '/documents':
if ('POST' === $request->getMethod()) {
if ('{"title":"Test 4","body":"Lorem ipsum"}' === $request->getBody()->getContents()) {
return new Response(201, ['Location' => '/documents/4']);
}
}
if ('GET' === $request->getMethod()) {
return new Response(200, ['Content-Type' => 'application/hal+json'], file_get_contents(__DIR__ . '/fixtures/documents.json'));
}
break;
case '':
if ('GET' === $request->getMethod()) {
return new Response(200, ['Content-Type' => 'application/hal+json'], file_get_contents(__DIR__ . '/fixtures/root.json'));
}
break;
default:
return new Response(404);
}
return new Response(405, ['Content-Type' => 'text/plain'], sprintf('No route found for "%s %s": Method Not Allowed', $request->getUri()->getPath(), $request->getMethod()));
}
示例4: enter
/**
* Starts the profiling.
* @param RequestInterface $request
*/
public function enter(RequestInterface $request = null)
{
$this->starts = ['wt' => microtime(true), 'mu' => memory_get_usage(), 'pmu' => memory_get_peak_usage()];
if ($request) {
$this->request = ['method' => $request->getMethod(), 'url' => (string) $request->getUri(), 'body' => (string) $request->getBody()];
}
}
示例5: fetchResumeUri
private function fetchResumeUri()
{
$result = null;
$body = $this->request->getBody();
if ($body) {
$headers = array('content-type' => 'application/json; charset=UTF-8', 'content-length' => $body->getSize(), 'x-upload-content-type' => $this->mimeType, 'x-upload-content-length' => $this->size, 'expect' => '');
foreach ($headers as $key => $value) {
$this->request = $this->request->withHeader($key, $value);
}
}
$response = $this->client->execute($this->request, false);
$location = $response->getHeaderLine('location');
$code = $response->getStatusCode();
if (200 == $code && true == $location) {
return $location;
}
$message = $code;
$body = json_decode((string) $this->request->getBody(), true);
if (isset($body['error']['errors'])) {
$message .= ': ';
foreach ($body['error']['errors'] as $error) {
$message .= "{$error[domain]}, {$error[message]};";
}
$message = rtrim($message, ';');
}
$error = "Failed to start the resumable upload (HTTP {$message})";
$this->client->getLogger()->error($error);
throw new GoogleException($error);
}
示例6: renderRequest
/**
* Render a PSR-7 request.
*
* @param RequestInterface $request
* @return string
*/
public function renderRequest(RequestInterface $request)
{
$return = '';
$return .= sprintf("URL: %s\n", $request->getUri());
$return .= sprintf("METHOD: %s\n", $request->getMethod());
if ($request->getHeaders()) {
$return .= 'HEADERS:';
}
$indent = false;
foreach ($request->getHeaders() as $name => $values) {
if ($indent) {
$return .= str_repeat(' ', 8);
}
$return .= sprintf(" %s: %s\n", $name, implode(', ', $values));
$indent = true;
}
if ($body = (string) $request->getBody()) {
$return .= 'BODY: ';
switch ($request->getHeaderLine('Content-Type')) {
case 'application/json':
$return .= json_encode(json_decode($body, true), JSON_PRETTY_PRINT);
break;
default:
$return .= $body;
break;
}
$return .= "\n";
}
return $return;
}
示例7: signRequest
public function signRequest(RequestInterface $request, CredentialsInterface $credentials)
{
$params = Psr7\parse_query($request->getBody()->__toString());
$params['SignatureVersion'] = '2';
$params['SignatureMethod'] = 'HmacSHA256';
$params['AWSAccessKeyId'] = $credentials->getAccessKeyId();
if ($credentials->getSecurityToken()) {
$params['MWSAuthToken'] = $credentials->getSecurityToken();
}
$params['Timestamp'] = gmdate(self::ISO8601_BASIC);
ksort($params);
$canonicalizedQueryString = $this->getCanonicalizedQuery($params);
$stringToSign = implode("\n", [$request->getMethod(), $request->getUri()->getHost(), $request->getUri()->getPath(), $canonicalizedQueryString]);
// calculate HMAC with SHA256 and base64-encoding
$signature = base64_encode(hash_hmac('sha256', $stringToSign, $credentials->getSecretKey(), TRUE));
// encode the signature for the request
$signature = str_replace('%7E', '~', rawurlencode($signature));
$signature = str_replace('+', '%20', $signature);
$signature = str_replace('*', '%2A', $signature);
$queryString = $canonicalizedQueryString . "&Signature=" . $signature;
if ($request->getMethod() === 'POST') {
return new Request('POST', $request->getUri(), ['Content-Length' => strlen($queryString), 'Content-Type' => 'application/x-www-form-urlencoded'], $queryString);
} else {
return new Request('GET', $request->getUri()->withQuery($queryString));
}
}
示例8: convertRequestToMessage
/**
* @param RequestInterface $request
* @return Message
*/
public function convertRequestToMessage(RequestInterface $request)
{
parse_str($request->getBody(), $body);
$message = new Message($body['Message-Id']);
$message->setSubject($body['Subject']);
if (!empty($body['Reply-To'])) {
$message->setReplyTo($body['Reply-To']);
} elseif (!empty($body['Reply-to'])) {
$message->setReplyTo($body['Reply-to']);
} elseif (!empty($body['reply-to'])) {
$message->setReplyTo($body['reply-to']);
}
if (!empty($body['From'])) {
$message->setFrom($body['From']);
} else {
$message->setFrom($body['from']);
}
if (isset($body['To'])) {
$message->setTo($body['To']);
}
if (!empty($body['body-html'])) {
$message->setBodyHtml($body['body-html']);
}
if (!empty($body['stripped-html'])) {
$body['stripped-html'] = html_entity_decode($body['stripped-html']);
if (strpos($body['stripped-html'], 'ĂĄ') !== false && stripos($body['stripped-html'], 'charset=iso-8859-2')) {
$body['stripped-html'] = iconv('UTF-8', 'ISO-8859-2//TRANSLIT', $body['stripped-html']);
} elseif (strpos($body['stripped-html'], 'á') !== false && stripos($body['stripped-html'], 'charset=windows-1250')) {
$body['stripped-html'] = iconv('UTF-8', 'CP1250//TRANSLIT', $body['stripped-html']);
}
$message->setStrippedHtml($body['stripped-html']);
}
if (!empty($body['body-plain'])) {
if (isset($body['stripped-html'])) {
if (strpos($body['body-plain'], 'ĂĄ') !== false && stripos($body['stripped-html'], 'charset=iso-8859-2')) {
$body['body-plain'] = iconv('UTF-8', 'ISO-8859-2//TRANSLIT', $body['body-plain']);
} elseif (strpos($body['body-plain'], 'á') !== false && stripos($body['stripped-html'], 'charset=windows-1250')) {
$body['body-plain'] = iconv('UTF-8', 'CP1250//TRANSLIT', $body['body-plain']);
}
}
$message->setBodyPlain($body['body-plain']);
}
if (!empty($body['References'])) {
$message->setReferences($body['References']);
}
$message->setDate((new \DateTime())->setTimestamp($body['timestamp']));
$message->setSpam(isset($body['X-Mailgun-Sflag']) && $body['X-Mailgun-Sflag'] === 'yes');
$message->setSpamScore(isset($body['X-Mailgun-Sscore']) ? (double) $body['X-Mailgun-Sscore'] : 0);
if (isset($body['attachments'])) {
foreach (json_decode($body['attachments']) as $at) {
if ($at->name == 'smime.p7s') {
continue;
}
$attachment = new Attachment();
$attachment->setName($at->name)->setUrl(str_replace('https://', 'https://api:key-' . $this->key . '@', $at->url));
$message->addAttachment($attachment);
}
}
return $message;
}
示例9: send
/**
* @param RequestInterface $request
* @return ResponseInterface
*/
public function send($request)
{
/**
* var \GuzzleHttp\Message\Response $response
*/
$headers = $request->getHeaders();
if (!empty($this->append_headers)) {
$headers = array_merge($headers, $this->append_headers);
}
$opt = [];
if (!empty($this->basicAuth)) {
$opt['auth'] = $this->basicAuth;
}
if (!empty($headers)) {
$opt['headers'] = $headers;
}
$body = $request->getBody();
if ($body !== null) {
$opt['body'] = $body;
}
$g4request = $this->getClient()->createRequest($request->getMethod(), $request->getUri(), $opt);
try {
$response = $this->getClient()->send($g4request);
return new Response($response->getStatusCode(), $response->getHeaders(), $response->getBody());
} catch (\GuzzleHttp\Exception\RequestException $ex) {
$ex_request = $ex->getRequest();
$ex_response = $ex->getResponse();
throw new RequestException($ex->getMessage(), $ex_request ? new Request($ex_request->getMethod(), $ex_request->getUrl(), $ex_request->getHeaders(), $ex_request->getBody()) : null, $ex_response ? new Response($ex_response->getStatusCode(), $ex_response->getHeaders(), $ex_response->getBody()) : null, $ex);
}
}
示例10: request
/**
* {@inheritdoc}
*/
public function request(RequestInterface $request)
{
$url = (string) $request->getUri();
$body = $request->getBody();
$body->seek(0);
$headers = $request->getHeaders();
$headers['Accept'] = 'application/json';
$headers['Content-Type'] = 'application/json';
$req = $this->guzzle->createRequest($request->getMethod(), $url);
$req->setHeaders($headers);
$req->setBody(GStream::factory($body->getContents()));
try {
$res = $this->guzzle->send($req);
} catch (RequestException $e) {
// Guzzle will throw exceptions for 4xx and 5xx responses, so we catch
// them here and quietly get the response object.
$res = $e->getResponse();
if (!$res) {
throw $e;
}
}
$response = (new Response(new Stream('php://memory', 'w')))->withStatus($res->getStatusCode(), $res->getReasonPhrase());
$response->getBody()->write((string) $res->getBody());
return $response;
}
示例11: assertRequest
/**
* Assert request matches against declared specification.
*
* The list of constraints:
*
* - Assert request method defined
* - Assert request URI declared by host, basePath, schemes and parameters (path, query)
* - Assert content-type declared by consumes
* - Assert headers declared by parameters (header)
* - Assert body declared by parameters (body)
*
* @param Spec $spec
* @param string $template
* @param Request $request
* @param string $msg
*/
protected static final function assertRequest(Spec $spec, $template, Request $request, $msg = '')
{
self::assertMethodAllowed($spec, $template, $request->getMethod(), $msg);
self::assertUri($spec, $template, $request->getMethod(), $request->getUri(), $msg);
self::assertRequestHeaders($spec, $template, $request->getMethod(), $request->getHeaders(), $msg);
self::assertRequestBody($spec, $template, $request->getMethod(), $request->getBody(), $msg);
}
示例12:
function it_returns_body_with_headers(RequestInterface $request, Stream $stream)
{
$request->getHeaders()->shouldBeCalled()->willReturn(['content-type' => 'application/json']);
$request->getBody()->shouldBeCalled()->willReturn($stream);
$stream->getContents()->shouldBeCalled()->willReturn('{"data": {}}');
$this->getBodyWithHeaders($request)->shouldReturn('content-type: application/json' . PHP_EOL . PHP_EOL . '{"data": {}}');
}
示例13: addExpectHeader
private function addExpectHeader(RequestInterface $request, array $options, array &$modify)
{
// Determine if the Expect header should be used
if ($request->hasHeader('Expect')) {
return;
}
$expect = isset($options['expect']) ? $options['expect'] : null;
// Return if disabled or if you're not using HTTP/1.1 or HTTP/2.0
if ($expect === false || $request->getProtocolVersion() < 1.1) {
return;
}
// The expect header is unconditionally enabled
if ($expect === true) {
$modify['set_headers']['Expect'] = '100-Continue';
return;
}
// By default, send the expect header when the payload is > 1mb
if ($expect === null) {
$expect = 1048576;
}
// Always add if the body cannot be rewound, the size cannot be
// determined, or the size is greater than the cutoff threshold
$body = $request->getBody();
$size = $body->getSize();
if ($size === null || $size >= (int) $expect || !$body->isSeekable()) {
$modify['set_headers']['Expect'] = '100-Continue';
}
}
示例14: __invoke
/**
* @param Request $request
*
* @return Response
*/
public function __invoke(Request $request)
{
$options = [];
// Headers
$headerLines = [];
foreach ($request->getHeaders() as $name => $values) {
$headerLines[] = sprintf('%s: %s', $name, implode(', ', $values));
}
$options[CURLOPT_HTTPHEADER] = $headerLines;
// Url
$options[CURLOPT_URL] = (string) $request->getUri();
switch ($request->getMethod()) {
case 'HEAD':
$options[CURLOPT_NOBODY] = true;
break;
case 'GET':
$options[CURLOPT_HTTPGET] = true;
break;
case 'POST':
$options[CURLOPT_POST] = true;
$options[CURLOPT_POSTFIELDS] = (string) $request->getBody();
// Don't duplicate the Content-Length header
$request = $request->withoutHeader('Content-Length');
$request = $request->withoutHeader('Transfer-Encoding');
break;
case 'PUT':
// Write to memory/temp
$file = fopen('php://temp/' . spl_object_hash($request), 'w+');
$bytes = fwrite($file, (string) $request->getBody());
rewind($file);
$options[CURLOPT_PUT] = true;
$options[CURLOPT_INFILE] = $file;
$options[CURLOPT_INFILESIZE] = $bytes;
$request = $request->withoutHeader('Content-Length');
break;
default:
$options[CURLOPT_CUSTOMREQUEST] = $request->getMethod();
}
// If the Expect header is not present, prevent curl from adding it
if (!$request->hasHeader('Expect')) {
$options[CURLOPT_HTTPHEADER][] = 'Expect:';
}
// cURL sometimes adds a content-type by default. Prevent this.
if (!$request->hasHeader('Content-Type')) {
$options[CURLOPT_HTTPHEADER][] = 'Content-Type:';
}
list($body, $headerLines) = $this->execute($options);
$headerLines = preg_split("#\r\n#", $headerLines, -1, PREG_SPLIT_NO_EMPTY);
$headers = [];
// Extract the version and status from the first header
preg_match('#HTTP/(\\d\\.\\d)\\s(\\d\\d\\d)\\s(.*)#', array_shift($headerLines), $matches);
array_shift($matches);
list($protocolVersion, $statusCode, $reasonPhrase) = $matches;
foreach ($headerLines as $line) {
list($name, $values) = preg_split('#\\s*:\\s*#', $line, 2, PREG_SPLIT_NO_EMPTY);
$headers[$name] = preg_split('#\\s*,\\s*#', $values, -1, PREG_SPLIT_NO_EMPTY);
}
$response = new \GuzzleHttp\Psr7\Response($statusCode, $headers, $body, $protocolVersion, $reasonPhrase);
return $response;
}
示例15: getPayload
protected function getPayload(RequestInterface $request)
{
// Calculate the request signature payload
if ($request->hasHeader('X-Amz-Content-Sha256')) {
// Handle streaming operations (e.g. Glacier.UploadArchive)
return $request->getHeaderLine('X-Amz-Content-Sha256');
}
if (!$request->getBody()->isSeekable()) {
throw new CouldNotCreateChecksumException('sha256');
}
try {
return Psr7\hash($request->getBody(), 'sha256');
} catch (\Exception $e) {
throw new CouldNotCreateChecksumException('sha256', $e);
}
}