Generate controller of all routes & middlewares
7350
function generate() {
  for(const i in Routes) {
    if(!Routes[i].generated) {
      Routes[i] = generateController(path.controllers, Routes[i]);
    }
  }

  for(const i in MiddleWares) {
    MiddleWares[i] = generateController(path.middlewares, MiddleWares[i]);
  }

  for(const i in GlobalMiddleWares) {
    GlobalMiddleWares[i] = generateController(path.middlewares, GlobalMiddleWares[i]);
  }

  for(const i in ErrorsHandler) {
    ErrorsHandler[i] = generateController(path.errorHandler, ErrorsHandler[i]);
  }

  for(const i in Services) {
    Services[i] = generateService(path.services, Services[i]);
  }
}
1088486
private function generateController()
    {
        // Generate Controller class
        $controllerInstance = Controller::instance($this->columns, $this->viewType, $this);

        $controllerTemplateDir =
            dirname(dirname(__FILE__)).DS.'src'.DS.'Apps'.DS.'Controllers'.DS;

        $controllerInstance->setControllerTemplatePath($controllerTemplateDir);
        $controllerInstance->setApplicationDirectory($this->applicationDir);

        $controllerInstance->setControllerName($this->controller);
        $controllerInstance->setModelName($this->model);
        $controllerInstance->updateTemplate();
        $controllerInstance->generateControllerTemplate();

        $controllerInstance->generate();

        $this->info("Controller $this->controller Generated Successfully!");
    }
