Process custom router

@return bool
974437
protected function processCustom(): bool
    {
        $uri = '/' . $this->getCleanUri();
        foreach ($this->routers as $router) {
            if (preg_match($router['pattern'], $uri, $matches)) {
                $this->setParam('_module', $router['module']);
                $this->setParam('_controller', $router['controller']);

                foreach ($router['params'] as $param => $type) {
                    if (isset($matches[$param])) {
                        $this->setParam($param, $matches[$param]);
                    }
                }
                return true;
            }
        }
        return false;
    }
687644
public function exec()
    {
        $http = $this->argument('http');
        $controller = $this->argument('controller');
        $method = $this->argument('method');
        //
        $process = Router::target($http, $controller, $method);
        //
        $this->show($process);
    }
994655
public function runServer()
    {
        $router = $this->drupalDir . '/.ht.router.php';
        if (!file_exists($router)) {
            $this->createFile(
                $router,
                file_get_contents(__DIR__ . '/.ht.router.php')
            );
        }

        $uri = parse_url($this->baseUrl);

        $this->serverProcess = ProcessBuilder::create()
            ->setPrefix('exec')
            ->add($this->phpBin)
            ->add('-S')
            ->add(sprintf('%s:%s', $uri['host'], $uri['port']))
            ->add($router)
            ->setWorkingDirectory($this->drupalDir)
            ->getProcess();

        $this->serverProcess->start();

        sleep(1);

        if (!$this->serverProcess->isRunning()) {
            throw new RuntimeException('PHP built-in server process terminated immediately');
        }

        // Also trap fatal errors to make sure running processes are terminated.
        register_shutdown_function([$this, 'stopServer']);
    }
1290812
public function processOptionRoutes()
    {
        $this->alert('ROUTES PROCESS');

        // Verify option ROUTES
        if (in_array(strtoupper(trim($this->option('routes'))), ['N','NO','FALSE'])) {
            $this->routes = false;
        }

    }
1196188
protected function processRequest()
    {
        $route  = $this[ 'request' ]->getRoute();
        $params = $this[ 'request' ]->getParams();

        $controller = $this[ 'router' ]->createController( $route, $params );

        if ( NULL === $controller )
        {
            throw new RawException( 'Failed to Initialise Controller', 404 );
        }

        $this->controller = $controller;

        /** @var IController $controller */
        $controller->run();
    }
886669
private function processExternalTemplater()
    {
        $template_extension = pathinfo($this->router_instance->getPageData()['file'], PATHINFO_EXTENSION);

        // Render twig file. e.g. file.twig
        if ($template_extension == 'twig') {
            if (Settings::isFrontendLogEnabled()) {
                FrontendLogger::getInstance()->log('Processing twig template');
            }
            $templater = new ExternalTemplater('twig');
            $this->html = $templater->processHtml($this->html, $this->router_instance->getPageData());

            return;
        }

        // Check blade files, e.g. file.blade.php
        if (stripos($this->router_instance->getPageData()['file'], '.blade.php') !== false) {
            if (Settings::isFrontendLogEnabled()) {
                FrontendLogger::getInstance()->log('Processing blade template');
            }
            $templater = new ExternalTemplater('blade');
            $this->html = $templater->processHtml($this->html, $this->router_instance->getPageData());

            return;
        }
    }
763470
protected function cloneLaravelRouter()
    {
        $router = clone $this->app['router'];
        $router->aliasMiddleware('api.auth', NodesHttpMiddlewareAuth::class);
        $router->aliasMiddleware('api.controllers', NodesHttpMiddlewarePrepareController::class);
        $router->aliasMiddleware('api.throttle', NodesHttpMiddlewareRateLimit::class);
        $router->aliasMiddleware('api.useragent', NodesHttpMiddlewareUserAgent::class);
        $router->aliasMiddleware('api.meta', NodesHttpMiddleware::class);

        return $router;
    }
1082240
private function handleRouter()
    {
        require_once QP_APP_PATH . "routers.php";

        if (QR::hasMatched() == false) {
            echo (new \App\Controllers\IndexController)->notFoundAction();
            exit;
        }

        $matched_router_data = QR::getMatchedData();

        $ns = $matched_router_data['namespace'];
        $ctrl = $matched_router_data['controller'];
        $m = QR::getMethod();

        if (! method_exists(($ns . "\\" . $ctrl . "Controller"), $m . "Action")) {
            echo (new \App\Controllers\IndexController)->notFoundAction();
            exit;
        }

        $router = new \Phalcon\Mvc\Router();
        $router->setDefaults([
            "namespace" => $ns,
            "controller" => $ctrl,
            "action" => $m,
        ]);

        return $router;
    }
