Try to match the current uri with all routes


@param \React\Http\Request     $request
@param \React\Restify\Response $response

@throws \RuntimeException
@return Void
435925
private function matchRoutes(Request $request, Response $response)
    {
        $stack  = [];
        $path   = $request->httpRequest->getPath();
        $method = $request->httpRequest->getMethod();

        foreach ($this->routes as $route) {
            if (!$route->match($path, $method)) {
                continue;
            }

            $methodArgs = $route->getArgs($path);
            $request->setData($methodArgs);

            $route->on('error', function (...$args) {
                $this->emit('error', $args);
            });

            $stack[] = function (...$params) use ($route) {
                $route->run(...$params);
            };
        }

        if (count($stack) == 0) {
            $this->emit('NotFound', array($request, $response));
            return;
        }

        $this->runStack($stack, $request, $response);
    }
249343
public function handle(ServerRequestInterface $request, Response $response)
    {
        $server = $request->getServerParams();
        $server['REQUEST_METHOD'] = $request->getMethod();
        $server['REQUEST_URI'] = $request->getUri()->getPath();
        $globals = [
            '_GET' => $request->getQueryParams(),
            '_POST' => $request->getParsedBody()
        ];
        $req = $this->router->match($globals, $server);
        $resourceObject = $this->resource->{$req->method}->uri($req->path)->withQuery($req->query)->eager->request();
        $response = $this->toPsr7Response($response, $resourceObject);

        return $response;
    }
470
protected function getErrorRoute(ServerRequestInterface $request, ResponseInterface $response)
    {
        if (
            interface_exists('Jasny\HttpMessage\GlobalEnvironmentInterface') &&
            $request instanceof GlobalEnvironmentInterface
        ) {
            $request = $request->withoutGlobalEnvironment();
        }
        
        $status = $response->getStatusCode();
        
        $errorUri = $request->getUri()
            ->withPath($status)
            ->withQuery(null)
            ->withFragment(null);
        
        return $this->router->getRoutes()->getRoute($request->withUri($errorUri));
    }
338544
public function handle(
        ServerRequestInterface $request, ResponseInterface $response
    )
    {
        $path = array_key_exists(self::QUERY_PARAM, $request->getQueryParams())
            ? $request->getQueryParams()[self::QUERY_PARAM]
            : '';
        $uri = Uri::create($request->getUri());
        $queryString = ltrim(
            str_replace(
                self::QUERY_PARAM."={$path}",
                '',
                $uri->getQuery()
            ),
            '&'
        );
        $uri = $uri->withPath(str_replace('//', '/', "/$path"))
            ->withQuery($queryString);
        /** @var ServerRequestInterface $request */
        $request = $request->withUri($uri);
        return $this->executeNext($request, $response);
    }
135372
public function doFilter(Request $request, Response $response)
    {
        if ((int) $request->get('error') === 1) {
            return
                $response
                    ->withStatusCode(404)
                    ->write('error')
            ;
        }
    }
739253
public function modifyResponse(Request $request, Response $response)
    {
        if ($this->isCollect() === false) {
            return;
        }

        // if ($this -> created) {
        //     return;
        // }

        $app = $this->app;


        if ($app->runningInConsole() || !$this->isEnabled() || $this->isMyselfRequest()) {
            return $response;
        }

        // Show the Http Response Exception, when available
        if (isset($response->exception)) {
            $this->addThrowable($response->exception);
        }

        /**---------------------------------------------------------
         *   Display config settings
         *---------------------------------------------------------*/

        if ($this->shouldCollect('config', false)) {
            try {
                $configCollector = new ConfigCollector();
                $configCollector->setData($app['config']->all());
                $this->addCollector($configCollector);
            } catch (\Exception $e) {
                $this->addThrowable(
                    new Exception(
                        'Cannot add ConfigCollector to SongshenzongLog: ' . $e->getMessage(),
                        $e->getCode(),
                        $e
                    )
                );
            }
        }


        if ($this->app->bound(SessionManager::class)) {

            /** @var \Illuminate\Session\SessionManager $sessionManager */
            $sessionManager = $app->make(SessionManager::class);
            $httpDriver     = new SymfonyHttpDriver($sessionManager, $response);
            $this->setHttpDriver($httpDriver);

            if ($this->shouldCollect('session') && !$this->hasCollector('session')) {
                try {
                    $this->addCollector(new SessionCollector($sessionManager));
                } catch (\Exception $e) {
                    $this->addThrowable(
                        new Exception(
                            'Cannot add SessionCollector to SongshenzongLog: ' . $e->getMessage(),
                            $e->getCode(),
                            $e
                        )
                    );
                }
            }
        } else {
            $sessionManager = null;
        }


        /**---------------------------------------------------------
         *   Only one can be enabled.
         *---------------------------------------------------------*/
        if ($this->shouldCollect('request', true) && !$this->hasCollector('request')) {
            try {
                $this->addCollector(new RequestCollector($request, $response, $sessionManager));
            } catch (\Exception $e) {
                $this->addThrowable(
                    new Exception(
                        'Cannot add RequestCollector to SongshenzongLog: ' . $e->getMessage(),
                        $e->getCode(),
                        $e
                    )
                );
            }
        }


        /**---------------------------------------------------------
         *   Just collect + store data
         *---------------------------------------------------------*/
        try {
            $this->collect();
        } catch (\Exception $e) {
            $app['log']->error('Songshenzong exception: ' . $e->getMessage());
        }


        return $response;
    }
