本文整理汇总了PHP中Psr\Http\Message\RequestInterface::getMethod方法的典型用法代码示例。如果您正苦于以下问题:PHP RequestInterface::getMethod方法的具体用法?PHP RequestInterface::getMethod怎么用?PHP RequestInterface::getMethod使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Psr\Http\Message\RequestInterface
的用法示例。
在下文中一共展示了RequestInterface::getMethod方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: 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));
}
}
示例2: 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);
}
示例3: describe
/**
* @param \Psr\Http\Message\RequestInterface $request
* @param \Psr\Http\Message\ResponseInterface $response
*
* @return string
*/
protected function describe(RequestInterface $request, ResponseInterface $response = null)
{
if (!$response) {
return sprintf('%s %s failed', $request->getMethod(), $request->getUri());
}
return sprintf('%s %s returned %s %s', $request->getMethod(), $request->getUri(), $response->getStatusCode(), $response->getReasonPhrase());
}
示例4: getPath
/**
* Create a fingerprint for each request.
*
* As it is for mocking (and not for real caching), ignore some
* characteristics like the 'User-Agent' to avoid stale cache
* when updating PHP or Guzzle.
*
* @param RequestInterface $request
*
* @return string The path to the mock file
*/
public function getPath(RequestInterface $request)
{
$headers = $request->getHeaders();
foreach ($headers as $name => $values) {
if (in_array($name, $this->headersBlacklist)) {
unset($headers[$name]);
}
}
$fingerprint = md5(serialize(['method' => $request->getMethod(), 'path' => $request->getUri()->getPath(), 'query' => $request->getUri()->getQuery(), 'user_info' => $request->getUri()->getUserInfo(), 'port' => $request->getUri()->getPort(), 'scheme' => $request->getUri()->getScheme(), 'headers' => $headers]));
$path = sprintf('%s_%s____%s', str_pad($request->getMethod(), 6, '_'), urldecode(ltrim($request->getUri()->getPath(), '/') . '-' . $request->getUri()->getQuery()), $fingerprint);
return $this->storagePath . '/' . preg_replace('/[^a-zA-Z0-9_+=@\\-\\?\\.]/', '-', $path) . '.txt';
}
示例5: convertPostToGet
/**
* Converts a POST request to a GET request by moving POST fields into the
* query string.
*
* Useful for pre-signing query protocol requests.
*
* @param RequestInterface $request Request to clone
*
* @return RequestInterface
* @throws \InvalidArgumentException if the method is not POST
*/
public static function convertPostToGet(RequestInterface $request)
{
if ($request->getMethod() !== 'POST') {
throw new \InvalidArgumentException('Expected a POST request but ' . 'received a ' . $request->getMethod() . ' request.');
}
$sr = $request->withMethod('GET')->withBody(Psr7\stream_for(''))->withoutHeader('Content-Type')->withoutHeader('Content-Length');
// Move POST fields to the query if they are present
if ($request->getHeaderLine('Content-Type') === 'application/x-www-form-urlencoded') {
$body = (string) $request->getBody();
$sr = $sr->withUri($sr->getUri()->withQuery($body));
}
return $sr;
}
示例6: 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()));
}
示例7: create
/**
* Factory method to create a new exception with a normalized error message
*
* @param RequestInterface $request Request
* @param ResponseInterface $response Response received
* @param \Exception $previous Previous exception
* @param array $ctx Optional handler context.
*
* @return self
*/
public static function create(RequestInterface $request, ResponseInterface $response = null, \Exception $previous = null, array $ctx = [])
{
if (!$response) {
return new self('Error completing request', $request, null, $previous, $ctx);
}
$level = (int) floor($response->getStatusCode() / 100);
if ($level === 4) {
$label = 'Client error';
$className = __NAMESPACE__ . '\\ClientException';
} elseif ($level === 5) {
$label = 'Server error';
$className = __NAMESPACE__ . '\\ServerException';
} else {
$label = 'Unsuccessful request';
$className = __CLASS__;
}
$uri = $request->getUri();
$uri = static::obfuscateUri($uri);
// Server Error: `GET /` resulted in a `404 Not Found` response:
// <html> ... (truncated)
$message = sprintf('%s: `%s` resulted in a `%s` response', $label, $request->getMethod() . ' ' . $uri, $response->getStatusCode() . ' ' . $response->getReasonPhrase());
$summary = static::getResponseBodySummary($response);
if ($summary !== null) {
$message .= ":\n{$summary}\n";
}
return new $className($message, $request, $response, $previous, $ctx);
}
示例8: __invoke
/**
* @param RequestInterface $request
*
* @return RequestInterface
*/
public function __invoke(RequestInterface $request)
{
$uri = $request->getUri();
$path = $uri->getPath();
$path .= $uri->getQuery() != null ? '?' . $uri->getQuery() : '';
$payload = ['key' => 'master', 'exp' => time() + $this->exp, 'method' => $request->getMethod(), 'path' => $path];
if (in_array($request->getMethod(), ['PUT', 'POST'])) {
$body = $request->getBody();
$computedHash = \GuzzleHttp\Psr7\hash($body, 'sha256');
$payload['body'] = ['alg' => 'sha256', 'hash' => $computedHash];
}
$jws = new JWS(['typ' => 'JWT', 'alg' => 'HS256']);
$jws->setPayload($payload)->sign($this->secret);
$token = $jws->getTokenString();
return $request->withHeader('Authorization', 'JWT token="' . $token . '"');
}
示例9: 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()];
}
}
示例10: __invoke
/**
* Dispatching.
*
* @param RequestInterface $request Representation of an outgoing,
* client-side request.
*
* @throws RouteNotFoundException If the route is not found.
* @throws MethodNotAllowedException If the method is not allowed.
* @throws Exception If no one case is matched.
*
* @return RouteInfo
*/
public function __invoke(RequestInterface $request)
{
$router = $this->router;
$uri = $request->getUri();
$dispatch = $router->dispatch($request->getMethod(), $uri->getPath());
switch ($dispatch[0]) {
case BaseDispatcher::NOT_FOUND:
throw new RouteNotFoundException('Route with path ' . $uri->getPath() . ' not found.');
case BaseDispatcher::METHOD_NOT_ALLOWED:
throw new MethodNotAllowedException('Method ' . $request->getMethod() . ' not allowed.');
case BaseDispatcher::FOUND:
return $this->processRouteInfo($dispatch);
default:
throw new Exception(null, 500);
}
}
示例11: 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;
}
示例12: __invoke
/**
* @param RequestInterface $request
* @param array $options
*
* @return PromiseInterface
*/
public function __invoke(RequestInterface $request, array $options)
{
$fn = $this->nextHandler;
// Don't do anything if the request has no body.
if (isset(self::$skipMethods[$request->getMethod()]) || $request->getBody()->getSize() === 0) {
return $fn($request, $options);
}
$modify = [];
// Add a default content-type if possible.
if (!$request->hasHeader('Content-Type')) {
if ($uri = $request->getBody()->getMetadata('uri')) {
if ($type = Psr7\mimetype_from_filename($uri)) {
$modify['set_headers']['Content-Type'] = $type;
}
}
}
// Add a default content-length or transfer-encoding header.
if (!isset(self::$skipMethods[$request->getMethod()]) && !$request->hasHeader('Content-Length') && !$request->hasHeader('Transfer-Encoding')) {
$size = $request->getBody()->getSize();
if ($size !== null) {
$modify['set_headers']['Content-Length'] = $size;
} else {
$modify['set_headers']['Transfer-Encoding'] = 'chunked';
}
}
// Add the expect header if needed.
$this->addExpectHeader($request, $options, $modify);
return $fn(Psr7\modify_request($request, $modify), $options);
}
示例13: __invoke
/**
* Invoke this state. States are invoked until they return something
* non-invokable.
*
* @param array $arguments All matched URL parameters.
* @param Psr\Http\Message\RequestInterface $request The current request.
* @return mixed Whatever the state eventually resolves to.
*/
public function __invoke(array $arguments, RequestInterface $request)
{
$method = $request->getMethod();
if (!isset($this->actions[$method])) {
return new EmptyResponse(405);
}
$call = $this->actions[$method];
$this->request = $request;
do {
$args = $this->parseArguments($call, $arguments);
foreach ($args as &$value) {
if (is_string($value) && $this->isHttpAction(substr($value, 1))) {
$key = substr($value, 1);
if ($key == $method) {
throw new EndlessStateLoopException();
}
if (isset($this->actions[$key])) {
$value = $this->actions[$key];
} else {
$value = new EmptyResponse(405);
}
}
}
$call = call_user_func_array($call, $args);
} while (is_callable($call));
return $call;
}
示例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: send
/**
* {@inheritdoc}
*/
public function send(RequestInterface $request, array $options = array())
{
$options += Client::$defaultOptions;
$curlOptions = $options['curl'] + array(CURLOPT_URL => (string) $request->getUri(), CURLOPT_CUSTOMREQUEST => $request->getMethod(), CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => true, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_HTTPHEADER => \EasyRequest\get_headers($request), CURLOPT_ENCODING => $request->getHeaderLine('Accept-Encoding'), CURLOPT_NOBODY => $options['nobody'], CURLOPT_CONNECTTIMEOUT => $options['timeout'], CURLOPT_HTTP_VERSION => $request->getProtocolVersion() == '1.0' ? CURL_HTTP_VERSION_1_0 : CURL_HTTP_VERSION_1_1);
if ($options['upload']) {
$body = $request->getBody();
$curlOptions += array(CURLOPT_UPLOAD => true, CURLOPT_READFUNCTION => function ($ch, $fp, $length) use($body) {
return $body->read($length);
});
} elseif ($options['body']) {
$curlOptions[CURLOPT_POSTFIELDS] = (string) $request->getBody();
}
if ($options['proxy']) {
$curlOptions += array(CURLOPT_PROXY => $options['proxy'], CURLOPT_PROXYTYPE => $options['proxy_type']);
if ($options['proxy_userpwd']) {
$curlOptions[CURLOPT_PROXYUSERPWD] = $options['proxy_userpwd'];
}
}
if ($options['bindto']) {
$curlOptions[CURLOPT_INTERFACE] = $options['bindto'];
}
$header = $body = '';
$curlOptions[CURLOPT_HEADERFUNCTION] = $this->handleResponseHeader($header);
$ch = curl_init();
curl_setopt_array($ch, $curlOptions);
$result = curl_exec($ch);
curl_close($ch);
if ($result === false) {
throw new Exception(sprintf('%d - %s', curl_errno($ch), curl_error($ch)));
}
$body = substr($result, strlen($header));
return Response::parse($header, $body);
}