Go to controller
@param HttpListener $request parameters
@return int Return as success
@throws Server404 Url not found
@throws Server500|\Exception Class or method does not exist or router failed
779787
public function dispatching(HttpListener $request):int
    {
        self::$runtime_parameters = $request;
        $apps = AppTools::registerApps();
        $bapps = AppTools::registerBaseApps();
        $great = false;

        if ($this->isComponentCall($bapps, $request)) {
            return (1);
        }
        
        $values = AppTools::getSimpleAppFormat($apps);
        foreach ($values as $one => $def) {
            if ($great) {
                return (1);
            }
            if ($def["value"]["enabled"] == "no") {
                continue;
            }
            $rt = new Routing($def['name'], $def['value']['prefix']);
            if ($rt->routingRegister() == true) {
                $callback = FrameworkTools::manage($request, $rt->routes());
                if ($callback != null) {
                    (AppConfig::getInstance($def['name']))->checkRequirements();
                    Routing::checkRouteMatchesMethod($callback, strtoupper($request->getMethod()));
                    $method = $callback['method'];
                    $controller = $callback['controller'];
                    $defname = $def['name'];
                    $master = "\\$defname\\Masters\\{$controller}Master";
                    $call = new FrameworkReflection();
                    FEnv::set("app.call", $def['name']);
                    FEnv::set("app.is_components", false);
                    Locale::applyLocale($callback["locale"] ?? null);
                    if (isset($callback['pval'])) {
                        if (isset($callback['r_parameters']) && count($callback['r_parameters']) > 0) {
                            $callback['pval'] = $rt->checkParametersTypeURI(
                                $callback['pval'],
                                $callback['r_parameters'],
                                $callback["routename"]
                            );
                        }
                        $rscall = $call->__named($master, $method, $callback['pval']);
                    } else {
                        $rscall =  $call->__named($master, $method);
                    }
                    if (!($rscall instanceof Renderer)) {
                        $ac_called = FEnv::get("app.activity_called");
                        throw new Server500(new \ArrayObject(
                            array("explain" => "The activity {".$ac_called['method'].
                                "} result in object {".$ac_called['class'].
                                "} must be a Renderer : ".ucfirst(gettype($rscall))." is given", "solution" =>
                            "Return a Renderer instance in this activity")
                        ));
                    }
                    $great = true;
                    new Access200();
                    $rscall->pushRender();
                }
            } else {
                throw new Server500(new \ArrayObject(array("explain" => "Router register failed  ", "solution" =>
                    "Please check your app configuration")));
            }
        }
        if ($great == false) {
            throw new Server404(new \ArrayObject(array("solution" => "Please check your URI")));
        }

        return (1);
    }
1176583
public function callback(HTTPRequest $request)
    {
        $session = $request->getSession();

        if (!$this->validateState($request)) {
            $session->clear('oauth2');
            $this->httpError(400, 'Invalid session state.');
            return null;
        }

        $providerName = $session->get('oauth2.provider');
        /** @var ProviderFactory $providerFactory */
        $providerFactory = Injector::inst()->get(ProviderFactory::class);
        $provider = $providerFactory->getProvider($providerName);
        $returnUrl = $this->getReturnUrl();

        try {
            $accessToken = $provider->getAccessToken('authorization_code', [
                'code' => $request->getVar('code')
            ]);

            $handlers = $this->getHandlersForContext($session->get('oauth2.context'));

            // Run handlers to process the token
            $results = [];
            foreach ($handlers as $handlerConfig) {
                $handler = Injector::inst()->create($handlerConfig['class']);
                $results[] = $handler->handleToken($accessToken, $provider);
            }

            // Handlers may return response objects
            foreach ($results as $result) {
                if ($result instanceof HTTPResponse) {
                    $session->clear('oauth2');

                    // If the response is redirecting to the login page (e.g. on Security::permissionFailure()),
                    // update the BackURL so it doesn't point to /oauth/callback/
                    if ($result->isRedirect()) {
                        $location = $result->getHeader('location');
                        $relativeLocation = Director::makeRelative($location);

                        // If the URL begins Security/login and a BackURL parameter is set...
                        if (
                            strpos($relativeLocation, Security::config()->uninherited('login_url')) === 0
                            && strpos($relativeLocation, 'BackURL') !== -1
                        ) {
                            $session->set('BackURL', $returnUrl);
                            $location = HTTP::setGetVar('BackURL', $returnUrl, $location);
                            $result->addHeader('location', $location);
                        }
                    }
                    
                    return $result;
                }
            }
        } catch (IdentityProviderException $e) {
            /** @var LoggerInterface $logger */
            $logger = Injector::inst()->get(LoggerInterface::class . '.oauth');
            $logger->error('OAuth IdentityProviderException: ' . $e->getMessage());
            $this->httpError(400, 'Invalid access token.');
            return null;
        } catch (Exception $e) {
            /** @var LoggerInterface $logger */
            $logger = Injector::inst()->get(LoggerInterface::class . '.oauth');
            $logger->error('OAuth Exception: ' . $e->getMessage());
            $this->httpError(400, $e->getMessage());
            return null;
        } finally {
            $session->clear('oauth2');
        }

        return $this->redirect($returnUrl);
    }
