当前位置: 首页>>代码示例>>PHP>>正文


PHP Message\ServerRequestInterface类代码示例

本文整理汇总了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);
 }
开发者ID:xtreamwayz,项目名称:xtreamwayz.com,代码行数:26,代码来源:ContactAction.php

示例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));
     }
 }
开发者ID:prooph,项目名称:psr7-middleware,代码行数:32,代码来源:MessageMiddleware.php

示例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;
 }
开发者ID:andela-gjames,项目名称:Emoji-API,代码行数:42,代码来源:Middleware.php

示例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());
 }
开发者ID:pumatertion,项目名称:bleicker.typo3.fastroute-requesthandler,代码行数:10,代码来源:RequestHandler.php

示例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;
 }
开发者ID:gobline,项目名称:router,代码行数:26,代码来源:PlaceholderRequestMatcher.php

示例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;
 }
开发者ID:gboily,项目名称:rka-ip-address-middleware,代码行数:32,代码来源:IpAddress.php

示例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;
 }
开发者ID:rickymathew,项目名称:TYPO3.CMS,代码行数:34,代码来源:RequestHandler.php

示例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);
 }
开发者ID:jkhaled,项目名称:xtreamwayz.com,代码行数:37,代码来源:ContactAction.php

示例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;
 }
开发者ID:air-php,项目名称:fastroute-middleware,代码行数:36,代码来源:FastRoute.php

示例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);
 }
开发者ID:juvenn,项目名称:php-sdk,代码行数:15,代码来源:SlimEngine.php

示例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());
 }
开发者ID:markstory,项目名称:mini-asset,代码行数:33,代码来源:AssetMiddleware.php

示例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));
 }
开发者ID:sijad,项目名称:flarum-ext-links,代码行数:10,代码来源:UpdateLinkController.php

示例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));
 }
开发者ID:tonis-io,项目名称:response-cache,代码行数:14,代码来源:ResponseCache.php

示例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;
         }
     }
 }
开发者ID:afilina,项目名称:phpapifoo,代码行数:26,代码来源:ApiRequest.php

示例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');
 }
开发者ID:AndrewCarterUK,项目名称:AstroSplash,代码行数:7,代码来源:PictureListAction.php


注:本文中的Psr\Http\Message\ServerRequestInterface类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。