本文整理汇总了PHP中Psr\Http\Message\ServerRequestInterface::withAttribute方法的典型用法代码示例。如果您正苦于以下问题:PHP ServerRequestInterface::withAttribute方法的具体用法?PHP ServerRequestInterface::withAttribute怎么用?PHP ServerRequestInterface::withAttribute使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Psr\Http\Message\ServerRequestInterface
的用法示例。
在下文中一共展示了ServerRequestInterface::withAttribute方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: run
/**
* Set up the application and shut it down afterwards
*
* @param callable $execute
* @return void
*/
public function run(callable $execute = null)
{
$this->request = \TYPO3\CMS\Core\Http\ServerRequestFactory::fromGlobals();
// see below when this option is set and Bootstrap::defineTypo3RequestTypes() for more details
if (TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_AJAX) {
$this->request = $this->request->withAttribute('isAjaxRequest', true);
} elseif (isset($this->request->getQueryParams()['M'])) {
$this->request = $this->request->withAttribute('isModuleRequest', true);
}
$this->bootstrap->handleRequest($this->request);
if ($execute !== null) {
call_user_func($execute);
}
$this->bootstrap->shutdown();
}
示例2: logIn
/**
* @param Request $request
* @return Request
*/
protected function logIn(Request $request)
{
$header = $request->getHeaderLine('authorization');
$parts = explode(';', $header);
$actor = new Guest();
if (isset($parts[0]) && starts_with($parts[0], $this->prefix)) {
$token = substr($parts[0], strlen($this->prefix));
if (($accessToken = AccessToken::find($token)) && $accessToken->isValid()) {
$actor = $accessToken->user;
$actor->updateLastSeen()->save();
} elseif (isset($parts[1]) && ($apiKey = ApiKey::valid($token))) {
$userParts = explode('=', trim($parts[1]));
if (isset($userParts[0]) && $userParts[0] === 'userId') {
$actor = User::find($userParts[1]);
}
}
}
if ($actor->exists) {
$locale = $actor->getPreference('locale');
} else {
$locale = array_get($request->getCookieParams(), 'locale');
}
if ($locale && $this->locales->hasLocale($locale)) {
$this->locales->setLocale($locale);
}
return $request->withAttribute('actor', $actor ?: new Guest());
}
示例3: __invoke
/**
* Our job as a pipe rat router is to set the "ResourceKey" route param to the
* data that we are given for the matched route.
*
* @param Request $request
* @param Response $response
* @param callable|null $out
*
* @return mixed
* @throws RouteException
*/
public function __invoke(Request $request, Response $response, callable $out = null)
{
$aPathMatched = false;
$paths = $request->getAttribute(Paths::ATTRIBUTE_NAME);
/**
*
*/
foreach ($paths as $availablePath => $availableVerbs) {
$regex = '/^' . str_replace(['{', '}', '/'], ['(?<', '>[^/]+)', '\\/'], $availablePath) . '$/';
if (preg_match($regex, $request->getUri()->getPath(), $captures)) {
$aPathMatched = true;
foreach ($availableVerbs as $availableVerb => $routeData) {
if (strcasecmp($availableVerb, $request->getMethod()) === 0) {
return $out($request->withAttribute(ResourceKey::ATTRIBUTE_NAME, $routeData)->withAttribute(RouteParams::ATTRIBUTE_NAME, new RouteParams($this->parseNamedCaptures($captures))), $response);
}
}
break;
}
}
if ($aPathMatched) {
//A path matched but a verb did not so return "Method not allowed"
return $response->withStatus(405);
}
//No paths matched so do nothing and allow other middleware to handle this request.
return $out($request, $response);
}
示例4: validateAuthorization
/**
* {@inheritdoc}
*/
public function validateAuthorization(ServerRequestInterface $request)
{
if ($request->hasHeader('authorization') === false) {
throw OAuthServerException::accessDenied('Missing "Authorization" header');
}
$header = $request->getHeader('authorization');
$jwt = trim(preg_replace('/^(?:\\s+)?Bearer\\s/', '', $header[0]));
try {
// Attempt to parse and validate the JWT
$token = (new Parser())->parse($jwt);
if ($token->verify(new Sha256(), $this->publicKey->getKeyPath()) === false) {
throw OAuthServerException::accessDenied('Access token could not be verified');
}
// Ensure access token hasn't expired
$data = new ValidationData();
$data->setCurrentTime(time());
if ($token->validate($data) === false) {
throw OAuthServerException::accessDenied('Access token is invalid');
}
// Check if token has been revoked
if ($this->accessTokenRepository->isAccessTokenRevoked($token->getClaim('jti'))) {
throw OAuthServerException::accessDenied('Access token has been revoked');
}
// Return the request with additional attributes
return $request->withAttribute('oauth_access_token_id', $token->getClaim('jti'))->withAttribute('oauth_client_id', $token->getClaim('aud'))->withAttribute('oauth_user_id', $token->getClaim('sub'))->withAttribute('oauth_scopes', $token->getClaim('scopes'));
} catch (\InvalidArgumentException $exception) {
// JWT couldn't be parsed so return the request as is
throw OAuthServerException::accessDenied($exception->getMessage());
} catch (\RuntimeException $exception) {
//JWR couldn't be parsed so return the request as is
throw OAuthServerException::accessDenied('Error while decoding to JSON');
}
}
示例5: dispatchModule
/**
* Executes the modules configured via Extbase
*
* @param string $moduleName
* @return Response A PSR-7 response object
* @throws \RuntimeException
*/
protected function dispatchModule($moduleName)
{
$moduleConfiguration = $this->getModuleConfiguration($moduleName);
// Check permissions and exit if the user has no permission for entry
$this->backendUserAuthentication->modAccess($moduleConfiguration, true);
$id = isset($this->request->getQueryParams()['id']) ? $this->request->getQueryParams()['id'] : $this->request->getParsedBody()['id'];
if ($id && MathUtility::canBeInterpretedAsInteger($id)) {
// Check page access
$permClause = $this->backendUserAuthentication->getPagePermsClause(true);
$access = is_array(BackendUtility::readPageAccess((int) $id, $permClause));
if (!$access) {
throw new \RuntimeException('You don\'t have access to this page', 1289917924);
}
}
/** @var Response $response */
$response = GeneralUtility::makeInstance(Response::class);
// Use Core Dispatching
if (isset($moduleConfiguration['routeTarget'])) {
$dispatcher = GeneralUtility::makeInstance(Dispatcher::class);
$this->request = $this->request->withAttribute('target', $moduleConfiguration['routeTarget']);
$response = $dispatcher->dispatch($this->request, $response);
} else {
// extbase module
$configuration = array('extensionName' => $moduleConfiguration['extensionName'], 'pluginName' => $moduleName);
if (isset($moduleConfiguration['vendorName'])) {
$configuration['vendorName'] = $moduleConfiguration['vendorName'];
}
// Run Extbase
$bootstrap = GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\Core\Bootstrap::class);
$content = $bootstrap->run('', $configuration);
$response->getBody()->write($content);
}
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)
{
$user = null;
if (isset($_SESSION) && isset($_SESSION['twitterUser'])) {
$user = $_SESSION['twitterUser'];
}
return $next($request->withAttribute(self::USER, $user), $response);
}
示例7: parse
/**
* {@inheritDoc}
*/
public function parse(ServerRequestInterface $request)
{
$rawBody = (string) $request->getBody();
$parsedBody = json_decode($rawBody, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new MalformedRequestBodyException('Error when parsing JSON request body: ' . json_last_error_msg());
}
return $request->withAttribute('rawBody', $rawBody)->withParsedBody($parsedBody);
}
示例8: withPaths
/**
* withPaths
*
* set Reliv\PipeRat\RequestAttribute\Paths attribute = array ['/{path}' => ['{verb}' => 'resourceKey']]
*
* @param Request $request
*
* @return Request
*/
public function withPaths(Request $request)
{
if (!empty($this->paths)) {
$request->withAttribute(Paths::getName(), $this->paths);
return $request;
}
$resourceConfig = $this->getResourceConfig();
/**
* @var string $resourceName
* @var Options $resourceOptions
*/
foreach ($resourceConfig as $resourceName => $resourceOptions) {
$resourcePath = $resourceOptions->get('path', '/' . $resourceName);
$methodsAllowed = $resourceOptions->get('methodsAllowed', []);
$methods = $resourceOptions->get('methods', []);
$methodPriority = $resourceOptions->get('methodPriority', []);
$this->buildMethods($resourceName, $resourcePath, $methodsAllowed, $methods, $methodPriority);
}
return $request->withAttribute(Paths::getName(), $this->paths);
}
示例9: __invoke
/**
* Execute the middleware
*
* @param ServerRequestInterface $request
* @param ResponseInterface $response
*
* @return ResponseInterface
*/
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
{
$negotiator = new Negotiator();
$language = $negotiator->getBest($request->getHeaderLine('Accept-Language'), $this->languages);
if ($language) {
$language = strtolower(substr($language->getValue(), 0, 2));
} else {
$language = isset($this->languages[0]) ? $this->languages[0] : null;
}
return $next($request->withAttribute('LANGUAGE', $language), $response);
}
示例10: it_should_throw_exception_when_class_is_not_implement_interface
public function it_should_throw_exception_when_class_is_not_implement_interface(ServerRequestInterface $request, UriInterface $uri, ResponseInterface $response, GroupCountBased $dispatcher, ContainerInterface $container)
{
$request->getMethod()->willReturn('GET');
$request->getUri()->willReturn($uri);
$uri->getPath()->willReturn('/');
$dispatcher->dispatch('GET', '/')->willReturn([Dispatcher::FOUND, 'Test', []]);
$request->withAttribute('param', [])->shouldBeCalled();
$container->offsetGet('Test')->willReturn(new \ArrayObject());
$this->shouldThrow(InternalErrorHttpException::class)->during('__invoke', [$request, $response, function ($request, $response) {
return $response;
}]);
}
示例11: __invoke
/**
* {@inheritdoc}
*/
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, \Closure $next = null)
{
//Opening cookie scope
$outerCookies = $this->container->replace(self::class, $this);
$this->request = $this->decodeCookies($request);
$response = $next($this->request->withAttribute('cookieDomain', $this->cookieDomain()));
//New cookies
$response = $this->mountCookies($response);
//Restoring scope
$this->container->restore($outerCookies);
return $response;
}
示例12: __construct
/**
* Constructor setting up legacy constant and register available Request Handlers
*
* @param \Composer\Autoload\ClassLoader $classLoader an instance of the class loader
*/
public function __construct($classLoader)
{
$this->defineLegacyConstants();
$this->bootstrap = Bootstrap::getInstance()->initializeClassLoader($classLoader)->baseSetup($this->entryPointPath);
// can be done here after the base setup is done
$this->defineAdditionalEntryPointRelatedConstants();
// Redirect to install tool if base configuration is not found
if (!$this->bootstrap->checkIfEssentialConfigurationExists()) {
$this->bootstrap->redirectToInstallTool($this->entryPointPath);
}
foreach ($this->availableRequestHandlers as $requestHandler) {
$this->bootstrap->registerRequestHandlerImplementation($requestHandler);
}
$this->request = \TYPO3\CMS\Core\Http\ServerRequestFactory::fromGlobals();
// see below when this option is set
if ($GLOBALS['TYPO3_AJAX']) {
$this->request = $this->request->withAttribute('isAjaxRequest', true);
} elseif (isset($this->request->getQueryParams()['M'])) {
$this->request = $this->request->withAttribute('isModuleRequest', true);
}
$this->bootstrap->configure();
}
示例13: __invoke
/**
* Invoke middleware.
*
* @param ServerRequestInterface $request request object
* @param ResponseInterface $response response object
* @param callable $next next middleware
*
* @return ResponseInterface response object
*/
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
{
$isValid = $request->getAttribute(self::$isValidAttribute, false);
$violations = $request->getAttribute(self::$violationsAttribute, []);
foreach ($request->getHeader($this->headerName) as $token) {
$tokenViolations = call_user_func($this->tokenValidator, $token);
if (count($tokenViolations) === 0) {
$isValid = true;
continue;
}
$violations = array_merge($violations, $tokenViolations);
}
return $next($request->withAttribute(self::$isValidAttribute, $isValid)->withAttribute(self::$violationsAttribute, $violations), $response);
}
示例14: __invoke
/**
* Execute the middleware.
*
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @param callable $next
*
* @return ResponseInterface
*/
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
{
/* @var $view \Slim\Views\Twig */
$view = $this->ci->get('view');
/* @var $autoLogin \nanotwi\AutoLogin */
$autoLogin = $this->ci->get('autoLogin');
/* @var $autoLogin \nanotwi\NanoTwitter */
$nanoTwitter = $this->ci->get('nanoTwitter');
$routeInfo = $request->getAttribute('routeInfo')[2];
//https://github.com/slimphp/Slim/issues/1505#issuecomment-142193606
$token = $routeInfo['token'];
$oAuthToken = $autoLogin->parseAutologinToken($token);
$view['token'] = $token;
return $next($request->withAttribute('autologinToken', $token)->withAttribute('oAuth', $oAuthToken), $response);
}
示例15: callsNextMiddlewareIfResponderReturnedAResponse
/**
* @test
*/
public function callsNextMiddlewareIfResponderReturnedAResponse()
{
$called = false;
$next = function (ServerRequestInterface $request, ResponseInterface $response, callable $next = null) use(&$called) : ResponseInterface {
$called = true;
return $response;
};
$responder = $this->createMock(Responder::class, ['__invoke']);
$responder->expects($this->once())->method('__invoke')->will($this->returnValue(new Response()));
$payload = $this->createMock(Payload::class);
$this->request = $this->request->withAttribute(self::$responderAttribute, $responder);
$this->request = $this->request->withAttribute(self::$payloadAttribute, $payload);
$this->middleware->__invoke($this->request, $this->response, $next);
$this->assertTrue($called);
}