492445
protected function processRoute($route)
	{
		$routeAction = $route->getAction();

		$this->getParentCommand()->info('Processing route [' . implode('/', $route->methods()) . '] ' . $routeAction['uri']);

		$routeControllerDocBlock = $this->getRouteControllerDocBlock($route);
		$routeControllerOperationTags = $this->getDocBlockOperationTags($routeControllerDocBlock);

		foreach ($route->methods() as $httpMethod) {
			// Ignore HEAD

			if (strtolower($httpMethod) == 'head') {
				continue;
			}

			if (isset($this->openAPI->paths[$routeAction['uri']])) {
				$pathItem = $this->openAPI->paths[$routeAction['uri']];
			} else {
				$pathItem = $this->openAPI->paths[$routeAction['uri']] = new PathItem();

				if (!is_null($routeControllerDocBlock)) {
					$pathItem->summary = $routeControllerDocBlock->getSummary();
					if (empty($pathItem->summary)) {
						$pathItem->summary = null;
					}
					$routeControllerDescriptionDocBlock = $routeControllerDocBlock->getDescription();
					$pathItem->description = $routeControllerDescriptionDocBlock->render();
					if (empty($pathItem->description)) {
						$pathItem->description = null;
					}
				}
			}

			$operation = new Operation();

			$operationTags = $routeControllerOperationTags;

			$routeMethodDocBlock = $this->getRouteMethodDocBlock($route);
			$extraParameterRefTags = [];

			if (!is_null($routeMethodDocBlock)) {
				$operation->summary = $routeMethodDocBlock->getSummary();
				if (empty($operation->summary)) {
					$operation->summary = null;
				}
				$routeMethodDescriptionDocBlock = $routeMethodDocBlock->getDescription();
				$operation->description = $routeMethodDescriptionDocBlock->render();
				if (empty($operation->description)) {
					$operation->description = null;
				}
				$routeMethodOperationTags = $this->getDocBlockOperationTags($routeMethodDocBlock);

				$operationTags = array_merge($routeControllerOperationTags, $routeMethodOperationTags);
				$extraParameterRefTags = $this->getDocBlockExtraParameterRefTags($routeMethodDocBlock);

				$operation->operationId = $this->getDocBlockOperationId($routeMethodDocBlock);
			}

			if (is_null($operation->operationId)) {
				switch (strtolower($httpMethod)) {
					case 'patch':
					case 'put':
						$operation->operationId = strtolower($httpMethod) . ucfirst(array_last(explode('.', $routeAction['as'])));
						break;
					default :
						$operation->operationId = array_last(explode('.', $routeAction['as']));
				}
			}

			if (count($operationTags) > 0) {
				$operation->tags = $operationTags;
			}

			// Try
			$routePathParameters = $this->getRoutePathParameters($route);

			foreach ($routePathParameters as $parameterName => $parameterData) {
				$parameterDescription = isset($parameterData['docDescription']) ? $parameterData['docDescription'] : '';
				if (trim($parameterDescription) == '') {
					$parameterDescription = null;
				}
				$parameter = new Parameter([
					'name' => $parameterName,
					'in' => 'path',
					'description' => $parameterDescription,
					'required' => true,
				]);
				if (isset($parameterData['type'])) {
					$parameter->schema = new Schema([
						'type' => $parameterData['type']
					]);
				}
				if (isset($parameterData['docType'])) {
					$parameter->schema = new Schema([
						'type' => $parameterData['docType']
					]);
				}
				$operation->parameters[] = $parameter;
			}

			// Try to get route validation rules
			$routeValidationRules = $this->getRouteValidationRules($route);

			if (count($routeValidationRules) > 0) {
				switch (strtolower($httpMethod)) {
					case 'get':
					//case 'head':

						foreach ($routeValidationRules as $parameterName => $rulesString) {
							$rules = explode('|', $rulesString);

							$parameter = new Parameter([
								'name' => $parameterName,
								'in' => 'query',
								'description' => null, /* @todo Grab description from phpdoc custom tag ? */
								'required' => in_array('required', $rules),
							]);

							$parameter->schema = $this->getPropertyValidationRulesSchema(
								$rules,
								'Validation rules for parameter "' . $parameterName . '"',
								true
							);
							
							if (is_null($parameter->schema->format)) {
								// ignore this parameter if no type found
								$this->getParentCommand()->warn('  Ignore parameter "' . $parameterName . '"');
								continue;
							}

							// Add if not already added from the "path" parameters
							$find = false;
							if (is_null($operation->parameters)) {
								$operation->parameters = [];
							}
							/** @var Parameter $p */
							foreach ($operation->parameters as $p) {
								if ($p->name == $parameter->name) {
									$find = true;
								}
							}
							if (!$find) {
								$operation->parameters[] = $parameter;
							}
						}

						break;

					case 'put':
					case 'patch':
					case 'post':

						$requestBody = new RequestBody();
						$mediaType = new MediaType();
						$mediaType->schema = new Schema();
						$mediaType->schema->properties = [];

						// Change to multi-part if file in parameters ("string" type and "binary" format)
						$contentType = 'application/json';
						
						foreach ($routeValidationRules as $parameterName => $rulesString) {
							$rules = explode('|', $rulesString);
							$schema = $this->getPropertyValidationRulesSchema(
								$rules,
								'Validation rules for parameter "' . $parameterName . '"',
								true
							);
							
							// ignore this property if no type found
							if (is_null($schema->type)) {
								$this->getParentCommand()->warn('  Ignore parameter "' . $parameterName . '"');
								continue;
							}
							
							// Change to multi-part if file in parameters ("string" type and "binary" format)
							if ($schema->type == 'string' && $schema->format == 'binary') {
								$contentType = 'multipart/form-data';
								// Change mediaType schema type
								$mediaType->schema->type = 'object';
							}
							
							$mediaType->schema->properties[$parameterName] = $schema;
						}

						$mediaType->schema->required = $this->getValidationRulesSchemaRequired($routeValidationRules);

						$requestBody->content[$contentType] = $mediaType;
						$operation->requestBody = $requestBody;

						$operation->responses = [];

						break;
				}
			}

			// Append extra parameter refs

			foreach ($extraParameterRefTags as $extraParameterRefTag) {
				$parameterRef = new Reference([
					'ref' => $extraParameterRefTag
				]);

				if (is_null($operation->parameters)) {
					$operation->parameters = [];
				}

				$operation->parameters[] = $parameterRef;
			}

			// First response

			$response = new Response();
			$responseMediaType = null;

			$apiResponseSchemaRefTags = $routeMethodDocBlock->getTagsByName('OpenApiResponseSchemaRef');
			if (count($apiResponseSchemaRefTags) > 0) {
				if (is_null($responseMediaType)) {
					$responseMediaType = new MediaType();
				}
				$apiResponseSchemaRefTag = $apiResponseSchemaRefTags[0];
				$apiResponseSchemaRef = trim(str_replace('@OpenApiResponseSchemaRef', '', $apiResponseSchemaRefTag->render()));
				$responseMediaType->schema = new Reference([
					'ref' => $apiResponseSchemaRef
				]);
			}
			
			$response->description = '';
			$apiResponseDescriptionTags = $routeMethodDocBlock->getTagsByName('OpenApiResponseDescription');
			if (count($apiResponseDescriptionTags) > 0) {
				$apiResponseDescriptionTag = $apiResponseDescriptionTags[0];
				$apiResponseDescription = trim(str_replace('@OpenApiResponseDescription', '', $apiResponseDescriptionTag->render()));
				$response->description = $apiResponseDescription;
			}

			$apiDocsNoCallTags = $routeMethodDocBlock->getTagsByName('ApiDocsNoCall');
			if (count($apiDocsNoCallTags) == 0) {
				$exampleResponse = $this->getRouteCallExampleResponse($route, $httpMethod);
				if (!is_null($exampleResponse)) {
					if (is_null($responseMediaType)) {
						$responseMediaType = new MediaType();
					}

					$exampleSchemaId = $this->getRouteExampleResponseId($route);

					// Create Example schema in components

					if (is_null($this->openAPI->components)) {
						$this->openAPI->components = new Components();
					}

					$this->openAPI->components->examples[$exampleSchemaId] = new Example([
						'value' => json_decode($exampleResponse, true)
					]);

					$responseMediaType->example = new Reference([
						'ref' => '#/components/examples/' . $exampleSchemaId
					]);
				}
			}

			if (!is_null($responseMediaType)) {
				$response->content['application/json'] = $responseMediaType;
			}
			
			// Excepted HTTP code specified ? "OpenApiResponseExceptedHTTPCode" tag
			
			$apiResponseExceptedHTTPCode = null;
			$apiResponseExceptedHTTPCodeTags = $routeMethodDocBlock->getTagsByName('OpenApiResponseExceptedHTTPCode');
			if (count($apiResponseExceptedHTTPCodeTags) > 0) {
				$apiResponseExceptedHTTPCodeTag = $apiResponseExceptedHTTPCodeTags[0];
				$apiResponseExceptedHTTPCode = trim(str_replace('@OpenApiResponseExceptedHTTPCode', '', $apiResponseExceptedHTTPCodeTag->render()));
			}

			if (!is_null($apiResponseExceptedHTTPCode)) {
				$operation->responses[$apiResponseExceptedHTTPCode] = $response;
			} else {
				switch (strtolower($httpMethod)) {
					case 'get':
						//case 'head':
						$operation->responses['200'] = $response;
						break;
					
					case 'put':
					case 'patch':
						$operation->responses['200'] = $response;
						break;
						
					case 'post':
						$operation->responses['201'] = $response;
						break;
					
					case 'delete':
						$operation->responses['204'] = $response;
						break;
				}
			}

			// Default response (Errors)

			$defaultResponse = new Response();
			$defaultResponseMediaType = null;

			$apiDefaultResponseSchemaRefTags = $routeMethodDocBlock->getTagsByName('OpenApiDefaultResponseSchemaRef');
			if (count($apiDefaultResponseSchemaRefTags) > 0) {
				if (is_null($defaultResponseMediaType)) {
					$defaultResponseMediaType = new MediaType();
				}
				$apiDefaultResponseSchemaRefTag = $apiDefaultResponseSchemaRefTags[0];
				$apiDefaultResponseSchemaRef = trim(str_replace('@OpenApiDefaultResponseSchemaRef', '', $apiDefaultResponseSchemaRefTag->render()));
				$defaultResponseMediaType->schema = new Reference([
					'ref' => $apiDefaultResponseSchemaRef
				]);
			}

			$defaultResponse->description = '';
			$apiDefaultResponseDescriptionTags = $routeMethodDocBlock->getTagsByName('OpenApiDefaultResponseDescription');
			if (count($apiDefaultResponseDescriptionTags) > 0) {
				$apiDefaultResponseDescriptionTag = $apiResponseDescriptionTags[0];
				$apiDefaultResponseDescription = trim(str_replace('@OpenApiDefaultResponseDescription', '', $apiDefaultResponseDescriptionTag->render()));
				$defaultResponse->description = $apiDefaultResponseDescription;
			}

			if (!is_null($defaultResponseMediaType)) {
				$defaultResponse->content['application/json'] = $defaultResponseMediaType;
			}

			$operation->responses['default'] = $defaultResponse;

			$pathItem->{strtolower($httpMethod)} = $operation;
		}
	}