201152
public function dispatch(Request $request, Response $response) {
		$module = ucfirst($request->module);
		$controller = ucfirst($request->controller);
		$action = ucfirst($request->action);
		$response->setTemplate($controller . '/' . $action);
		$response->setTemplatePath(APP_PATH . 'Module/' . $module . '/View/');
		if (!empty($request->extension)) {
			$response->mimeType($request->extension);
		}
		try {
			$code = self::isValid($module, $controller, $action);
			if ($code === self::ROUTE_VALID) {
				$className = EntryUtil::controller($module, $controller);
				$clazz = Container::getInstance()->get($className);
				$actionName = $action . 'Action';
				$result = $clazz->$actionName($request, $response);
				if ($result !== null) {
					$response->result = $result;
				}
			} else {
				// Not found
				$request->status = $code;
			}
		} catch (\Throwable $e) {
			$request->status = $e;
		}
		$this->executeInterceptor('after', $request, $response);
		$request->end();
		$response->end();
		unset($request, $response);
	}
1176794
protected function call(\LibX\Net\Rest\Request $request, \LibX\Net\Rest\Response $response)
    {
      // Make the call!
      $this->client->execute($request, $response);

      //print_r($request);
      //print_r($response);

      // Get info
      $info = $response->getInfo();

      // Get JSON response
      $json = $response->getData();

      // Decode JSON
      $data = json_decode($json);

      return $data;
    }
1032561
protected function addJquery(Request $request, Response $response)
    {
        if (!$this->config->get('general/add_jquery', false) &&
            !$this->config->get('theme/add_jquery', false)) {
            return;
        }

        // Check zone to skip expensive regex
        if (Zone::isFrontend($request) === false) {
            return;
        }

        $html = $response->getContent();
        $regex = '/<script(.*)jquery(-latest|-[0-9\.]*)?(\.min)?\.js/';
        if (preg_match($regex, $html)) {
            return;
        }

        $this->add(
            (new JavaScript('js/jquery-2.2.4.min.js', 'bolt'))
                ->setLocation(Target::BEFORE_JS)
        );
    }
32518
protected function _processRoute(Context $c, $handler, &$response)
  {
    if($handler === null)
    {
      throw new \RuntimeException(ConditionHandler::ERROR_NO_HANDLER, 500);
    }
    throw new \RuntimeException(self::ERROR_NO_ROUTE, 404);
  }
726538
public function decorateResponse(Request $request, Response $response)
    {
        if ($request->headers->has(self::ORIGIN_REQUEST_HEADER)) {
            $request->headers->set('referer', $request->headers->get(self::ORIGIN_REQUEST_HEADER));
        }

        $this->setTurbolinksLocationHeaderFromSession($request, $response);

        if ($response->isRedirect() && $response->headers->has(self::ORIGIN_RESPONSE_HEADER)) {
            $this->redirectTo($request, $response);
        }

        $this->modifyStatusCode($request, $response);
    }
970046
public function run(
        ServerRequestInterface $request,
        ResponseInterface $response
    )
    {

        if ($this->running)
            throw new \RuntimeException(
                "Failed to run middleware queue: Queue is already running"
            );

        $this->running = true;
        $this->save();

        $next = function (
            ServerRequestInterface $request,
            ResponseInterface $response
        ) use (&$next) {

            if (count($this->middleware) > 0) {

                $middleware = array_shift($this->middleware);
                $response = call_user_func($middleware, $request, $response, $next);

                if (!($response instanceof ResponseInterface))
                    throw new \RuntimeException(
                        "Failed to run middleware: Middleware didn't return ".
                        "a valid ".ResponseInterface::class." object"
                    );
            }

            $this->running = false;
            $this->restore();
            return $response;
        };

        return $next($request, $response);
    }
