Find Route

Matches any routes that may exists in config/routes.php file of specific module
against the URI to determine current route and current module

@return void
@throws RouteException When repetitive route was found
505253
public function findRoute() {
        if (isset($_SERVER['REQUEST_URI'])) {

            $matched_uris = array();
            $routes_group = array();
            $request_uri = preg_replace('/[?]/', '', $_SERVER['REQUEST_URI']);

            foreach ($this->routes as $route) {
                if (trim(urldecode($request_uri), '/') == $route['uri']) {
                    $matched_uris[] = $route['uri'];
                    $route['args'] = [];
                    array_push($routes_group, $route);
                }
            }

            if (!$matched_uris) {
                foreach ($this->routes as $route) {
                    $route['uri'] = str_replace('/', '\/', $route['uri']);
                    $route['uri'] = preg_replace_callback('/\[(:num)(:([0-9]+))*\](\?)?/', array($this, 'findPattern'), $route['uri']);
                    $route['uri'] = preg_replace_callback('/\[(:alpha)(:([0-9]+))*\](\?)?/', array($this, 'findPattern'), $route['uri']);
                    $route['uri'] = preg_replace_callback('/\[(:any)(:([0-9]+))*\](\?)?/', array($this, 'findPattern'), $route['uri']);

                    $request_uri = parse_url($_SERVER['REQUEST_URI']);

                    preg_match("/^\/" . $route['uri'] . "$/u", urldecode($request_uri['path']), $matches);

                    if ($matches) {
                        array_push($matched_uris, $matches[0]);
                        array_shift($matches);

                        $route['args'] = $matches;
                        array_push($routes_group, $route);
                    }
                }
            }

            if (!$matched_uris) {
                self::$currentRoute = NULL;
                HookManager::call('pageNotFound');
            }

            if ($matched_uris) {
                if (count($routes_group) > 1) {

                    self::$currentModule = $routes_group[0]['module'];

                    for ($i = 0; $i < count($routes_group) - 1; $i++) {
                        for ($j = $i + 1; $j < count($routes_group); $j++) {
                            if ($routes_group[$i]['method'] == $routes_group[$j]['method']) {
                                self::$currentRoute = NULL;
                                throw new RouteException(_message(ExceptionMessages::REPETITIVE_ROUTE_SAME_METHOD, $routes_group[$j]['method']));
                                break 2;
                            }
                            if ($routes_group[$i]['module'] != $routes_group[$j]['module']) {
                                self::$currentRoute = NULL;
                                throw new RouteException(ExceptionMessages::REPETITIVE_ROUTE_DIFFERENT_MODULES);
                                break 2;
                            }
                        }
                    }

                    foreach ($routes_group as $route) {
                        if (strpos($route['method'], '|') !== false) {
                            if (in_array($_SERVER['REQUEST_METHOD'], explode('|', $route['method']))) {
                                self::$currentRoute = $route;
                                break;
                            }
                        } else if ($_SERVER['REQUEST_METHOD'] == $route['method']) {
                            self::$currentRoute = $route;
                            break;
                        }
                    }
                } else {
                    self::$currentModule = $routes_group[0]['module'];
                    self::$currentRoute = $routes_group[0];
                }
            }

            HookManager::call('handleHeaders');

            if ($_SERVER['REQUEST_METHOD'] != 'OPTIONS') {
                $this->checkMethod();
            }
        }
    }
1290472
public function filter()
    {
        $requestUrl = $this->application->request->getQuery('url', '/');
        $requestMethod = $this->application->request->getMethod();
        $event = new Route([
            'router' => $this,
            'application' => $this->application,
            'request' => $this->application->request
        ]);
        $this->_application->getEventManager()
            ->trigger(Route::BEFORE_ROUTE, $this, $event);
        $options = $this->getService()->match($requestUrl, $requestMethod);
        if ($options == false) {
            throw new RouterException(
                "No route was found for the given request URL."
            );
        }
        // Route match, add the extension
        $cfg = $this->application->getContainer()->get('configuration');


        $routerInfo = new RouteInfo($options);
        $routerInfo->setConfiguration($cfg)
            ->setTarget($options['target']);

        $extension = $this->application->getRequest()
            ->getQuery('extension');

        if (strlen($extension) < 1) {
            $extension = $cfg->get('router.extension', 'html');
        }
        $routerInfo->extension = $extension;

        $event->routeInfo = $routerInfo;
        $this->_application->getEventManager()
            ->trigger(Route::AFTER_ROUTE, $this, $event);
        return $event->routeInfo;
    }