595600
public function fireOnSendingRequest(HttpRequest $request)
    {
        $event = EnumEvent::REQUEST;
        if (isset($this->listeners[$event]) && is_array($this->listeners[$event]))
        {
            foreach($this->listeners[$event] as $l)
            {
                $ret = $l($request);
                if ($ret instanceof HttpRequest){
                    $request = $ret;
                }
            }
        }
        return $request;
    }
80099
public function sendRequest($request)
    {
        try {
            $result = fputs($this->_socket, $request."\r\n");
        } catch (\Exception $e) {

        }

        if (!$result) {
            throw new \RuntimeException('send failed - connection closed?'.$e->getMessage());
        }
    }
557334
public function doRequest($request)
    {
        $application = $this->getApplication();
        if (!$application instanceof Application && !$application instanceof MicroApplication) {
            throw new RuntimeException('Unsupported application class.');
        }

        $di = $application->getDI();
        /** @var Http\Request $phRequest */
        if ($di->has('request')) {
            $phRequest = $di->get('request');
        }

        if (!$phRequest instanceof Http\RequestInterface) {
            $phRequest = new Http\Request();
        }

        $uri         = $request->getUri() ?: $phRequest->getURI();
        $pathString  = parse_url($uri, PHP_URL_PATH);
        $queryString = parse_url($uri, PHP_URL_QUERY);

        $_SERVER = $request->getServer();
        $_SERVER['REQUEST_METHOD'] = strtoupper($request->getMethod());
        $_SERVER['REQUEST_URI'] = null === $queryString ? $pathString : $pathString . '?' . $queryString;

        $_COOKIE  = $request->getCookies();
        $_FILES   = $this->remapFiles($request->getFiles());
        $_REQUEST = $this->remapRequestParameters($request->getParameters());
        $_POST    = [];
        $_GET     = [];

        if ($_SERVER['REQUEST_METHOD'] == 'GET') {
            $_GET = $_REQUEST;
        } else {
            $_POST = $_REQUEST;
        }

        parse_str($queryString, $output);
        foreach ($output as $k => $v) {
            $_GET[$k] = $v;
        }

        $_GET['_url']            = $pathString;
        $_SERVER['QUERY_STRING'] = http_build_query($_GET);

        Di::reset();
        Di::setDefault($di);

        $di['request'] = Stub::construct($phRequest, [], ['getRawBody' => $request->getContent()]);

        $response = $application->handle();
        if (!$response instanceof Http\ResponseInterface) {
            $response = $application->response;
        }

        $headers = $response->getHeaders();
        $status = (int) $headers->get('Status');

        $headersProperty = new ReflectionProperty($headers, '_headers');
        $headersProperty->setAccessible(true);
        $headers = $headersProperty->getValue($headers);
        if (!is_array($headers)) {
            $headers = [];
        }

        $cookiesProperty = new ReflectionProperty($di['cookies'], '_cookies');
        $cookiesProperty->setAccessible(true);
        $cookies = $cookiesProperty->getValue($di['cookies']);
        if (is_array($cookies)) {
            $restoredProperty = new ReflectionProperty('\Phalcon\Http\Cookie', '_restored');
            $restoredProperty->setAccessible(true);
            $valueProperty = new ReflectionProperty('\Phalcon\Http\Cookie', '_value');
            $valueProperty->setAccessible(true);
            foreach ($cookies as $name => $cookie) {
                if (!$restoredProperty->getValue($cookie)) {
                    $clientCookie = new Cookie(
                        $name,
                        $valueProperty->getValue($cookie),
                        $cookie->getExpiration(),
                        $cookie->getPath(),
                        $cookie->getDomain(),
                        $cookie->getSecure(),
                        $cookie->getHttpOnly()
                    );
                    $headers['Set-Cookie'][] = (string)$clientCookie;
                }
            }
        }

        return new Response(
            $response->getContent() ?: '',
            $status ? $status : 200,
            $headers
        );
    }
1013706
public function dispatch(Request $request) {

        $uri = $request->uri();
        $method = $request->method();

        if (in_array($uri, self::$routes)) {
            if (self::$methods[$uri] == $method || self::$methods[$uri] == 'ANY') {
                if (is_object(self::$callbacks[$uri])) {
                     call_user_func(self::$callbacks[$uri]);
                } else {
                    $s = explode('@', self::$callbacks[$uri]);
                    call_user_func(array((new $s[0]), $s[1]));
                }
            }
        } else {
            header($_SERVER['SERVER_PROTOCOL']." 404 Not Found");
            echo '404';
        }
    }
