本文整理汇总了PHP中Psr\Http\Message\ResponseInterface::withStatus方法的典型用法代码示例。如果您正苦于以下问题:PHP ResponseInterface::withStatus方法的具体用法?PHP ResponseInterface::withStatus怎么用?PHP ResponseInterface::withStatus使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Psr\Http\Message\ResponseInterface
的用法示例。
在下文中一共展示了ResponseInterface::withStatus方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: __invoke
/**
* Handle authentication
*
* @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 $request, Response $response, $next)
{
$path = $request->getUri()->getPath();
if ($path && $path != 'login') {
$serverParams = $request->getServerParams();
$authHeader = isset($serverParams['HTTP_X_AUTHORIZATION']) ? $serverParams['HTTP_X_AUTHORIZATION'] : null;
list($jwt) = sscanf($authHeader, 'Bearer %s');
if (!$jwt) {
return $response->withStatus(401)->write(json_encode(['message' => '401 Unauthorized']));
}
try {
$settings = $this->app->getContainer()->get('settings');
$secretKey = base64_decode($settings->get('jwt')['key']);
$token = JWT::decode($jwt, $secretKey, [$settings->get('jwt')['algorithm']]);
// Get the user info and add to the container
$this->app->getContainer()['currentUser'] = function ($c) use($token) {
return $token->data;
// user attributes
};
} catch (\Exception $e) {
return $response->withStatus(401)->write(json_encode(['message' => $e->getMessage()]));
}
}
$response = $next($request, $response);
return $response;
}
示例2: redirect
/**
* Mount redirect headers into response
*
* @param UriInterface|string $uri
* @param int $status
* @return ResponseInterface
* @throws \InvalidArgumentException
*/
public function redirect($uri, $status = 302)
{
if (!is_string($uri) && !$uri instanceof UriInterface) {
throw new \InvalidArgumentException("Redirect allowed only for string or UriInterface uris.");
}
return $this->response->withStatus($status)->withHeader("Location", (string) $uri);
}
示例3: validateToken
public function validateToken(ServerRequestInterface $request, ResponseInterface $response)
{
$authHeader = $request->getHeader('HTTP_AUTHORIZATION');
if (empty($authHeader)) {
$authHeader = apache_request_headers();
if (empty($authHeader['Authorization'])) {
throw (new OAuth2Exception('Authorization header is missing'))->displayMessage(OAuth2Exception::FORBIDDEN)->response($response->withStatus(403));
}
$authHeader = $authHeader['Authorization'];
} else {
$authHeader = $authHeader[0];
}
list($token) = sscanf($authHeader, 'Bearer %s');
if (!$token) {
throw (new OAuth2Exception('Token is missing in the request'))->displayMessage(OAuth2Exception::FORBIDDEN)->response($response->withStatus(403));
}
try {
$token = (new Parser())->parse($token);
} catch (\Exception $e) {
throw (new OAuth2Exception('Token was tampered'))->displayMessage(OAuth2Exception::FORBIDDEN)->response($response->withStatus(403));
}
if ($token->getClaim('exp') <= time()) {
throw (new OAuth2Exception('Token expired'))->displayMessage(OAuth2Exception::FORBIDDEN)->response($response->withStatus(403));
}
$this->info['id'] = $token->getClaim('sub');
foreach (explode(',', $token->getClaim('cc')) as $customClaim) {
$this->info[$customClaim] = $token->getClaim($customClaim);
}
if (!$token->verify(new Sha256(), $this->config['public-key'])) {
throw (new OAuth2Exception('Token was tampered'))->displayMessage(OAuth2Exception::FORBIDDEN)->response($response->withStatus(403));
}
return $response;
}
示例4: 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);
}
}
示例5: 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;
}
示例6: __invoke
/**
* Execute the middleware.
*
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @param callable $next
*
* @return ResponseInterface
*/
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
{
if (empty($this->router)) {
throw new RuntimeException('No RouterContainer instance has been provided');
}
$matcher = $this->router->getMatcher();
$route = $matcher->match($request);
if (!$route) {
$failedRoute = $matcher->getFailedRoute();
switch ($failedRoute->failedRule) {
case 'Aura\\Router\\Rule\\Allows':
return $response->withStatus(405);
// 405 METHOD NOT ALLOWED
// 405 METHOD NOT ALLOWED
case 'Aura\\Router\\Rule\\Accepts':
return $response->withStatus(406);
// 406 NOT ACCEPTABLE
// 406 NOT ACCEPTABLE
default:
return $response->withStatus(404);
// 404 NOT FOUND
}
}
$request = Middleware::setAttribute($request, self::KEY, $route);
foreach ($route->attributes as $name => $value) {
$request = $request->withAttribute($name, $value);
}
$response = $this->executeCallable($route->handler, $request, $response);
return $next($request, $response);
}
示例7: setHeadersFromArray
/**
* Add headers represented by an array of header lines.
*
* @param string[] $headers Response headers as array of header lines.
*
* @return $this
*
* @throws \UnexpectedValueException For invalid header values.
* @throws \InvalidArgumentException For invalid status code arguments.
*/
public function setHeadersFromArray(array $headers)
{
$statusLine = trim(array_shift($headers));
$parts = explode(' ', $statusLine, 3);
if (count($parts) < 2 || substr(strtolower($parts[0]), 0, 5) !== 'http/') {
throw new \UnexpectedValueException(sprintf('"%s" is not a valid HTTP status line', $statusLine));
}
$reasonPhrase = count($parts) > 2 ? $parts[2] : '';
$this->response = $this->response->withStatus((int) $parts[1], $reasonPhrase)->withProtocolVersion(substr($parts[0], 5));
foreach ($headers as $headerLine) {
$headerLine = trim($headerLine);
if ('' === $headerLine) {
continue;
}
$parts = explode(':', $headerLine, 2);
if (count($parts) !== 2) {
throw new \UnexpectedValueException(sprintf('"%s" is not a valid HTTP header line', $headerLine));
}
$name = trim(urldecode($parts[0]));
$value = trim(urldecode($parts[1]));
if ($this->response->hasHeader($name)) {
$this->response = $this->response->withAddedHeader($name, $value);
} else {
$this->response = $this->response->withHeader($name, $value);
}
}
return $this;
}
示例8: 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);
}
}
示例9: __invoke
public function __invoke(Request $req, Response $res, $args = [])
{
$vaultName = $args['vaultName'];
if (!Vault::create($vaultName)) {
return $res->withStatus(500);
}
return $res->withStatus(201);
}
示例10: __invoke
public function __invoke(Request $request, Response $response, callable $out = null)
{
if (!$request->hasHeader('authorization')) {
return $response->withStatus(401);
}
if (!$this->isValid($request)) {
return $response->withStatus(403);
}
return $out($request, $response);
}
示例11: __invoke
/**
* {@inheritdoc}
*/
public function __invoke(ServerRequestInterface $request, ResponseInterface $response)
{
try {
$page = new Page($this->basePath, $this->defaultPage);
return $response->withStatus(301)->withHeader('Location', '/' . $page->getName());
} catch (\Exception $e) {
$this->logger->debug(sprintf('Page creation failed, due to "%s"', $e->getMessage()));
}
return $response->withStatus(404);
}
示例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)
{
if ($request->getMethod() !== 'GET') {
return $response->withStatus(405);
}
$file = $this->getFilename($request);
if (!is_file($file)) {
return $response->withStatus(404);
}
return $next($request, $response->withBody(Middleware::createStream($file)));
}
示例13: __invoke
public function __invoke(Request $req, Response $res, $args = [])
{
$vaultName = $args['vaultName'];
$multipartID = $args['multipartID'];
if (!($vault = Vault::get($vaultName))) {
return $res->withStatus(404);
}
if ($m = $vault->getMultipart($multipartID)) {
$m->delete();
}
return $res->withStatus(204);
}
示例14: process
/**
* {@inheritdoc}
*/
public function process(RequestInterface $request, DelegateInterface $delegate)
{
try {
$response = $delegate->next($request);
} catch (\Exception $e) {
if ($this->logger instanceof LoggerInterface) {
$this->logger->error($e);
}
return $this->response->withStatus(500);
}
return $response;
}
示例15: __invoke
public function __invoke(Request $req, Response $res, $args = [])
{
$vaultName = $args['vaultName'];
$multipartID = $args['multipartID'];
if (!($vault = Vault::get($vaultName))) {
return $res->withStatus(404);
}
if (!($m = $vault->getMultipart($multipartID))) {
return $res->withStatus(404);
}
return $res->withJson($m->serializeArray(true), 200, JSON_PRETTY_PRINT);
}