1101623
public function terminate($request, $response)
    {
        $routeMiddlewares = $this->gatherRouteMiddlewares($request);
        foreach (array_merge($routeMiddlewares, $this->middleware) as $middleware) {
            $instance = $this->app->make($middleware);
            if ($instance instanceof TerminableMiddleware) {
                $instance->terminate($request, $response);
            }
        }
        $this->app->terminate();
    }
880663
public function startAuthentication(Request $request, Response $response)
    {
        if (isset($this->options['routeValues'])) {
            $routeValues = $this->options['routeValues'];
            if (!is_array($routeValues)) {
                throw new MissingConfigurationException(sprintf('The configuration for the WebRedirect authentication entry point is incorrect. "routeValues" must be an array, got "%s".', gettype($routeValues)), 1345040415);
            }
            $actionRequest = new ActionRequest($request);
            $this->uriBuilder->setRequest($actionRequest);

            $actionName = $this->extractRouteValue($routeValues, '@action');
            $controllerName = $this->extractRouteValue($routeValues, '@controller');
            $packageKey = $this->extractRouteValue($routeValues, '@package');
            $subPackageKey = $this->extractRouteValue($routeValues, '@subpackage');
            $uri = $this->uriBuilder->setCreateAbsoluteUri(true)->uriFor($actionName, $routeValues, $controllerName, $packageKey, $subPackageKey);
        } elseif (isset($this->options['uri'])) {
            $uri = strpos($this->options['uri'], '://') !== false ? $this->options['uri'] : $request->getBaseUri() . $this->options['uri'];
        } else {
            throw new MissingConfigurationException('The configuration for the WebRedirect authentication entry point is incorrect or missing. You need to specify either the target "uri" or "routeValues".', 1237282583);
        }

        $response->setContent(sprintf('<html><head><meta http-equiv="refresh" content="0;url=%s"/></head></html>', htmlentities($uri, ENT_QUOTES, 'utf-8')));
        $response->setStatus(303);
        $response->setHeader('Location', $uri);
    }
405298
private void processRedirectResponse(Response response) throws RuntimeException, JSONException, MalformedURLException {
        // a valid redirect response must contain the Location header.
        ResponseImpl responseImpl = (ResponseImpl)response;
        List<String> locationHeaders = responseImpl.getHeader(LOCATION_HEADER_NAME);

        String location = (locationHeaders != null && locationHeaders.size() > 0) ? locationHeaders.get(0) : null;

        if (location == null) {
            throw new RuntimeException("Redirect response does not contain 'Location' header.");
        }

        // the redirect location url should contain "wl_result" value in query parameters.
        URL url = new URL(location);
        String query = url.getQuery();

        if (query.contains(WL_RESULT)) {
            String result = Utils.getParameterValueFromQuery(query, WL_RESULT);
            JSONObject jsonResult = new JSONObject(result);

            // process failures if any
            JSONObject jsonFailures = jsonResult.optJSONObject(AUTH_FAILURE_VALUE_NAME);

            if (jsonFailures != null) {
                processFailures(jsonFailures);
                listener.onFailure(response, null, null);
                return;
            }

            // process successes if any
            JSONObject jsonSuccesses = jsonResult.optJSONObject(AUTH_SUCCESS_VALUE_NAME);

            if (jsonSuccesses != null) {
                processSuccesses(jsonSuccesses);
            }
        }

        // the rest is handles by the caller
        listener.onSuccess(response);
    }
316197
public function run(ServerRequestInterface $request, ResponseInterface $response)
    {
        $route = $request->getAttribute('route');
        $callback = !empty($route->fn) ? $route->fn : null;

        if (!is_callable($callback)) {
            trigger_error("'fn' property of route shoud be a callable", E_USER_NOTICE);
            return $this->notFound($request, $response);
        }

        return $callback($request, $response);
    }
76965
public function handle(
        ServerRequestInterface $request, ResponseInterface $response
    )
    {
        $route = $this->getMatcher()->match($request);
        $request = $request->withAttribute('route', $route);
        return $this->executeNext($request, $response);
    }