204472
public function doRequest($request)
    {
        $inputStream = fopen('php://memory', 'r+');
        $content = $request->getContent();
        if ($content !== null) {
            fwrite($inputStream, $content);
            rewind($inputStream);
        }

        $queryParams = [];
        $postParams = [];
        $queryString = parse_url($request->getUri(), PHP_URL_QUERY);
        if ($queryString != '') {
            parse_str($queryString, $queryParams);
        }
        if ($request->getMethod() !== 'GET') {
            $postParams = $request->getParameters();
        }

        $serverParams = $request->getServer();
        if (!isset($serverParams['SCRIPT_NAME'])) {
            //required by WhoopsErrorHandler
            $serverParams['SCRIPT_NAME'] = 'Codeception';
        }
        
        $cookies = $request->getCookies();
        $headers = $this->extractHeaders($request);

        //set cookie header because dflydev/fig-cookies reads cookies from header
        if (!empty($cookies)) {
            $headers['cookie'] = implode(';', array_map(function ($key, $value) {
                return "$key=$value";
            }, array_keys($cookies), $cookies));
        }

        $zendRequest = new ServerRequest(
            $serverParams,
            $this->convertFiles($request->getFiles()),
            $request->getUri(),
            $request->getMethod(),
            $inputStream,
            $headers,
            $cookies,
            $queryParams,
            $postParams
        );

        $this->request = $zendRequest;

        $cwd = getcwd();
        chdir(codecept_root_dir());

        if ($this->config['recreateApplicationBetweenRequests'] === true || $this->application === null) {
            $application = $this->initApplication();
        } else {
            $application = $this->application;
        }

        if (method_exists($application, 'handle')) {
            //Zend Expressive v3
            $response = $application->handle($zendRequest);
        } else {
            //Older versions
            $application->run($zendRequest);
            $response = $this->responseCollector->getResponse();
            $this->responseCollector->clearResponse();
        }

        chdir($cwd);

        return new Response(
            (string)$response->getBody(),
            $response->getStatusCode(),
            $response->getHeaders()
        );
    }
1256637
public function execute($request)
	{
		$url = $request->getUrl();
		$path = $url->getPath();

		$match = $this->_router->lookup($path);
		return $this->_controllerFor($match->getName())->execute(
			new RoutedRequest(
				$this->_filterChain->filter($request),
					$match, $this->_router));
	}
319265
public function route($request = NULL)
    {
        $matchedResource = NULL;
        if (!$request) {
            $request = new Request();
        }
        foreach ($this->resources as $className => $resourceMetadata) {
            foreach ($resourceMetadata->getUri() as $index => $uri) {
                $uriRegex = '|^'.$uri.'$|';
                if (
                    ($matchedResource == NULL || $matchedResource[0]->getPriority() < $resourceMetadata->getPriority())
                &&
                    preg_match($uriRegex, $request->getUri(), $params)
                ) {
                    array_shift($params);
                    $uriParams = $resourceMetadata->getUriParams($index);
                    if ($uriParams) { // has params within URI
                        foreach ($uriParams as $key => $name) {
                            $params[$name] = $params[$key];
                        }
                    }
                    $matchedResource = array($resourceMetadata, $params);
                }
            }
        }
        if ($matchedResource) {
            $request->setParams($matchedResource[1]);

            return $matchedResource[0];
        } else {
            throw new NotFoundException(sprintf('Resource matching URI "%s" not found', $request->uri));
        }
    }
424130
public function handleRequest($request)
    {
        list ($route, $params) = $request->resolve();
        $this->requestedRoute = $route;
        $result = $this->runAction($route, $params);
        if ($result instanceof Response) {
            return $result;
        } else {
            $response = $this->getResponse();
            $response->exitStatus = $result;

            return $response;
        }
    }
123997
public function handle(Request $request): Response
    {
        try {
            $matcher = $this->getUrlMatcher($request);

            $parameters = $matcher->match($request->getPathInfo());

            if (empty($parameters['_controller'])) {
                throw new InvalidRouteException('Route requires a _controller callable');
            }

            if (!\is_callable($parameters['_controller'])) {
                throw new InvalidRouteException('_controller must be a callable');
            }

            $callback = $parameters['_controller'];

            $result = call_user_func_array($callback, $this->getControllerParameters($request, $parameters));

            if (!$result instanceof Response) {
                throw new InvalidResponseException('Response must be an instance of \Symfony\Component\HttpFoundation\Response');
            }
        } catch (\Exception $e) {
            $result = $this->handleException($request, $e);
        }

        return $result;
    }