692429
public function run( string $routesFilename=''  )
  {
    #
    # Load the Routes
    #
    if ( empty($routesFilename) ) {
      $routesFilename = $this->getBasePath().'/app/Config/routes.json';
    }
    $this->loadRoutes( $routesFilename );


    # Get Method and URI
    $httpMethod = $this->getRequest()->getMethod();
    $path = $this->getRequest()->getUri()->getPath();
    $routeInfo = null;

    # Find route match in groups
    foreach ($this->getRouteGroups() as $routeGroup)
    {
      # Match the METHOD and URI to the routes in this group
      $routeInfo = $routeGroup->matchRoute($httpMethod,$path);

      if ( count($routeInfo)>0 ) {
        $beforeResult = true; // assume all before handlers succeed
        $routeResult = false;
        $afterResult = true; // assume all after handlers succeed

        # Debug log
        $this->getLogger()->debug('Route matched ',['handler'=>$routeInfo['handler']]);

        #
        # Run the Common AND Groups Before Middlewares (ServerRequestInterface)
        #
        $beforeMiddleware = array_merge($this->beforeMiddleware, $routeGroup->getBeforeMiddleware());

        foreach ($beforeMiddleware as $middleware)
        {
          if (class_exists($middleware) ) {
            $beforeHandler = new $middleware($routeInfo['args']);

            # Debug log
            $this->getLogger()->debug('Running Before middleware',['rid'=>app('requestId'),'middleware'=>$middleware]);

            if (!$beforeHandler->handle($routeInfo['args'])) {
              # Record outcome
              $beforeResult = false;
              # Stop processing more middleware
              break;
            }
          } else {
            # Log
            $this->getLogger()->warning('Before Middleware not found',['rid'=>app('requestId'),'middleware'=>$middleware]);
          }
        }

        #
        # Create & Run the Handler Class - If the Before Middlewares where ok!
        #
        if ($beforeResult) {
          # Extract class & method
          $arr = explode('@',$routeInfo['handler']);
          $handlerClass = $arr[0];
          $handlerMethod = ($arr[1] ?? 'handle');

          # Check existance of handler class
          if (class_exists($handlerClass))
          {
            # Create the class
            $routeHandler = new $handlerClass( $routeInfo['args'] );

            # Check method existance
            if ($routeHandler && method_exists($routeHandler,'initialize') && method_exists($routeHandler,$handlerMethod))
            {
              # Debug log
              $this->getLogger()->debug('Running controller->initialize()',['rid'=>app('requestId'),'controller'=>$handlerClass]);

              # Initialize
              $routeHandler->initialize($routeInfo['args']);

              # Debug log
              $this->getLogger()->debug('Running controller->handle()',['rid'=>app('requestId'),'method'=>$handlerMethod]);

              # Run handler
              $routeResult = $routeHandler->$handlerMethod($routeInfo['args']);
            } else {
              # Log
              $this->getLogger()->error('Method not found in controller ',['rid'=>app('requestId'),'controller'=>$handlerClass,'method'=>$handlerMethod]);
            }
          } else {
            # Debug log
            $this->getLogger()->debug('Controller not found ',['rid'=>app('requestId'),'controller'=>$handlerClass]);
          }
        }

        #
        # Run the After Middlewares (ServerRequestInterface)
        #
        $afterMiddleware = array_merge($this->afterMiddleware,$routeGroup->getAfterMiddleware());
        foreach ($afterMiddleware as $middleware)
        {
          if (class_exists($middleware) ) {
            $afterHandler = new $middleware($routeInfo['args']);

            # Debug log
            $this->getLogger()->debug('Running After middleware',['rid'=>app('requestId'),'middleware'=>$middleware]);

            if (!$afterHandler->handle($routeInfo['args'])) {
              return false;
            }
          } else {
            # Log
            $this->getLogger()->warning('After Middleware not found',['rid'=>app('requestId'),'middleware'=>$middleware]);
          }
        }

        return $routeResult;

      } else {
        # No route matched the URI in this group, we'll look in the next group or exit the foreach()
        $routeInfo = null;
      }

    }

    # Output debug info
    if (is_null($routeInfo)) {
      # Debug log
      $this->getLogger()->debug('No route matched request',['rid'=>app('requestId'),'method'=>$httpMethod,'path'=>$path]);
    }

    return false; // default response
  }