562898
protected void generateRoutes()
    {
        try {

//			Optional<io.sinistral.proteus.annotations.Chain> typeLevelWrapAnnotation = Optional.ofNullable(controllerClass.getAnnotation(io.sinistral.proteus.annotations.Chain.class));
//			
//			typeLevelWrapAnnotation.ifPresent( a -> {
//				 
//				io.sinistral.proteus.annotations.Chain w = typeLevelWrapAnnotation.get();
//
//				Class<? extends HandlerWrapper> wrapperClasses[] = w.value();
//
//				for (int i = 0; i < wrapperClasses.length; i++)
//				{
//					Class<? extends HandlerWrapper> wrapperClass = wrapperClasses[i];
//
//					String wrapperName = generateFieldName(wrapperClass.getCanonicalName());
//
//					handlerWrapperMap.put(wrapperClass, wrapperName);
//				}
//				
//			});
//			
//			for(Method m : this.controllerClass.getDeclaredMethods())
//			{
//			
//				Optional<io.sinistral.proteus.annotations.Chain> methodLevelWrapAnnotation = Optional.ofNullable(m.getAnnotation(io.sinistral.proteus.annotations.Chain.class));
//				
//				methodLevelWrapAnnotation.ifPresent( a -> {
//					 
//					io.sinistral.proteus.annotations.Chain w = methodLevelWrapAnnotation.get();
//	
//					Class<? extends HandlerWrapper> wrapperClasses[] = w.value();
//	
//					for (int i = 0; i < wrapperClasses.length; i++)
//					{
//						Class<? extends HandlerWrapper> wrapperClass = wrapperClasses[i];
//	
//						String wrapperName = generateFieldName(wrapperClass.getCanonicalName());
//	
//						handlerWrapperMap.put(wrapperClass, wrapperName);
//					}
//					
//				});
//
//			}
//			
//			log.info("handlerWrapperMap: " + handlerWrapperMap);

            TypeSpec.Builder typeBuilder = TypeSpec.classBuilder(className).addModifiers(Modifier.PUBLIC)
                    .addSuperinterface(ParameterizedTypeName.get(Supplier.class, RoutingHandler.class));

            ClassName extractorClass = ClassName.get("io.sinistral.proteus.server", "Extractors");

            ClassName injectClass = ClassName.get("com.google.inject", "Inject");


            MethodSpec.Builder constructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addAnnotation(injectClass);

            String className = this.controllerClass.getSimpleName().toLowerCase() + "Controller";

            typeBuilder.addField(this.controllerClass, className, Modifier.PROTECTED, Modifier.FINAL);

            ClassName wrapperClass = ClassName.get("io.undertow.server", "HandlerWrapper");
            ClassName stringClass = ClassName.get("java.lang", "String");
            ClassName mapClass = ClassName.get("java.util", "Map");

            TypeName mapOfWrappers = ParameterizedTypeName.get(mapClass, stringClass, wrapperClass);

            TypeName annotatedMapOfWrappers = mapOfWrappers
                    .annotated(AnnotationSpec.builder(com.google.inject.name.Named.class).addMember("value", "$S", "registeredHandlerWrappers").build());

            typeBuilder.addField(mapOfWrappers, "registeredHandlerWrappers", Modifier.PROTECTED, Modifier.FINAL);


            constructor.addParameter(this.controllerClass, className);
            constructor.addParameter(annotatedMapOfWrappers, "registeredHandlerWrappers");

            constructor.addStatement("this.$N = $N", className, className);
            constructor.addStatement("this.$N = $N", "registeredHandlerWrappers", "registeredHandlerWrappers");

            addClassMethodHandlers(typeBuilder, this.controllerClass);

            typeBuilder.addMethod(constructor.build());

            JavaFile javaFile = JavaFile.builder(packageName, typeBuilder.build()).addStaticImport(extractorClass, "*").build();

            StringBuilder sb = new StringBuilder();

            javaFile.writeTo(sb);

            this.sourceString = sb.toString();

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
487311
function route({path, module, props, childRoutes}) {
  let urlPath = ''
  let childs = {}

  for (let i = 0, childRoute, moduleTemp; childRoute = childRoutes[i]; i++) {
    childs[childRoute.path] = childRoute.module
  }

  let routerDef = F.def({
    init: ({key}) => ({
      childName: '/',
      childStates:  R.mapObjIndexed((child, name) => child.init({key: name}), childs),
      ...module.init({key}),
    }),
    inputs: {
      changeChild: (ctx, Action, name) => Action.ChangeChild(name),
      childAction: (ctx, Action, name, a) => Action.ChildAction(name, a),
      ...module.inputs,
    },
    load: (ctx, i, Action) => {
      return {
        childModules: R.mapObjIndexed((child, name) => F.createContext(child, {action$: i.childAction(name)}), childs),
        ...module.load(ctx, i, Action),
      }
    },
    actions: {
      ChangeChild: [[String], (name, m) => R.evolve({childName: R.always(name)}, m)],
      ChildAction: [[String, Array], (name, a, m) => R.evolve({childStates: R.evolve({[name]: childs[name].update(a)})}, m)],
      ...module.actions,
    },
    interfaces: {
      view: (ctx, i, m) => module.interfaces.view(ctx, i, m),
      router: (ctx, i, m) => ({
        routeChange: function(path) {
          i.changeChild(path)
        }
      }),
    },
  })
  return routerDef
}
145209
def make_map():
    """"""
    map = Mapper(directory=config['pylons.paths']['controllers'],
                 always_scan=config['debug'])

    # The ErrorController route (handles 404/500 error pages); it should
    # likely stay at the top, ensuring it can always be resolved
    map.connect('error/:action/:id', controller='error')

    # CUSTOM ROUTES HERE

    map.connect(':controller/:action/:id')

    return map
640004
def _generate_route_methods(self, namespaces):
        """"""
        self.cur_namespace = None
        for namespace in namespaces:
            if namespace.routes:
                self.emit('# ------------------------------------------')
                self.emit('# Routes in {} namespace'.format(namespace.name))
                self.emit()
                self._generate_routes(namespace)
1339378
function generateController(path, modelName, modelFields, generateMethod, ts, cb) {
    var extension = (ts) ? 'ts' : 'js';
    var controller = ft.loadTemplateSync('controller.' + extension);

    var updateFields = '';
    var createFields = os.EOL;

    modelFields.forEach(function (f, index, fields) {
        var field = f.name;

        updateFields += modelName + '.' + field + ' = req.body.' + field + ' ? req.body.' + field + ' : ' +
            modelName + '.' + field + ';';
        updateFields += os.EOL + '\t\t\t';

        createFields += '\t\t\t' + field + ' : req.body.' + field;
        createFields += ((fields.length - 1) > index) ? ',' + os.EOL : '';
    });

    controller = controller.replace(/{modelName}/g, formatTools.capitalizeFirstLetter(modelName) + 'Model');
    controller = controller.replace(/{name}/g, modelName);
    controller = controller.replace(/{pluralName}/g, formatTools.pluralize(modelName));
    controller = controller.replace(/{controllerName}/g, modelName + 'Controller');
    controller = controller.replace(/{createFields}/g, createFields);
    controller = controller.replace(/{updateFields}/g, updateFields);

    if (generateMethod === 't') {
        ft.createDirIfIsNotDefined(path, 'controllers', function () {
            controller = controller.replace(/{modelPath}/g, '\'../models/' + modelName + 'Model.' + extension + '\'');
            ft.writeFile(path + '/controllers/' + modelName + 'Controller.' + extension, controller, null, cb);
        });
    } else {
        ft.createDirIfIsNotDefined(path, modelName, function () {
            controller = controller.replace(/{modelPath}/g, '\'./' + modelName + 'Model.' + extension + '\'');
            ft.writeFile(path + '/' + modelName + '/' + modelName + 'Controller.' + extension, controller, null, cb);
        });
    }
}
133891
protected function dispatch ($routes, $toController) 
	{
		/**
		 * $routes - Routes from the list of declared routes
		 * $route  - Actual route from the URI
		 */
		$route = $this->resolve();

		preg_match_all("/{([^{}?&]+)}/", $routes, $matches);

		// Non dynamic route
		if (empty($matches[0])) {
			if (is_callable($toController)){
				if ($route === $routes) {
					$middlewareRoute 	= $route;

					$before = null;
					if (isset($this->middlewares['before'][$middlewareRoute]))
						$before = $this->middlewares['before'][$middlewareRoute];

					$after = null;
					if (isset($this->middlewares['after'][$middlewareRoute]))
						$after = $this->middlewares['after'][$middlewareRoute];

					return [
						'controllerClosure' => $toController,
						'args' => ['app' => $this->app, 'requests' => $this->requests],
						'before' => $before,
						'after' => $after,
					];
				} else {
					return null;
				}
			} else if (is_array($toController)) {
				if ($route === $routes) {
					$middlewareRoute 	= $route;
					$controller 		= array_keys($toController);
					$action 			= array_values($toController);

					$before = null;
					if (isset($this->middlewares['before'][$middlewareRoute]))
						$before = $this->middlewares['before'][$middlewareRoute];

					$after = null;
					if (isset($this->middlewares['after'][$middlewareRoute]))
						$after = $this->middlewares['after'][$middlewareRoute];

					return [
						'controller' => sprintf("%s::%s", $controller[0],$action[0]),
						'args' => ['app' => $this->app, 'requests' => $this->requests],
						'before' => $before,
						'after' => $after,
					];
				} else {
					return null;
				}
			}

		} 
		// Dynamic route
		else {
			$middlewareRoute 	= $routes;
			$routes 			= str_replace("/", "\/", $routes);
			$routes 			= preg_replace("/{([^{}]+)}/", "([^\/]+)", $routes);

			if (is_callable($toController)){
				if (preg_match_all("#$routes$#", $route, $matchRoute)) {
					array_shift($matchRoute);

					$args = ['app' => $this->app, 'requests' => $this->requests];
					foreach ($matchRoute as $key => $value) {
						$args[] = $value[0];
					}

					$before = null;
					if (isset($this->middlewares['before'][$middlewareRoute]))
						$before = $this->middlewares['before'][$middlewareRoute];

					$after = null;
					if (isset($this->middlewares['after'][$middlewareRoute]))
						$after = $this->middlewares['after'][$middlewareRoute];

					return [
						'controllerClosure' => $toController,
						'args' => $args,
						'before' => $before,
						'after' => $after,
					];
				} else {
					return null;
				}
			} else if (is_array($toController)) {
				if (preg_match_all("#^$routes$#", $route, $matchRoute)) {
					array_shift($matchRoute);

					$controller = array_keys($toController);
					$action 	= array_values($toController);

					$args = ['app' => $this->app, 'requests' => $this->requests];
					foreach ($matchRoute as $key => $value) {
						$args[] = $value[0];
					}

					$before = null;
					if (isset($this->middlewares['before'][$middlewareRoute]))
						$before = $this->middlewares['before'][$middlewareRoute];

					$after = null;
					if (isset($this->middlewares['after'][$middlewareRoute]))
						$after = $this->middlewares['after'][$middlewareRoute];

					return [
						'controller' => sprintf("%s::%s", $controller[0],$action[0]),
						'args' => $args,
						'before' => $before,
						'after' => $after,
					];
				} else {
					return null;
				}
			}
		}
	}
1041893
protected function initRouter()
    {

        // Get all routes from local bootstrap
        $routes = $this->setRoutes();

        // Send all routes to Router
        foreach ($routes as $route) {
            if ($route[0] == 'any') {
                Router::any($route[1], $route[2]);
            } elseif ($route[0] == 'get') {
                Router::get($route[1], $route[2]);
            } elseif ($route[0] == 'post') {
                Router::post($route[1], $route[2]);
            } else {
                echo error::display('Route Error: bad declaration');
            }
        }

        // Set default controller and action for errors
        Router::error('\Core\Error@index');
        Router::dispatch();
    }
190174
protected function generateController()
    {
        $name = Pluralizer::plural($this->model);

        $this->call(
            'generate:controller',
            array(
                'name' => "{$name}Controller",
                '--template' => $this->getControllerTemplatePath()
            )
        );
    }
140442
function Router() {
  var self = this;
  this._routes = [];
  this.middleware = function(page, next) {
    self._dispatch(page, next);
  };
}
1143684
function middlewares() {
        app.middlewares = {}
        const basePath = path.join(app.root, '/middlewares')
        let middlewares = app.config.get('express').middlewares
        if (middlewares && Array.isArray(middlewares) && middlewares.length) {
            for (let m of middlewares) {
                let middleware = require(path.join(basePath, m.dest))(app)
                app.middlewares[m.dest.toLowerCase()] = middleware

                if (middleware.length == 4) { //error handler
                    errorHandlers.push(middleware)
                    continue
                }

                if (m.src)
                    server.use(m.src, wrapper(middleware))
                else
                    server.use(wrapper(middleware))
            }
            if (middlewares.length)
                app.drivers.logger.success('Middleware', 'initialized')
        }
    }
560864
public static function dispatch()
    {
        $vars = [];

        $request = Request::createFromGlobals();

        $dispatcher = new Dispatcher(static::instance()->getData());
        $routeInfo = $dispatcher->dispatch(
            $request->getMethod(),
            $request->getUri()->getPath()
        );

        $controller = "\\Barebone\\Controller";
        $action = "index";

        switch ($routeInfo[0]) {
        case Dispatcher::NOT_FOUND:
            $action = 'routerError';
            $vars['error'] = static::ERR_NOT_FOUND;
            $vars['subject'] = $request->getUri()->getPath();
            break;

        case Dispatcher::METHOD_NOT_ALLOWED:
            $action = 'routerError';
            $vars['error'] = static::ERR_BAD_METHOD;
            $vars['subject'] = $routeInfo[1];
            break;

        case Dispatcher::FOUND:
            $handler = $routeInfo[1];
            $vars = $routeInfo[2];

            if (!class_exists($handler[0])) {
                $action = 'routerError';
                $vars['error'] = static::ERR_MISSING_CONTROLLER;
                $vars['subject'] = $handler[0];
            } elseif (!method_exists($handler[0], $handler[1])) {
                $action = 'routerError';
                $vars['error'] = static::ERR_MISSING_ACTION;
                $vars['subject'] = $handler[0] . '::' . $handler[1];
            } else {
                $controller = $handler[0];
                $action = $handler[1];
            }
            break;
        }

        // Start with an empty response
        $response = new Response();
        $request->setAction($action);

        // @var Controller $instance
        $instance = new $controller($request, $response);
        $instance->initController();

        // Get Middleware stacks
        $before = $instance->getMiddlewareBefore();
        $after = $instance->getMiddlewareAfter();

        // Append the action call to the middleware stack
        $before[] = function (Request $request, Response $response,
            callable $next = null
        ) use ($instance, $action, $vars) {

            // assigned updated objects
            $instance->setRequest($request);
            $instance->setResponse($response);

            // get updated response from action
            $response = call_user_func_array([$instance, $action], $vars);

            // continue
            return $next($instance->getRequest(), $response);
        };

        // Run the middleware stack and return the Response
        $middlewares = array_reverse(array_merge($before, $after));
        $runner = \Sirius\Middleware\Runner::factory($middlewares);

        return $runner($request, $response);
    }
976236
private function generateControllerClass()
    {
        $dir = $this->bundle->getPath();

        $parts = explode('\\', $this->document);
        $class = array_pop($parts);

        $namespace = implode('\\', $parts);

        $target = sprintf(
            '%s/Controller/%s/%sController.php',
            $dir,
            str_replace('\\', '/', $namespace),
            $class
        );

        if (file_exists($target)) {
            throw new \RuntimeException('Unable to generate the controller as it already exists.');
        }

        $this->renderFile('controller.php.twig', $target, array(
            'actions' => $this->actions,
            'route_prefix' => $this->routePrefix,
            'route_name_prefix' => $this->routeNamePrefix,
            'dir' => $this->skeletonDir,
            'bundle' => $this->bundle->getName(),
            'document' => $this->document,
            'document_class' => $class,
            'namespace' => $this->bundle->getNamespace(),
            'controller_namespace' => $namespace,
            'format' => $this->format,
        ));
    }
290298
public static function dispatch()
    {

        if (is_null(self::$route)) die(Utils::colorize("No console route found", 'FAILURE'));

        // Grab the controller name and method call
        $segments = explode('@', self::$route);

        $controller = $segments[0];
        // Compiled action name
        $action = $segments[1] . 'Action';

        $object = new $controller();
        if (!method_exists($object, $action)) die(Utils::colorize("No action '{$segments[1]}' find in {$controller}!", 'FAILURE'));

        call_user_func_array(array($controller, $action), self::$parameters);
    }
1118091
def make_route(self, route) -> dict:
        
        middleware = route['middleware'] if 'middleware' in route else None
        # added to ALL requests to support xhr cross-site requests
        route['methods'].append('OPTIONS')
        return {
            'url': route['url'],
            'name': route['name'],
            'methods': route['methods'],
            'middleware': middleware,
            'callback': {
                'module': route['function'].__module__,
                'class': route['function'].__qualname__.rsplit('.', 1)[0],
                'function': route['function'].__name__
            }
        }
1277066
def _routes(self, app):
        
        _routes = []
        prefix = self.url_prefix if self.url_prefix is not None else ""
        for rule in app.url_map.iter_rules():
            if str(rule).startswith(prefix):
                _routes.append({
                    'path':rule.rule,
                    'name':rule.endpoint,
                    'methods':list(rule.methods)
                })
        returns = {
            'api': self.name,
            'url_root': request.url_root,
            'routes': _routes
        }
        return jsonify(returns)