587968
protected function handle(Request $request)
    {
        try {
            list($routeInformation, $parameters) = $this->findRoute($request);

            return (new Pipeline($this->container))
                ->through($routeInformation['middlewares'])
                ->send($request)
                ->then(function (Request $request) use ($routeInformation, $parameters) {
                    if ($routeInformation['action'] instanceof Closure) {
                        return call_user_func_array($routeInformation['action'], $parameters);
                    }

                    list($controller, $action) = $routeInformation['action'];
                    $controllerInstance = new $controller;

                    if ($controllerInstance instanceof KeeperBaseController) {
                        $controllerInstance->setContainer($this->container);
                        $controllerInstance->setRequest($request);
                    }

                    return call_user_func_array([$controllerInstance, $action], $parameters);
                });

        } catch (Throwable $exception) {
            if ($this->exceptionHandler) {
                return $this->exceptionHandler->handle($exception, $request);
            }

            return new Response((string)$exception, 500);
        }
    }
891752
protected function httpTransport($request)
    {

        try {
            $response = $this->client->send($request);
            $results = json_decode($response->getBody());
            return $results;
        } catch (RequestException $e) {
            Log::error(Psr7\str($e->getRequest()));
            if ($e->hasResponse()) {
                Log::error(Psr7\str($e->getResponse()));
            }
        }
    }
249953
private function handle(Request $request) : Response
    {
        $router = $this->getInstance(Router::class);

        if ($router->match($request->getPathInfo(), $request->getMethod())) { // A match has been found
            /** @var Route $match */
            $match = $router->getMatch();

            // Check if the handler is a closure or not
            $handler = $match->getHandler();

            if (is_object($handler) && $handler instanceof \Closure) {
                try {
                    $content = $this->resolveClosure($handler);
                } catch (\Exception $e) {
                    if (DEVELOPMENT) {
                        showPlainError('Something went wrong while resolving a closure, details below:', false);
                        pr($e);
                        exit;
                    }

                    return $this->respond(500);
                }
            } else {
                $controller = substr($handler, 0, stripos($handler, '.'));
                $method = substr($handler, (stripos($handler, '.') + 1));

                try {
                    $instance = $this->getInstance($controller);
                    if (method_exists($instance, 'setCrispySystem')) {
                        $instance->setCrispySystem($this);
                    }
                    $content = $this->resolveMethod($instance, $method, $match->getParameters());
                } catch (\Exception $e) {
                    if (DEVELOPMENT) {
                        showPlainError('Something went wrong while resolving a controller, details below:', false);
                        pr($e);
                        exit;
                    }

                    return $this->respond(500);
                }
            }

            return $this->respond(200, $content);
        }

        // No match found
        return $this->respond(404);
    }
291675
protected function handleRouting(HttpRequest $request)
    {
        $this->router = $this->serviceManager->get('Router');
        $this->router->warmUp($this->getCacheDir());

        try {
            // Lets load up our router and match the appropriate route
            $parameters = $this->router->matchRequest($request);
            if (!empty($parameters)) {
                if (null !== $this->logger) {
                    $this->logger->info(sprintf('Matched route "%s" (parameters: %s)', $parameters['_route'], $this->router->parametersToString($parameters)));
                }
            }
        } catch (ResourceNotFoundException $e) {
            $routeUri = $this->router->generate('Framework_404');
            $parameters = $this->router->matchRequest($request::create($routeUri));
        } catch (\Exception $e) {
            throw $e;
        }

        $parameters['_route_params'] = $parameters;

        return $parameters;
    }
1337559
public function dispatch(ServerRequest $request, array $parameters = [])
    {
        $matchedRoute = $this->matcher->matchRequest($request);
        if ($matchedRoute !== false) {
            return $this->dispatcher->dispatchRoute($matchedRoute, $parameters);
        }

        return $this->dispatcher->dispatchNotFound();
    }
1201574
public function execute($request)
    {
        RequestNotSupportedException::assertSupports($this, $request);

        $details = ArrayObject::ensureArrayObject($request->getModel());

        if (isset($details['RtnCode']) === false) {
            $request->markNew();

            return;
        }

        if ($details['RtnCode'] === '2') {
            $request->markPending();

            return;
        }

        if ($details['RtnCode'] === '1') {
            if (isset($details['Action']) === true) {
                switch ($details['Action']) {
                    case 'C':
                        $request->markCaptured();
                        break;
                    case 'R':
                        $request->markRefunded();
                        break;
                    case 'E':
                    case 'N':
                        $request->markCanceled();
                        break;
                }

                return;
            } else {
                $request->markCaptured();

                return;
            }
        }

        $request->markFailed();
    }