本文整理汇总了PHP中Psr\Http\Message\ServerRequestInterface类的典型用法代码示例。如果您正苦于以下问题:PHP ServerRequestInterface类的具体用法?PHP ServerRequestInterface怎么用?PHP ServerRequestInterface使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ServerRequestInterface类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: process
public function process(ServerRequestInterface $request, DelegateInterface $delegate) : ResponseInterface
{
/* @var \PSR7Session\Session\SessionInterface $session */
$session = $request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE);
// Generate csrf token
if (!$session->get('csrf')) {
$session->set('csrf', md5(random_bytes(32)));
}
// Generate form and inject csrf token
$form = new FormFactory($this->template->render('app::contact-form', ['token' => $session->get('csrf')]), $this->inputFilterFactory);
// Validate form
$validationResult = $form->validateRequest($request);
if ($validationResult->isValid()) {
// Get filter submitted values
$data = $validationResult->getValues();
$this->logger->notice('Sending contact mail to {from} <{email}> with subject "{subject}": {body}', $data);
// Create the message
$message = new Message();
$message->setFrom($this->config['from'])->setReplyTo($data['email'], $data['name'])->setTo($this->config['to'])->setSubject('[xtreamwayz-contact] ' . $data['subject'])->setBody($data['body']);
$this->mailTransport->send($message);
// Display thank you page
return new HtmlResponse($this->template->render('app::contact-thank-you'), 200);
}
// Display form and inject error messages and submitted values
return new HtmlResponse($this->template->render('app::contact', ['form' => $form->asString($validationResult)]), 200);
}
示例2: __invoke
/**
* @interitdoc
*/
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
{
$payload = null;
$messageName = 'UNKNOWN';
try {
$payload = $request->getParsedBody();
if (is_array($payload) && isset($payload['message_name'])) {
$messageName = $payload['message_name'];
}
MessageDataAssertion::assert($payload);
$message = $this->messageFactory->createMessageFromArray($payload['message_name'], $payload);
switch ($message->messageType()) {
case Message::TYPE_COMMAND:
$this->commandBus->dispatch($message);
return $response->withStatus(Middleware::STATUS_CODE_ACCEPTED);
case Message::TYPE_EVENT:
$this->eventBus->dispatch($message);
return $response->withStatus(Middleware::STATUS_CODE_ACCEPTED);
case Message::TYPE_QUERY:
return $this->responseStrategy->fromPromise($this->queryBus->dispatch($message));
default:
return $next($request, $response, new RuntimeException(sprintf('Invalid message type "%s" for message "%s".', $message->messageType(), $messageName), Middleware::STATUS_CODE_BAD_REQUEST));
}
} catch (\Assert\InvalidArgumentException $e) {
return $next($request, $response, new RuntimeException($e->getMessage(), Middleware::STATUS_CODE_BAD_REQUEST, $e));
} catch (\Exception $e) {
return $next($request, $response, new RuntimeException(sprintf('An error occurred during dispatching of message "%s"', $messageName), Middleware::STATUS_CODE_INTERNAL_SERVER_ERROR, $e));
}
}
示例3: authorize
/**
* Authenticates that the user is allowed to make call to the route.
*
* @param ServerRequestInterface ServerRequestInterface $request PSR-7 standard for receiving client request
* @param ResponseInterface ResponseInterface $response PSR-& standard for sending server response
* @param function $next callback function for calling next method
*
* @return ResponseInterface HTTP response of client request
*/
public function authorize(ServerRequestInterface $request, $response, $next)
{
if (empty($request->getHeader('Authorization'))) {
$response = $response->withStatus(400);
$response->getBody()->write(json_encode(['message' => 'Token not found']));
return $response;
}
//Get token for accessing this route
$token = $request->getHeader('Authorization')[0];
try {
//Decode token to get object of data
$decodedToken = Auth::decodeToken($token);
//Extract the user id from decoded token
$uid = $decodedToken->data->uid;
$user = User::find($uid);
//Check if user exist with the user id
if ($user != null) {
if ($user->isTokenValid($decodedToken)) {
$response = $next($request, $response);
}
} else {
$response = $response->withStatus(401);
$response->getBody()->write(json_encode(['message' => 'User does not exist']));
}
} catch (TokenExpirationException $ex) {
$response = $response->withStatus(401);
$response->getBody()->write(json_encode(['message' => $ex->getMessage()]));
} catch (\Exception $ex) {
$response = $response->withStatus(400);
$response->getBody()->write(json_encode(['message' => $ex->getMessage()]));
}
return $response;
}
示例4: canHandleRequest
/**
* {@inheritdoc}
*/
public function canHandleRequest(ServerRequestInterface $request)
{
if (static::$uriPattern === null || (string) static::$uriPattern === '') {
return false;
}
return (bool) preg_match(static::$uriPattern, $request->getUri()->getPath());
}
示例5: match
public function match(ServerRequestInterface $request)
{
//Convert URL params into regex patterns, construct a regex for this route, init params
$patternAsRegex = preg_replace_callback('#:([\\w]+)\\+?#', array($this, 'matchesCallback'), str_replace(')', ')?', (string) $this->path));
if (substr($this->path, -1) === '/') {
$patternAsRegex .= '?';
}
$regex = '#^' . $patternAsRegex . '$#';
//Cache URL params' names and values if this route matches the current HTTP request
if (!preg_match($regex, $request->getUri()->getPath(), $paramValues)) {
return false;
}
$params = [];
if ($this->paramNames) {
foreach ($this->paramNames as $name) {
if (isset($paramValues[$name])) {
if (isset($this->paramNamesPath[$name])) {
$params[$name] = explode('/', urldecode($paramValues[$name]));
} else {
$params[$name] = urldecode($paramValues[$name]);
}
}
}
}
return $params;
}
示例6: determineClientIpAddress
/**
* Find out the client's IP address from the headers available to us
*
* @param ServerRequestInterface $request PSR-7 Request
* @return string
*/
protected function determineClientIpAddress($request)
{
$ipAddress = null;
$serverParams = $request->getServerParams();
if (isset($serverParams['REMOTE_ADDR']) && $this->isValidIpAddress($serverParams['REMOTE_ADDR'])) {
$ipAddress = $serverParams['REMOTE_ADDR'];
}
$checkProxyHeaders = $this->checkProxyHeaders;
if ($checkProxyHeaders && !empty($this->trustedProxies)) {
if (!in_array($ipAddress, $this->trustedProxies)) {
$checkProxyHeaders = false;
}
}
if ($checkProxyHeaders) {
foreach ($this->headersToInspect as $header) {
if ($request->hasHeader($header)) {
$ip = trim(current(explode(',', $request->getHeaderLine($header))));
if ($this->isValidIpAddress($ip)) {
$ipAddress = $ip;
break;
}
}
}
}
return $ipAddress;
}
示例7: handleRequest
/**
* Handles any backend request
*
* @param ServerRequestInterface $request
* @return NULL|ResponseInterface
*/
public function handleRequest(ServerRequestInterface $request)
{
// enable dispatching via Request/Response logic only for typo3/index.php
// This fallback will be removed in TYPO3 CMS 8, as only index.php will be allowed
$path = substr($request->getUri()->getPath(), strlen(GeneralUtility::getIndpEnv('TYPO3_SITE_PATH')));
$routingEnabled = $path === TYPO3_mainDir . 'index.php' || $path === TYPO3_mainDir;
$proceedIfNoUserIsLoggedIn = false;
if ($routingEnabled) {
$pathToRoute = (string) $request->getQueryParams()['route'];
// Allow the login page to be displayed if routing is not used and on index.php
if (empty($pathToRoute)) {
$pathToRoute = '/login';
}
$request = $request->withAttribute('routePath', $pathToRoute);
// Evaluate the constant for skipping the BE user check for the bootstrap
// should be handled differently in the future by checking the Bootstrap directly
if ($pathToRoute === '/login') {
$proceedIfNoUserIsLoggedIn = true;
}
}
$this->boot($proceedIfNoUserIsLoggedIn);
// Check if the router has the available route and dispatch.
if ($routingEnabled) {
return $this->dispatch($request);
}
// No route found, so the system proceeds in called entrypoint as fallback.
return null;
}
示例8: __invoke
/**
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @param callable|null $next
*
* @return HtmlResponse
*/
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
{
/* @var \PSR7Session\Session\SessionInterface $session */
$session = $request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE);
// Generate csrf token
if (!$session->get('csrf')) {
$session->set('csrf', md5(uniqid(rand(), true)));
}
// Generate form and inject csrf token
$form = FormFactory::fromHtml($this->template->render('app::contact-form', ['token' => $session->get('csrf')]));
// Get request data
$data = $request->getParsedBody() ?: [];
if ($request->getMethod() !== 'POST') {
// Display form
return new HtmlResponse($this->template->render('app::contact', ['form' => $form->asString()]), 200);
}
// Validate form
$validationResult = $form->validate($data);
if (!$validationResult->isValid()) {
// Display form and inject error messages and submitted values
return new HtmlResponse($this->template->render('app::contact', ['form' => $form->asString($validationResult)]), 200);
}
// Create the message
$message = Swift_Message::newInstance()->setFrom($this->config['from'])->setReplyTo($data['email'], $data['name'])->setTo($this->config['to'])->setSubject('[xtreamwayz-contact] ' . $data['subject'])->setBody($data['body']);
if ($this->config['transport']['debug'] !== true) {
$this->mailer->send($message);
}
// Display thank you page
return new HtmlResponse($this->template->render('app::contact-thank-you'), 200);
}
示例9: __invoke
/**
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @param callable $next
* @return ResponseInterface
*/
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
{
$routeInfo = $this->dispatcher->dispatch($request->getMethod(), $request->getUri()->getPath());
switch ($routeInfo[0]) {
case Dispatcher::NOT_FOUND:
$response = $response->withStatus(404);
break;
case Dispatcher::METHOD_NOT_ALLOWED:
$response = $response->withStatus(405);
break;
case Dispatcher::FOUND:
$callable = $routeInfo[1];
$args = $routeInfo[2];
if (isset($this->container)) {
$response = $this->container->call($callable, ['request' => $request, 'response' => $response, 'arguments' => $args]);
} else {
if (is_callable($callable)) {
call_user_func($callable, $request, $response, $args);
} else {
$callable = new $callable();
call_user_func($callable, $request, $response, $args);
}
}
break;
default:
return $response->withStatus(500);
}
$response = $next($request, $response);
return $response;
}
示例10: __invoke
/**
* Slim middleware entry point
*
* @param \Psr\Http\Message\ServerRequestInterface $request PSR7 request
* @param \Psr\Http\Message\ResponseInterface $response PSR7 response
* @param callable $next Next middleware
* @return \Psr\Http\Message\ResponseInterface
*/
public function __invoke($request, $response, $next)
{
$this->request = $request;
$this->response = $response;
$this->dispatch($request->getMethod(), $request->getUri());
return $next($this->request, $this->response);
}
示例11: __invoke
/**
* Apply the asset middleware.
*
* @param \Psr\Http\Message\ServerRequestInterface $request The request.
* @param \Psr\Http\Message\ResponseInterface $response The response.
* @param callable $next The callable to invoke the next middleware layer.
* @return \Psr\Http\Message\ResponseInterface A response.
*/
public function __invoke($request, $response, $next)
{
$path = $request->getUri()->getPath();
if (strpos($path, $this->urlPrefix) !== 0) {
// Not an asset request.
return $next($request, $response);
}
$factory = new Factory($this->config);
$assets = $factory->assetCollection();
$targetName = substr($path, strlen($this->urlPrefix));
if (!$assets->contains($targetName)) {
// Unknown build.
return $next($request, $response);
}
try {
$build = $assets->get($targetName);
$compiler = $factory->cachedCompiler($this->outputDir);
$contents = $compiler->generate($build);
} catch (Exception $e) {
// Could not build the asset.
$response->getBody()->write($e->getMessage());
return $response->withStatus(400)->withHeader('Content-Type', 'text/plain');
}
return $this->respond($response, $contents, $build->ext());
}
示例12: data
/**
* {@inheritdoc}
*/
protected function data(ServerRequestInterface $request, Document $document)
{
$id = array_get($request->getQueryParams(), 'id');
$actor = $request->getAttribute('actor');
$data = array_get($request->getParsedBody(), 'data');
return $this->bus->dispatch(new EditLink($id, $actor, $data));
}
示例13: generateKey
/**
* Generates a cache key based on a unique request.
*
* @todo determine parts required for unique request
* @param ServerRequestInterface $request
* @return string
*/
private function generateKey(ServerRequestInterface $request)
{
$params = $request->getQueryParams();
ksort($params);
$parts = [$request->getMethod(), $request->getUri()->getPath(), serialize($params)];
return sha1(implode(':', $parts));
}
示例14: __construct
public function __construct(ServerRequestInterface $request)
{
$this->body = $request->getParsedBody();
foreach ($request->getQueryParams() as $param => $value) {
switch ($param) {
case 'sort':
$parts = explode(',', $value);
foreach ($parts as $part) {
preg_match_all('/^(\\-)?([\\w]+)$/', $part, $matches);
if (empty($matches[0])) {
throw new \Exception('Invalid sort format.', 1);
}
$name = $matches[2][0];
$order = $matches[1][0];
$this->sort[$name] = $order;
}
break;
case 'pageSize':
case 'pageNumber':
$this->{$param} = $value;
break;
default:
$this->userFilters[$param] = $value;
}
}
}
示例15: __invoke
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $out = null)
{
$page = intval($request->getAttribute('page')) ?: 0;
$pictures = $this->apodApi->getPage($page, $this->resultsPerPage);
$response->getBody()->write(json_encode($pictures));
return $response->withHeader('Cache-Control', ['public', 'max-age=3600'])->withHeader('Content-Type', 'application/json');
}