1010043
protected function preProcess(): void
    {
        Router::process();

        // disable Layout for XmlHttpRequests
        if (Request::isXmlHttpRequest()) {
            $this->layoutFlag = false;
        }

        // switch to JSON response based on Accept header
        if (Request::checkAccept([Request::TYPE_HTML, Request::TYPE_JSON]) === Request::TYPE_JSON) {
            $this->layoutFlag = false;
            Response::setType('JSON');
        }
    }
838461
protected function executeHandler()/*# : bool */
    {
        // search handler
        $handler = $this->result->getHandler();

        if (is_null($handler)) {
            // matched, but no handler found
            return $this->defaultHandler();
        } else {
            $callable = $this->resolver->resolve($handler);

            // extension ?
            if (($route = $this->result->getRoute()) && $route->hasExtension()) {
                if ($route->runExtensions(Route::BEFORE_ROUTE, $this->result)) {
                    $callable($this->result);
                    $route->runExtensions(Route::AFTER_ROUTE, $this->result);
                }
            } else {
                $callable($this->result);
            }
            return true;
        }
    }
154840
public function map()
    {
        Route::namespace($this->namespace)->group(function (Router $router) {

            /*
             * Front office routes
             */
            $router->middleware('web')->group(function (Router $router) {
                foreach (locales() as $lang) {
                    if (config('typicms.register')) {
                        // Registration
                        $router->get($lang.'/register', 'RegisterController@showRegistrationForm')->name($lang.'::register');
                        $router->post($lang.'/register', 'RegisterController@register');
                        // Verify
                        $router->get($lang.'/email/verify', 'VerificationController@show')->name($lang.'::verification.notice');
                        $router->get($lang.'/email/verify/{id}', 'VerificationController@verify')->name($lang.'::verification.verify');
                        $router->get($lang.'/email/resend', 'VerificationController@resend')->name($lang.'::verification.resend');
                    }
                    // Login
                    $router->get($lang.'/login', 'LoginController@showLoginForm')->name($lang.'::login');
                    $router->post($lang.'/login', 'LoginController@login');
                    // Request new password
                    $router->get($lang.'/password/reset', 'ForgotPasswordController@showLinkRequestForm')->name($lang.'::password.request');
                    $router->post($lang.'/password/email', 'ForgotPasswordController@sendResetLinkEmail')->name($lang.'::password.email');
                    // Set new password
                    $router->get($lang.'/password/reset/{token}', 'ResetPasswordController@showResetForm')->name($lang.'::password.reset');
                    $router->post($lang.'/password/reset', 'ResetPasswordController@reset');
                    // Logout
                    $router->post($lang.'/logout', 'LoginController@logout')->name($lang.'::logout');
                }
            });

            /*
             * Admin routes
             */
            $router->middleware('admin')->prefix('admin')->group(function (Router $router) {
                $router->get('users', 'AdminController@index')->name('admin::index-users')->middleware('can:see-all-users');
                $router->get('users/create', 'AdminController@create')->name('admin::create-user')->middleware('can:create-user');
                $router->get('users/{user}/edit', 'AdminController@edit')->name('admin::edit-user')->middleware('can:update-user');
                $router->post('users', 'AdminController@store')->name('admin::store-user')->middleware('can:create-user');
                $router->put('users/{user}', 'AdminController@update')->name('admin::update-user')->middleware('can:update-user');
            });

            /*
             * API routes
             */
            $router->middleware('api')->prefix('api')->group(function (Router $router) {
                $router->middleware('auth:api')->group(function (Router $router) {
                    $router->get('users', 'ApiController@index')->middleware('can:see-all-users');
                    $router->post('users/current/updatepreferences', 'ApiController@updatePreferences')->middleware('can:update-preferences');
                    $router->patch('users/{user}', 'ApiController@updatePartial')->middleware('can:update-user');
                    $router->delete('users/{user}', 'ApiController@destroy')->middleware('can:delete-user');
                });
            });
        });
    }
