/** * @param Request $request * @return Executable */ public function routeRequest(Request $request, $fn404ErrorPage = null, $fn405ErrorPage = null) { $path = $request->getUri()->getPath(); $routeInfo = $this->dispatcher->dispatch($request->getMethod(), $path); $dispatcherResult = $routeInfo[0]; if ($dispatcherResult === Dispatcher::FOUND) { $handler = $routeInfo[1]; $vars = $routeInfo[2]; // Share the params once as parameters so they can // be injected by name $injectionParams = InjectionParams::fromParams($vars); // and then share them as a type $injectionParams->share(new RouteParams($vars)); $executable = new Executable($handler, $injectionParams, null); return $executable; } else { if ($dispatcherResult === Dispatcher::METHOD_NOT_ALLOWED) { if ($fn405ErrorPage === null) { $message = sprintf("Method '%s' not allowed for path '%s'", $request->getMethod(), $path); throw new MethodNotAllowedException($message); } $executable = new Executable($fn405ErrorPage); return $executable; } } if ($fn404ErrorPage === null) { throw new RouteNotMatchedException("Route not matched for path {$path}"); } $executable = new Executable($fn404ErrorPage); return $executable; }
/** * Convert a PSR-7 ServerRequest to a Zend\Http server-side request. * * @param ServerRequestInterface $psr7Request * @param bool $shallow Whether or not to convert without body/file * parameters; defaults to false, meaning a fully populated request * is returned. * @return Zend\Request */ public static function toZend(ServerRequestInterface $psr7Request, $shallow = false) { if ($shallow) { return new Zend\Request($psr7Request->getMethod(), $psr7Request->getUri(), $psr7Request->getHeaders(), $psr7Request->getCookieParams(), $psr7Request->getQueryParams(), [], [], $psr7Request->getServerParams()); } $zendRequest = new Zend\Request($psr7Request->getMethod(), $psr7Request->getUri(), $psr7Request->getHeaders(), $psr7Request->getCookieParams(), $psr7Request->getQueryParams(), $psr7Request->getParsedBody() ?: [], self::convertUploadedFiles($psr7Request->getUploadedFiles()), $psr7Request->getServerParams()); $zendRequest->setContent($psr7Request->getBody()); return $zendRequest; }
/** * Check if the token match with the given verify token. * This is useful in the webhook setup process. * * @return bool */ public function isValidVerifyTokenRequest() { if ($this->request->getMethod() !== 'GET') { return false; } $params = $this->request->getQueryParams(); if (!isset($params['hub_verify_token'])) { return false; } return $params['hub_verify_token'] === $this->verifyToken; }
/** * @throws \WoohooLabs\Harmony\Exception\MethodNotAllowed * @throws \WoohooLabs\Harmony\Exception\RouteNotFound */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) : ResponseInterface { $route = $this->fastRoute->dispatch($request->getMethod(), $request->getUri()->getPath()); if ($route[0] === Dispatcher::NOT_FOUND) { throw new RouteNotFound($request->getUri()->getPath()); } if ($route[0] === Dispatcher::METHOD_NOT_ALLOWED) { throw new MethodNotAllowed($request->getMethod()); } foreach ($route[2] as $name => $value) { $request = $request->withAttribute($name, $value); } $request = $request->withAttribute($this->actionAttributeName, $route[1]); return $next($request, $response); }
/** * @param Request $request * @return Executable */ public function routeRequest(Request $request) { $path = $request->getUri()->getPath(); $routeInfo = $this->dispatcher->dispatch($request->getMethod(), $path); $dispatcherResult = $routeInfo[0]; if ($dispatcherResult === \FastRoute\Dispatcher::FOUND) { $handler = $routeInfo[1]; $vars = $routeInfo[2]; $injectionParams = InjectionParams::fromParams($vars); $injectionParams->share(new \Tier\JigBridge\RouteInfo($vars)); $executable = new Executable($handler, $injectionParams, null); $executable->setTierNumber(TierHTTPApp::TIER_GENERATE_BODY); return $executable; } else { if ($dispatcherResult === \FastRoute\Dispatcher::METHOD_NOT_ALLOWED) { //TODO - need to embed allowedMethods....theoretically. $executable = new Executable([$this, 'serve405ErrorPage']); $executable->setTierNumber(TierHTTPApp::TIER_GENERATE_BODY); return $executable; } } $executable = new Executable([$this, 'serve404ErrorPage']); $executable->setTierNumber(TierHTTPApp::TIER_GENERATE_BODY); return $executable; }
/** * Process an incoming request and/or response. * * Accepts a server-side request and a response instance, and does * something with them. * * If the response is not complete and/or further processing would not * interfere with the work done in the middleware, or if the middleware * wants to delegate to another process, it can use the `$out` callable * if present. * * If the middleware does not return a value, execution of the current * request is considered complete, and the response instance provided will * be considered the response to return. * * Alternately, the middleware may return a response instance. * * Often, middleware will `return $out();`, with the assumption that a * later middleware will return a response. * * @param Request $request * @param Response $response * @param null|callable $out * @return null|Response */ public function __invoke(Request $request, Response $response, callable $out = null) { if ($request->getMethod() === 'OPTIONS') { return $response; } return $this->dispatch($request, $response, $out); }
/** * Invocation * * Register routes container and request attributes * * @param ServerRequestInterface $request Request * @param ResponseInterface $response Response * @param TornadoHttp $next Next Middleware - TornadoHttp container * @return ResponseInterface * @throws HttpMethodNotAllowedException * @throws HttpNotFoundException */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, TornadoHttp $next) { /** @var \FastRoute\Dispatcher\GroupCountBased $dispatcher */ $dispatcher = FastRoute\simpleDispatcher(function (RouteCollector $routeCollector) { foreach ($this->routes as $key => $route) { $routeCollector->addRoute($route['methods'], $route['path'], $key); } }); $method = $request->getMethod(); $uri = rawurldecode(parse_url($request->getUri(), \PHP_URL_PATH)); $route = $dispatcher->dispatch($method, $uri); $handler = null; $vars = null; switch ($route[0]) { case Dispatcher::NOT_FOUND: throw new HttpNotFoundException('Inexistent route for the url ' . $request->getUri()); case Dispatcher::METHOD_NOT_ALLOWED: throw new HttpMethodNotAllowedException('Method not allowed'); case Dispatcher::FOUND: $handler = $route[1]; $vars = $route[2]; break; } $request = $request->withAttribute(Router::REGISTER_KEY, $handler); foreach ($vars as $name => $value) { $request = $request->withAttribute($name, $value); } return $next($request, $response); }
protected function dispatch(Request $request) { $method = $request->getMethod(); if (!is_string($method)) { throw new ApiException(405, 'Unsupported HTTP method; must be a string, received ' . (is_object($method) ? get_class($method) : gettype($method))); } $method = strtoupper($method); /** @var Resource $resource */ $resource = $this->getResource(); if ('GET' === $method) { if ($id = $request->getAttribute(static::PK)) { $result = $resource->fetch($id, $request->getQueryParams()); } else { $result = $resource->fetchAll($request->getQueryParams()); } } elseif ('POST' === $method) { $result = $resource->create($request->getParsedBody()); } elseif ('PUT' === $method) { $result = $resource->update($request->getAttribute(static::PK), $request->getParsedBody()); } elseif ('PATCH' === $method) { $result = $resource->patch($request->getAttribute(static::PK), $request->getParsedBody()); } elseif ('DELETE' === $method) { $result = $resource->delete($request->getAttribute(static::PK)); } else { throw new ApiException(405, 'The ' . $method . ' method has not been defined'); } return $result; }
/** * @param ServerRequestInterface $request * @param ResponseInterface $response * @param array $methods * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, array $methods) { $this->isOptions = $request->getMethod() === 'OPTIONS'; $this->allowed = $methods; $response = $response->withHeader('Allow', implode(', ', $this->allowed)); return parent::__invoke($request, $response); }
/** * 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); }
/** * @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); }
private function _extractDataPSR7(ServerRequestInterface $request = null, $name = '') { $method = $request->getMethod(); $queryParams = $request->getQueryParams(); if ('GET' === $method) { if ('' === $name) { return $queryParams; } // Don't submit GET requests if the form's name does not exist // in the request if (!isset($queryParams[$name])) { return; } return $queryParams[$name]; } $serverParams = $request->getServerParams(); $uploadedFiles = $request->getUploadedFiles(); if ('' === $name) { return $this->mergeParamsAndUploadedFiles($serverParams, $uploadedFiles); } if (isset($serverParams[$name]) || isset($uploadedFiles[$name])) { $default = null; $params = isset($serverParams[$name]) ? $serverParams[$name] : null; $files = isset($uploadedFiles[$name]) ? $uploadedFiles[$name] : null; return $this->mergeParamsAndUploadedFiles($params, $files); } // Don't submit the form if it is not present in the request return; }
/** * Index action shows install tool / step installer or redirect to action to enable install tool * * @param ServerRequestInterface $request * @param ResponseInterface $response * @return ResponseInterface */ public function index(ServerRequestInterface $request, ResponseInterface $response) { /** @var EnableFileService $enableFileService */ $enableFileService = GeneralUtility::makeInstance(EnableFileService::class); /** @var AbstractFormProtection $formProtection */ $formProtection = FormProtectionFactory::get(); if ($enableFileService->checkInstallToolEnableFile()) { // Install tool is open and valid, redirect to it $response = $response->withStatus(303)->withHeader('Location', 'sysext/install/Start/Install.php?install[context]=backend'); } elseif ($request->getMethod() === 'POST' && $request->getParsedBody()['action'] === 'enableInstallTool') { // Request to open the install tool $installToolEnableToken = $request->getParsedBody()['installToolEnableToken']; if (!$formProtection->validateToken($installToolEnableToken, 'installTool')) { throw new \RuntimeException('Given form token was not valid', 1369161225); } $enableFileService->createInstallToolEnableFile(); // Install tool is open and valid, redirect to it $response = $response->withStatus(303)->withHeader('Location', 'sysext/install/Start/Install.php?install[context]=backend'); } else { // Show the "create enable install tool" button /** @var StandaloneView $view */ $view = GeneralUtility::makeInstance(StandaloneView::class); $view->setTemplatePathAndFilename(GeneralUtility::getFileAbsFileName('EXT:install/Resources/Private/Templates/BackendModule/ShowEnableInstallToolButton.html')); $token = $formProtection->generateToken('installTool'); $view->assign('installToolEnableToken', $token); /** @var ModuleTemplate $moduleTemplate */ $moduleTemplate = GeneralUtility::makeInstance(ModuleTemplate::class); $cssFile = 'EXT:install/Resources/Public/Css/BackendModule/ShowEnableInstallToolButton.css'; $cssFile = GeneralUtility::getFileAbsFileName($cssFile); $moduleTemplate->getPageRenderer()->addCssFile(PathUtility::getAbsoluteWebPath($cssFile)); $moduleTemplate->setContent($view->render()); $response->getBody()->write($moduleTemplate->renderContent()); } return $response; }
/** * {@inheritdoc} */ public function match(ServerRequestInterface $request) : RoutingResult { $requestPath = $request->getUri()->getPath(); $this->logger->debug(sprintf('Analysing request path "%s"', $requestPath)); $candidates = []; /** @var array $routeDefinition */ foreach ($this->routes as $routeDefinition) { $route = $routeDefinition['route']; $identifier = $this->getRouteIdentifier($route); $this->logger->debug(sprintf('Trying to match requested path to route "%s"', $identifier)); $urlVars = []; if (preg_match_all($routeDefinition['pathMatcher'], $requestPath, $urlVars)) { $method = strtoupper(trim($request->getMethod())); if (!in_array($method, $route->getMethods())) { $candidates[] = ['route' => $route, 'failure' => RoutingResult::FAILED_METHOD_NOT_ALLOWED]; continue; } // remove all elements which should not be set in the request, // e.g. the matching url string as well as all numeric items $params = $this->mapParams($urlVars); if (!$this->matchParams($route, $params)) { $candidates[] = ['route' => $route, 'failure' => RoutingResult::FAILED_BAD_REQUEST]; continue; } $this->logger->debug(sprintf('Route "%s" matches. Applying its target...', $identifier)); return RoutingResult::forSuccess($route, $params); } } $this->logger->debug('No matching route found.'); if (count($candidates)) { $candidate = $candidates[0]; return RoutingResult::forFailure($candidate['failure'], $candidate['route']); } return RoutingResult::forFailure(RoutingResult::FAILED_NOT_FOUND); }
/** * Invoke "Maintenance" Handler * * @param ServerRequestInterface $request The most recent Request object. * @param ResponseInterface $response The most recent Response object. * @param string[] $methods Allowed HTTP methods. * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, array $methods) { $this->setMethods($methods); if ($request->getMethod() === 'OPTIONS') { $contentType = 'text/plain'; $output = $this->renderPlainOutput(); } else { $contentType = $this->determineContentType($request); switch ($contentType) { case 'application/json': $output = $this->renderJsonOutput(); break; case 'text/xml': case 'application/xml': $output = $this->renderXmlOutput(); break; case 'text/html': default: $output = $this->renderHtmlOutput(); break; } } $body = new Body(fopen('php://temp', 'r+')); $body->write($output); return $response->withStatus(503)->withHeader('Content-type', $contentType)->withBody($body); }
/** * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable $next * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next) { $method = $request->getMethod(); // Dispatch middleware registered with the explicitly matching method. if (isset($this->map[$method])) { $middleware = $this->map[$method]; return $this->dispatchMiddleware($middleware, $request, $response, $next); } // For HEAD, dispatch GET by default. if ($method === "HEAD" && isset($this->map["GET"])) { $middleware = $this->map["GET"]; return $this->dispatchMiddleware($middleware, $request, $response, $next); } // Dispatch * middleware, if registered. if (isset($this->map["*"])) { $middleware = $this->map["*"]; return $this->dispatchMiddleware($middleware, $request, $response, $next); } // Respond describing the allowed methods, either as a 405 response or // in response to an OPTIONS request. if ($method === "OPTIONS") { $response = $response->withStatus(200); } else { $response = $response->withStatus(405); } return $this->addAllowHeader($response); }
/** * 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); }
/** * Execute the middleware. Don't call this method directly; it is used by the `Application` internally. * * @internal * * @param ServerRequestInterface $request The request object * @param ResponseInterface $response The response object * @param callable $next The next middleware handler * * @return ResponseInterface */ public function handle(ServerRequestInterface $request, ResponseInterface $response, callable $next = null) { $attributes = $request->getAttributes(); if (!isset($attributes['command'])) { switch (strtoupper($request->getMethod())) { case 'GET': $params = new Registry($request->getQueryParams()); break; case 'POST': default: $params = new Registry($request->getAttributes()); break; } $extension = ucfirst(strtolower($params->get('option', 'Article'))); $action = ucfirst(strtolower($params->get('task', 'display'))); $entity = $params->get('entity', 'error'); $id = $params->get('id', null); $commandClass = "\\Joomla\\Extension\\{$extension}\\Command\\{$action}Command"; if (class_exists($commandClass)) { $command = new $commandClass($entity, $id, $response->getBody()); $request = $request->withAttribute('command', $command); } // @todo Emit afterRouting event } return $next($request, $response); }
/** * @param Request $request * @param Response $response * @param callable $next * @return \Psr\Http\Message\MessageInterface|HtmlResponse * @throws Exception */ public function __invoke(Request $request, Response $response, callable $next) { //$form = new LoginForm('Login', []); //$form->get('submit')->setValue('Login'); if ($request->getMethod() == 'POST') { $auth = new AuthenticationService(); $query = $request->getParsedBody(); $authAdapter = new AuthAdapter($query['login'], $query['password'], $this->authConfig); $result = $auth->authenticate($authAdapter); if (!$result->isValid()) { //$response->getBody()->write("Not valid authentication\n"); //return $response->withStatus(403)->withHeader("Content-type", 'text/html'); throw new Exception("Not valid authentication\n", 403); } else { if ($request->getUri()->getPath() === '/auth') { $render = $this->template->render('app::homepage'); $query = $request->getParsedBody(); $query['view']['render'] = $render; $query['view']['code'] = 200; $request = $request->withParsedBody($query); } return $next($request, $response); } } else { $render = $this->template->render('app::login', ['error' => null]); $query = $request->getParsedBody(); $query['view']['render'] = $render; $query['view']['code'] = 200; $request = $request->withParsedBody($query); return $next($request, $response); } }
/** * Invoke error handler * * @param ServerRequestInterface $request The most recent Request object * @param ResponseInterface $response The most recent Response object * @param string[] $methods Allowed HTTP methods * * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, array $methods) { if ($request->getMethod() === 'OPTIONS') { $status = 200; $contentType = 'text/plain'; $output = $this->renderPlainNotAllowedMessage($methods); } else { $status = 405; $contentType = $this->determineContentType($request); switch ($contentType) { case 'application/json': $output = $this->renderJsonNotAllowedMessage($methods); break; case 'text/xml': case 'application/xml': $output = $this->renderXmlNotAllowedMessage($methods); break; case 'text/html': $output = $this->renderHtmlNotAllowedMessage($methods); break; } } $body = new Body(fopen('php://temp', 'r+')); $body->write($output); $allow = implode(', ', $methods); return $response->withStatus($status)->withHeader('Content-type', $contentType)->withHeader('Allow', $allow)->withBody($body); }
/** * 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)); }
/** * 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) { if (in_array($request->getMethod(), $this->methods)) { $request = $request->withAttribute(self::$isValidAttribute, true); } return $next($request, $response); }
/** * @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; }
/** * @param Request $request * @return Executable */ public function routeRequest(Request $request) { $path = $request->getUri()->getPath(); $routeInfo = $this->dispatcher->dispatch($request->getMethod(), $path); $dispatcherResult = $routeInfo[0]; if ($dispatcherResult === \FastRoute\Dispatcher::FOUND) { $handler = $routeInfo[1]; $vars = $routeInfo[2]; // Share the params once as parameters so they can // be injected by name $injectionParams = InjectionParams::fromParams($vars); // and then share them as a type $injectionParams->share(new \Tier\Bridge\RouteParams($vars)); return new Executable($handler, $injectionParams, null); } else { if ($dispatcherResult === \FastRoute\Dispatcher::METHOD_NOT_ALLOWED) { //TODO - need to embed allowedMethods....theoretically. return new Executable([$this, 'serve405ErrorPage']); } } $templateName = $this->templateExists($path, $this->jigConfig); if ($templateName !== false) { return $this->tierJig->createJigExecutable($templateName); } return new Executable([$this, 'serve404ErrorPage']); }
/** * Example middleware invokable class * * @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(ServerRequestInterface $request, ResponseInterface $response, callable $next) { $auth = $request->getHeader('Authenticate'); if ($request->getMethod() === 'GET') { // Get is allowed without authentication // Rate-Limit is handlede by another Middleware return $next($request, $response); } if (!$auth) { $response = $response->withHeader('WWW-Authenticate', 'Bearer realm="callingallpapers", error="no token", error_desciption="No Access-Token provided"'); $response = $response->withStatus(401); return $response; } $bearer = explode(' ', $auth[0]); if (!isset($bearer[1])) { $response = $response->withHeader('WWW-Authenticate', 'Bearer realm="callingallpapers", error="no token", error_desciption="No Access-Token provided"'); $response = $response->withStatus(401); return $response; } $bearer = $bearer[1]; $upl = new UserPersistenceLayer($this->app->getContainer()['pdo']); try { $user = $upl->getUserForToken($bearer); } catch (\Exception $e) { $response = $response->withHeader('WWW-Authenticate', 'Bearer realm="callingallpapers", error="invalid token", error_desciption="Invalid Access-Token provided"'); $response = $response->withStatus(401); return $response; } $request = $request->withAttribute('user', $user['user']); return $next($request, $response); }
public function match(array $route, Request $request) { $httpMethod = key($route); $stringRoute = current($route); if (in_array($httpMethod, ['GET', 'POST', 'PUT', 'DELETE'])) { if ($httpMethod !== $request->getMethod()) { return false; } } $match = $this->stringRouter->match($stringRoute, $request->getUri()->getPath()); if ($match === false) { return false; } array_shift($route); foreach ($route as $method => $rules) { $getter = 'get' . ucfirst($method); foreach ($rules as $param => $callback) { $value = call_user_func([$request, $getter], $param); if (!$callback($value)) { return false; } } } return $match; }
/** * {@inheritdoc} */ public function route(ServerRequestInterface $request) : RoutingResponse { $httpMethod = $request->getMethod(); $uri = $request->getUri()->getPath(); $routeInfo = $this->dispatcher->dispatch($httpMethod, $uri); return $this->processDispatcherResult($routeInfo); }
/** * @param $path * * @return array */ public function getRoute($path) { /* Get route information for the url */ $route = $this->router->routeUrl($path, $this->request->getMethod()); if (empty($route['page']) || !file_exists($route['page']['path'] . $route['page']['value'])) { $route = $this->pageNotFound($path); } if (isset($route['model']['file'])) { global $autoloader; $autoloader->addClassMap(["Leap\\Plugins\\" . ucfirst($route['model']['plugin']) . "\\Models\\" . $route['model']['class'] => $route['model']['file']]); } if (isset($route['controller']['file'])) { global $autoloader; $autoloader->addClassMap(["Leap\\Plugins\\" . ucfirst($route['controller']['plugin']) . "\\Controllers\\" . $route['controller']['class'] => $route['controller']['file']]); } /* If the controller class name does not contain the namespace yet, add it */ if (strpos($route['controller']['class'], "\\") === false && isset($route['controller']['plugin'])) { $namespace = getNamespace($route['controller']['plugin'], "controller"); $route['controller']['class'] = $namespace . $route['controller']['class']; } /* If the model name does not contain the namespace yet, add it */ if (strpos($route['model']['class'], "\\") === false && isset($route['model']['plugin'])) { $namespace = getNamespace($route['model']['plugin'], "model"); $route['model']['class'] = $namespace . $route['model']['class']; } return $route; }
protected function findStub(ServerRequestInterface $request) { $path = $request->getUri()->getPath(); $method = $request->getMethod(); $routeInfo = $this->cachedDispatcher->dispatch($method, $path); return $this->stub($routeInfo); }
/** * @param \Psr\Http\Message\ServerRequestInterface $request * @param \Psr\Http\Message\ResponseInterface $response * @param callable|null $next * * @throws \Wiring\Exception\MethodNotAllowedException * @throws \Wiring\Exception\NotFoundException * @return \Psr\Http\Message\ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null) { $routeInfo = $this->fastRoute->dispatch($request->getMethod(), $request->getUri()->getPath()); if ($routeInfo[0] == Dispatcher::FOUND) { // Get request params foreach ($routeInfo[2] as $param => $value) { $request = $request->withAttribute($param, $value); } // Get request with attribute $request = $request->withAttribute($this->attribute, $routeInfo[1]); return $next($request, $response); } if ($routeInfo[0] == Dispatcher::METHOD_NOT_ALLOWED) { // Check has handler if (!$this->container->has(MethodNotAllowedHandlerInterface::class)) { throw new MethodNotAllowedException($request, $response, $routeInfo[1]); } /** @var callable $notAllowedHandler */ $notAllowedHandler = $this->container->get(MethodNotAllowedHandlerInterface::class); return $notAllowedHandler($request, $response, $routeInfo[1]); } // Check has handler if (!$this->container->has(NotFoundHandlerInterface::class)) { throw new NotFoundException($request, $response); } /** @var callable $notFoundHandler */ $notFoundHandler = $this->container->get(NotFoundHandlerInterface::class); return $notFoundHandler($request, $response); }