1074805
public function matchRequest(Request $request)
    {
        $requestUrl = $request->getRouteURL();
        $requestMethod = $request->getMethod();

        if (empty($this->routes)) {
            $routeFile = basePath('app/Routes/web.php');
            if (file_exists($routeFile)) {
                /** @noinspection PhpIncludeInspection */
                require_once $routeFile;
            } else {
                throw new Exception("Route definition file $routeFile does not exist");
            }
        }

        $params = array();
        foreach ($this->routes as $handler) {
            $methods = $handler->getHttpMethod();
            $route = $handler->getRouteURI();

            $method_match = (stripos($methods, $requestMethod) !== false);

            // Method did not match, continue to next route.
            if (!$method_match) {
                continue;
            }

            if ($route === '*') {
                // * wildcard (matches all)
                $match = true;
            } elseif (isset($route[0]) && $route[0] === '@') {
                // @ regex delimiter
                $pattern = '`' . substr($route, 1) . '`u';
                $match = preg_match($pattern, $requestUrl, $params) === 1;
            } elseif (($position = strpos($route, '[')) === false) {
                // No params in url, do string comparison
                $match = strcmp($requestUrl, $route) === 0;
            } else {
                // Compare longest non-param string with url
                if (strncmp($requestUrl, $route, $position) !== 0) {
                    continue;
                }
                $regex = $this->compileRoute($route);
                $match = preg_match($regex, $requestUrl, $params) === 1;
            }

            if ($match) {
                if ($params) {
                    foreach ($params as $key => $value) {
                        if (is_numeric($key)) {
                            unset($params[$key]);
                        }
                    }
                }
                $handler->setParameters($params);
                $handler->lock();
                $request->setRoute($handler);

                return $handler;
            }
        }

        return false;
    }
1003352
public function routing(): void
    {
        $routingClass = $this->configs['routing'];
        try {
            $this->module('routing', new $routingClass());
        } catch (CoreException $e) {
            throw new CoreException($e->getMessage());
        }
    }
606532
public function getCurrentRouteMatch() {
    if (empty($this->currentRouteMatch)) {
      $this->currentRouteMatch = \Drupal::service('current_route_match');
    }
    return $this->currentRouteMatch;
  }
282509
private function matchExact(): bool
    {
        foreach ($this->routesExact as $route) {
            if ($this->uri === $route['u']) { // compare the current URI array to this route URI array
                $this->control = $route['c']; // set control or this exact match

                return true; // exact match found
            }
        }

        return false; // exact match not found
    }
817770
protected function matchRoute()/*# : bool */
    {
        foreach ($this->getCollectors() as $coll) {
            if ($coll->matchRoute($this->result)) {
                return true;
            }
        }
        return false;
    }
987958
public static function find () {
		//No routes are avaible
		if (count(Router::$routes) == 0)
			return null;

			echo Router::$queryString;
		if (Router::$queryString == "") {
			Router::$target = Router::$routes["/"];
		}
		else if (isset(Router::$routes["/".Router::$queryString])) {
		}

		//Build so it can runs some special functions
		Router::$built = true;
	}
1240540
public function match()
	{
		$requestUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
		$method = $this->getRequestMethod();
		$uri = $this->getCurrentUri();

		// Loop all routes
		foreach ($this->routes[$method] as $route) {
			// we have a match!
			if (preg_match_all('#^' . $route['pattern'] . '$#', $uri, $matches, PREG_OFFSET_CAPTURE)) {
				die("route matched");
			}
		}
		die("no route matched");
	}
361682
private function specificRouteRestrictionExists()
    {
        $requestMethod = isset($_POST['_method']) ? $_POST['_method'] : $_SERVER['REQUEST_METHOD'];
        
        $routes = app('router')->getRoutes()->match(app('request')->create($_SERVER['REQUEST_URI'], $requestMethod));


        if (!$routes) {
            throw new Exception('Error determining current route.');
        }

        if (get_class($routes) != \Illuminate\Routing\Route::class && count($routes) != 1) {
            $routes = $routes->first();
        }
        
        foreach($routes->middleware() as $routeMiddleware) {
            $routeMiddlewareParts = explode(':', $routeMiddleware);
            if ($routeMiddlewareParts[0]=='routeRestrictor') {
                return true;
            }
        }

        return false;
    }
