本文整理汇总了PHP中Psr\Http\Message\RequestInterface类的典型用法代码示例。如果您正苦于以下问题:PHP RequestInterface类的具体用法?PHP RequestInterface怎么用?PHP RequestInterface使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了RequestInterface类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: 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);
}
示例2: 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;
}
示例3: to
/**
* Forward the request to the target url and return the response.
*
* @param string $target
* @throws UnexpectedValueException
* @return Response
*/
public function to($target)
{
if (is_null($this->request)) {
throw new UnexpectedValueException('Missing request instance.');
}
$target = new Uri($target);
// Overwrite target scheme and host.
$uri = $this->request->getUri()->withScheme($target->getScheme())->withHost($target->getHost());
// Check for custom port.
if ($port = $target->getPort()) {
$uri = $uri->withPort($port);
}
// Check for subdirectory.
if ($path = $target->getPath()) {
$uri = $uri->withPath(rtrim($path, '/') . '/' . ltrim($uri->getPath(), '/'));
}
$request = $this->request->withUri($uri);
$stack = $this->filters;
$stack[] = function (RequestInterface $request, ResponseInterface $response, callable $next) {
$response = $this->adapter->send($request);
return $next($request, $response);
};
$relay = (new RelayBuilder())->newInstance($stack);
return $relay($request, new Response());
}
示例4: run
/**
* @param RequestInterface $request A PSR-7 compatible Request instance.
* @param ResponseInterface $response A PSR-7 compatible Response instance.
* @return ResponseInterface
*/
public function run(RequestInterface $request, ResponseInterface $response)
{
try {
$objType = $request->getParam('obj_type');
$objId = $request->getParam('obj_id');
if (!$objType) {
$this->setSuccess(false);
return $response->withStatus(404);
}
if (!$objId) {
$this->setSuccess(false);
return $response->withStatus(404);
}
$this->logger->debug(sprintf('Admin Deleting object "%s" ID %s', $objType, $objId));
$obj = $this->modelFactory()->create($objType);
$obj->load($objId);
if (!$obj->id()) {
$this->setSuccess(false);
return $response->withStatus(404);
}
$res = $obj->delete();
if ($res) {
$this->setSuccess(true);
return $response;
}
} catch (Exception $e) {
$this->setSuccess(false);
return $response->withStatus(500);
}
}
示例5: 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);
}
}
示例6: 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()];
}
}
示例7: request
/**
* Send a request to the server and return a Response object with the response.
*
* @param RequestInterface $request The request object to send.
*
* @return ResponseInterface
*
* @since 2.1
*/
public function request(RequestInterface $request)
{
$uri = $request->getUri()->withPath(null)->withQuery(null)->withFragment(null);
$uri = $uri . $request->getRequestTarget();
$request = $request->withRequestTarget($uri);
return $this->doRequest($request);
}
示例8: run
/**
* @param ServerRequestInterface $request PSR7 Request.
* @param ResponseInterface $response PSR7 Response.
* @return ResponseInterface
*/
public function run(RequestInterface $request, ResponseInterface $response)
{
$widgetType = $request->getParam('widget_type');
$widgetOptions = $request->getParam('widget_options');
if (!$widgetType) {
$this->setSuccess(false);
return $response->withStatus(400);
}
try {
$widget = $this->widgetFactory->create($widgetType);
$widget->setView($this->widgetView);
if (is_array($widgetOptions)) {
$widget->setData($widgetOptions);
}
$widgetHtml = $widget->renderTemplate($widgetType);
$widgetId = $widget->widgetId();
$this->setWidgetHtml($widgetHtml);
$this->setWidgetId($widgetId);
$this->setSuccess(true);
return $response;
} catch (Exception $e) {
$this->addFeedback('error', sprintf('An error occured reloading the widget: "%s"', $e->getMessage()));
$this->addFeedback('error', $e->getMessage());
$this->setSuccess(false);
return $response->withStatus(500);
}
}
示例9: getAttribute
/**
* @param RequestInterface $request
* @param string $name
* @return string
*/
public function getAttribute(RequestInterface $request, $name)
{
if (!$request instanceof ServerRequestInterface) {
throw new \InvalidArgumentException('Request is not of type ' . ServerRequestInterface::class);
}
return $request->getAttribute($name);
}
示例10: run
/**
* Note that the lost-password action should never change status code and always return 200.
*
* @param RequestInterface $request A PSR-7 compatible Request instance.
* @param ResponseInterface $response A PSR-7 compatible Response instance.
* @return ResponseInterface
* @todo This should be done via an Authenticator object.
*/
public function run(RequestInterface $request, ResponseInterface $response)
{
$username = $request->getParam('username');
if (!$username) {
$this->addFeedback('error', 'Missing username.');
$this->setSuccess(false);
return $response->withStatus(404);
}
$recaptchaValue = $request->getParam('g-recaptcha-response');
if (!$recaptchaValue) {
$this->addFeedback('error', 'Missing captcha.');
$this->setSuccess(false);
return $response->withStatus(404);
}
if (!$this->validateCaptcha($recaptchaValue)) {
$this->addFeedback('error', 'Invalid captcha.');
$this->setSuccess(false);
return $response->withStatus(404);
}
$user = $this->loadUser($username);
if (!$user) {
// Fail silently.
$this->logger->error('Lost password request: can not find user in database.');
return $response;
}
$token = $this->generateLostPasswordToken($user);
$this->sendLostPasswordEmail($user, $token);
return $response;
}
示例11: sign
/**
* @param \Psr\Http\Message\RequestInterface $request
*
* @return \Psr\Http\Message\RequestInterface
*/
public function sign(RequestInterface $request)
{
$timestamp = (new \DateTime('now', new \DateTimeZone('UTC')))->getTimestamp();
$data = implode('|', [$request->getMethod(), rtrim((string) $request->getUri(), '/'), $timestamp]);
$signature = $this->signer->sign($data);
return $request->withHeader(self::TIMESTAMP_HEADER, $timestamp)->withHeader(self::SIGNATURE_HEADER, $signature);
}
示例12: __invoke
/**
* Execute the middleware.
*
* @param RequestInterface $request
* @param ResponseInterface $response
* @param callable $next
*
* @return ResponseInterface
*/
public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next)
{
$uri = $request->getUri();
$path = $uri->getPath();
//Test basePath
if (!$this->testBasePath($path)) {
return $next($request, $response);
}
//Add/remove slash
if ($this->addSlash) {
if (strlen($path) > 1 && substr($path, -1) !== '/' && !pathinfo($path, PATHINFO_EXTENSION)) {
$path .= '/';
}
} else {
if (strlen($path) > 1 && substr($path, -1) === '/') {
$path = substr($path, 0, -1);
}
}
//Ensure the path has one "/"
if (empty($path) || $path === $this->basePath) {
$path .= '/';
}
//redirect
if (is_int($this->redirectStatus) && $uri->getPath() !== $path) {
return self::getRedirectResponse($this->redirectStatus, $uri->withPath($path), $response);
}
return $next($request->withUri($uri->withPath($path)), $response);
}
示例13: checkForOAuthPaths
/**
* Check the current url for oauth paths
*
* @param RequestInterface $request PSR7 request object
* @param ResponseInterface $response PSR7 response object
*
* @return ResponseInterface|false PSR7 response object
*/
private function checkForOAuthPaths(RequestInterface $request, ResponseInterface $response)
{
$path = $request->getUri()->getPath();
if (!is_string($path)) {
return false;
}
// this matches the request to authenticate for an oauth provider
if (1 === preg_match($this->getAuthRouteRegex(), $path, $matches)) {
// validate we have an allowed oAuthServiceType
if (!in_array($matches['oAuthServiceType'], $this->oAuthProviders)) {
throw new Exception("Unknown oAuthServiceType");
}
// validate the return url
parse_str($_SERVER['QUERY_STRING'], $query);
if (!array_key_exists('return', $query) || filter_var($query['return'], FILTER_VALIDATE_URL) === false) {
throw new Exception("Invalid return url");
}
$_SESSION['oauth_return_url'] = $query['return'];
$url = $this->oAuthFactory->getOrCreateByType($matches['oAuthServiceType'])->getAuthorizationUri();
return $response->withStatus(302)->withHeader('Location', $url);
} elseif (1 === preg_match($this->getCallbackRouteRegex(), $path, $matches)) {
// this matches the request to post-authentication for an oauth provider
if (!in_array($matches['oAuthServiceType'], $this->oAuthProviders)) {
throw new Exception("Unknown oAuthServiceType");
}
$service = $this->oAuthFactory->getOrCreateByType($matches['oAuthServiceType']);
// turn our code into a token that's stored internally
$service->requestAccessToken($request->getParam('code'));
// validates and creates the user entry in the db if not already exists
$user = $this->userService->createUser($service);
// set our token in the header and then redirect to the client's chosen url
return $response->withStatus(200)->withHeader('Authorization', 'token ' . $user->token)->withHeader('Location', $_SESSION['oauth_return_url']);
}
return false;
}
示例14: __invoke
/**
* Execute the middleware.
*
* @param RequestInterface $request
* @param ResponseInterface $response
* @param callable $next
*
* @return ResponseInterface
*/
public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next)
{
$uri = $request->getUri();
$path = $this->getBasePath($uri->getPath());
$request = $request->withUri($uri->withPath($path));
return $next($request, $response);
}
示例15: 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());
}