623708
public function build() : RouterInterface
    {
        $router = $this->router;
        try{
            // call bootstrap code
            $startup = $this->bootstrap;
            
            $startup($router);
        }
        catch(\Throwable $e)
        {
            throw new RouterBuildingException($e);
        }
        return $router;
    }
186789
public function process()
    {
        if ($this->cache !== null) {
            return $this->cache;
        } else {
            return ($this->cache = UriTemplate::expand($this->template, $this->data));
        }
    }
875785
public function process()
    {
        list($action, $ids) = $this->Process->getRequestVars($this->name);
        return $this->Process->make($this->Groups, $action, $ids);
    }
190261
public function handleSslRouting()
    {
        if ($this->settings->sslRoutingEnabled && !Craft::$app->getRequest()->getIsConsoleRequest())
        {
            $requestedUrl   = Craft::$app->request->getUrl();
            $restrictedUrls = $this->settings->sslRoutingRestrictedUrls;

            if (!Craft::$app->request->isSecureConnection)
            {
                foreach ($restrictedUrls as $restrictedUrl)
                {
                    // Parse dynamic variables like /{cpTrigger}
                    if (stripos($restrictedUrl, '{') !== false)
                    {
                        $restrictedUrl = Craft::$app->view->renderObjectTemplate(
                            $restrictedUrl,
                            $this->getDynamicParams()
                        );
                    }

                    $restrictedUrl = '/'.ltrim($restrictedUrl, '/');

                    if (stripos($requestedUrl, $restrictedUrl) === 0)
                    {
                        $this->forceSsl();
                    }
                }

                return true;
            }
        }

        return false;
    }
829845
public function process()
    {
        $args = $this->getArgs();
        $map = $this->getConfig('map');
        foreach ($map as $to => $from) {
            $args[$to] = isset($args[$from]) ? $args[$from] : null;
        }

        $options = $this->getConfig('options');
        $args += $options;

        $this->getQuery()->find($this->finder(), $args);

        return true;
    }