545481
public function seeCurrentRouteIs($routeName, array $params = [])
    {
        $router = $this->grabService('router');
        if (!$router->getRouteCollection()->get($routeName)) {
            $this->fail(sprintf('Route with name "%s" does not exists.', $routeName));
        }

        $uri = explode('?', $this->grabFromCurrentUrl())[0];
        try {
            $match = $router->match($uri);
        } catch (\Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
            $this->fail(sprintf('The "%s" url does not match with any route', $uri));
        }
        $expected = array_merge(['_route' => $routeName], $params);
        $intersection = array_intersect_assoc($expected, $match);

        $this->assertEquals($expected, $intersection);
    }
67730
private function FindRouteMatch() {
        $route = new Route();
        $route->setDefaultUrl(Config::Init($this->app)->Get(\Puzzlout\Framework\Enums\AppSettingKeys::DefaultUrl));
        $this->getRoute($route, $this->url);
        return $route;
    }
595544
protected function matchCache()
    {
        // check if we can find a match in cache
        // check if a cache exists
        if ($this->cache instanceof Cache) {
            // check if we have any routes saved in cache
            if ($cachedRoutes = $this->cache->get('routeMiddlewareRoutes')) {
                // check if the requested uri can be found in the cache
                if (isset($cachedRoutes[$this->requestUri])) {

                    // check if endpoint class exists
                    if (!$this->endpointExists($cachedRoutes[$this->requestUri]['matchedEndpoint'])) {
                        throw new NotFound();
                    }

                    if (!$this->endpointMethodExists(
                        $cachedRoutes[$this->requestUri]['matchedEndpoint'],
                        $this->requestMethod
                    )) {
                        // route found but method can't be found
                        throw new MethodNotAllowed();
                    }

                    // match found, set info
                    $this->matchedRoute = $cachedRoutes[$this->requestUri]['matchedRoute'];
                    $this->matchedEndpoint = $cachedRoutes[$this->requestUri]['matchedEndpoint'];
                    $this->matchedMethod  = $this->requestMethod;
                    $this->params  = (isset($cachedRoutes[$this->requestUri]['params'])) ?
                        $cachedRoutes[$this->requestUri]['params'] : [];

                    // no need to look for more
                    return true;
                }
            }
        }

        return false;
    }
587788
public function run()
    {
        $router = new Router();
        $cache = new Cache();
        if (file_exists('../Routes/Routes.php')) {
            $routeFile = '../Routes/Routes.php';
        } elseif (file_exists('Routes/Routes.php')) {
            $routeFile = 'Routes/Routes.php';
        } else {
            throw new \Exception('Error while loading Route.php file', 500);
        }
        if (__config()->config->router_cache === true) {
            if (!$cache->setAdapter('file')->has('router')) {
                require_once $routeFile;
                $router->cacheRouters();
                $router->dispatch(new Request());
            } else {
                $router->routes = $router->loadCache();
                $router->dispatch(new Request());
            }
        } else {
            require_once $routeFile;
            $router->cacheRouters();
            $router->dispatch(new Request());
        }
    }
962880
protected function findRoute(Request $request)
    {
        if (! in_array($request->method(), array('GET', 'HEAD', 'OPTIONS'))) {
            return;
        }

        $uri = $request->path();

        foreach ($this->routes as $pattern => $callback) {
            if (preg_match('#^' .$pattern .'$#s', $uri, $matches)) {
                return array($callback, array_slice($matches, 1));
            }
        }
    }
802931
public function setRoutes() : void
    {
        if (is_null($this->routes)) {
            $this->routes = [];
            $routesConfig = $this->config->getParam('routes') ?? [];
            foreach ($routesConfig as $routeName => $routeArr) {
                $route = new Route(
                    $routeName,
                    $routeArr['methods'],
                    $routeArr['path'],
                    $routeArr['params_defaults'],
                    $routeArr['params_requirements'],
                    $routeArr['handler'],
                    $routeArr['handler_method'] ?? null
                );
                $this->routes[] = $route;
            }
        }
    }