Launch the dispatch loop
@throws \Exception
@return $this
435464
public function dispatch()
    {
        $request  = Container::getRequest();
        $response = Container::getResponse();
        
        PluginManager::handleApplicationPlugins(PluginManager::STEP_BEFORE_DISPATCH_LOOP);
        //self::debug('Begin dispatch loop...');
        while (!$this->dispatched) {
            
            try {
                PluginManager::handleApplicationPlugins(PluginManager::STEP_BEFORE_ACTION);
                //self::debug('Begin dispatch ' . $request->getController() . '::' . $request->getAction() . ' [' . json_encode($request->getParams()) . ']');
                $this->dispatchProcess($request, $response);
                //self::debug('End dispatch ' . $request->getController() . '::' . $request->getAction() . ' [' . json_encode($request->getParams()) . ']');
                PluginManager::handleApplicationPlugins(PluginManager::STEP_AFTER_ACTION);
            }
            catch (Exception $e) {
                if ($request->getController(false) == 'event' 
                 && $request->getAction(false) == 'error') {
                    throw $e;
                }
                Container::getView()->addValue('exception', $e);
                $this->renderView = true;
                $request->setController('event')->setAction('error');
                $this->setDispatched(false);
            }
        }
        PluginManager::handleApplicationPlugins(PluginManager::STEP_AFTER_DISPATCH_LOOP);
        self::debug('End dispatch loop');
        if ($this->dispatched && $this->renderLayout) {
            $layout = Container::getConfig()->getConfig('layout');
            if ($layout !== null) {
                if (!file_exists($layout)) {
                    throw new ArchException('Layout file ' . $layout . ' not found');
                }
                $response->setBody(Container::getLayout(true)->render($layout));
            }
        }
        if ($this->renderResponse) {
            $response->fixHeaders()->putTypeHeadersInResponse();
            foreach ($response->getHeaders() as $header) {
                header($header);
            }
            $response->executeCallback();
            if ($response->hasBody()) {
                echo $response->getBody();
            }
        }
        return $this;
    }
853383
protected function prepareExecute()
    {
        if (!($this->console instanceof Console\AbstractConsole)) {
            throw new \Exception('RootCommand::$app should have Console Application');
        }

        if (!$this->getOption('ansi') || strtolower($this->getOption('ansi')) === 'off') {
            $this->console->set('ansi', false);

            $this->io->useColor(false);
        }

        if ($this->getOption('quiet')) {
            $this->console->set('quiet', true);
        }

        if ($this->getOption('verbose')) {
            $this->console->set('verbose', true);
        }

        if ($this->getOption('help')) {
            $this->console->set('show_help', true);
        }
    }
1075866
public function run()
    {
        if ($this->initialized) {
            $this->console(sprintf("Start running '%s' method of script '%s'.", $this->opts->action, get_class($this)));
            $this->{$this->action}();
            $this->console(sprintf("End of running '%s' cli script.", get_class($this)), true);
        }

        return $this;
    }
464834
public function dispatch() {
        foreach ($this->_listeners as $key => $listeners) {
            foreach ($this->_events as $events) {
                if (isset($listeners->implementedEvents()[$events->getName()])) {
                    foreach ($listeners->implementedEvents()[$events->getName()] as $event) {
                        if ($events->getStatus() == Event::START && method_exists($listeners, $event)) {
                            ob_start();
                            $this->addError('EVENT call the listener "' . $key . '" "' . get_class($listeners) . '::' . $event . '" for the event "' . $events->getName() . '"', __FILE__, __LINE__, ERROR_INFORMATION);
                            $events->setResult($listeners->$event($events), get_class($listeners) . '::' . $event, get_class($listeners), $event);
                            $output = ob_get_contents();
                            ob_get_clean();

                            $this->addError('[' . $key . '] [' . get_class($listeners) . '::' . $event . '] [' . $events->getName() . "]\n[" . $output . ']', 0, 0, 0, LOG_EVENT);
                        }
                    }
                }
            }
        }
    }
1244052
protected function run()
    {
        $this->silentRunActionTrigger(Action::EVENT_START);
        try {
            $event = $this->action->execute($this->control, $this->context) ?: Action::EVENT_SUCCESS;
            $this->context->exitCode = 0;
        } catch (ErrorException $errorException) {
            $event = Action::EVENT_ERROR;
            $this->context->exception = $errorException;
            $this->context->exitCode = 2;
        } catch (Exception $exception) {
            $event = Action::EVENT_FAILURE;
            $this->context->exception = $exception;
            $this->context->exitCode = 1;
        }
        $this->context->finishTime = time();
        $this->silentRunActionTrigger($event);
        $this->silentRunActionTrigger(Action::EVENT_FINISH);
    }
1110759
public function run(): self
    {
        $this->displayComment();
        $this->launched = true;
        if ($this->onStart) {
            ($this->onStart)();
        }
        $this->execute();
        if ($this->onFinish) {
            ($this->onFinish)();
        }
        $this->doneIterationsCombined += $this->doneIterations;
        return $this;
    }
993620
public function boot()
    {
        if ($this->app->getProps() === null) {
            return;
        }

        $routes = [];
        $pathPrefix = $this->app->getProp($this->routesPathPrefixPropName, '');
        $propRoutes = $this->app->getProp($this->routesPropName, []);

        if (!is_array($propRoutes)) {
            throw new \Exception('Routes definitions must be an array!');
        }

        foreach ($this->app->getProp($this->routesPropName, []) as $route) {
            $this->validate($route);
            $routes[] = $this->app->createRoute(
                $route['method'] ?? null,
                $pathPrefix.$route['path'],
                $route['stack']
            );
        }

        $this->app->stack($routes);
    }
808446
public function dispatch()
    {
        if (strtolower(Container::get('config')->get('url_mode')) == 'query_string') {
            $this->uri = explode('?', $this->uri, 2);
            $_SERVER['QUERY_STRING'] = isset($this->uri[1]) ? $this->uri[1] : '';
            $this->uri = $this->uri[0];
            parse_str($_SERVER['QUERY_STRING'], $_GET);
        }

        if ($this->uri == 'favicon.ico') {
            return Container::get('response')->setStatus(404);
        }

        Middleware::register('before_route');
        $parsedRoute = $this->parseRoutes($this->uri);
        Middleware::register('after_route');

        if ($parsedRoute) {
            $this->uri = $parsedRoute;
        } else {
            if (Container::get('request')->isOptions()) {
                Container::get('response')->setStatus(204);
                exit;
            }

            throw new RouteNotFoundException('Request URI ' . $this->uri . ' is not Matched by any route.');
        }

        $this->uris = ($this->uri != '') ? explode('/', trim($this->uri, '/')) : [];

        // Clean uris
        foreach ($this->uris as $key => $value) {
            if ($value == '') {
                unset($this->uris[$key]);
            }
        }

        $this->uris = array_merge($this->uris);

        $this->controller = $this->getController();
        $this->action = $this->getAction();

        // If is already initialized
        $prefix = Container::get('config')->get('namespace_prefix');

        $controllerClassName = $prefix . 'controllers\\' . $this->controller;

        Middleware::register('before_controller');

        if (isset($this->controllers[$this->controller])) {
            $class = $this->controllers[$this->controller];
        } else {
            $constructInstances = $this->getMethodInstances($controllerClassName);
            if (!$constructInstances) {
                $class = new $controllerClassName();
            } else {
                $reflect = new ReflectionClass($controllerClassName);
                $class = $reflect->newInstanceArgs($constructInstances);
            }

            $this->controllers[$this->controller] = $class;
        }

        Middleware::register('after_controller');

        if (!class_exists($controllerClassName)) {
            throw new NotFoundException('Request Controller ' . $this->controller . ' is not Found.');
        }

        if (!method_exists($class, $this->action)) {
            throw new NotFoundException('Request Action ' . $this->action . ' is not Found.');
        }

        $callback = [$class, $this->action];
        if (!is_callable($callback)) {
            throw new NotFoundException($controllerClassName . '::' . $this->action . '() is not callable');
        }

        // Parse params from uri
        $this->params = $this->getParams();

        // Do some final cleaning of the params
        $_GET = array_merge($this->params, $_GET);
        $_REQUEST = array_merge($_POST, $_GET, $_COOKIE);

        if (Container::get('config')->get('app_debug')) {
            Container::get('response')->setHeader('X-Kotori-Hash', call_user_func(function () {
                $lockFile = Helper::getComposerVendorPath() . '/../composer.lock';
                if (!Helper::isFile($lockFile)) {
                    return 'unknown';
                } else {
                    $lockData = file_get_contents($lockFile);
                    $lockData = json_decode($lockData, true);
                    foreach ($lockData['packages'] as $package) {
                        if ($package['name'] == 'kokororin/kotori-php') {
                            return substr($package['source']['reference'], 0, 6);
                        }
                    }
                }

                return 'unknown';
            }));
        }

        Middleware::register('before_action');
        // Call the requested method

        $methodInstances = $this->getMethodInstances($callback[0], $callback[1]);
        if (!$methodInstances) {
            $output = call_user_func_array($callback, $this->params);
        } else {
            $output = call_user_func_array($callback, $methodInstances);
        }

        Middleware::register('after_action');
        if (is_array($output)) {
            Container::get('response')->throwJSON($output);
        }
    }
327278
public function run()
    {
        $this->tryAssignController();
        if (!$this->isControllerAssigned()) {
            throw new Exception("It's unable to assign controller to this route path.");
        }
        $oCtrl = $this->createCtrl();
        $oCtrl->{$this->actionName}($this->actionArgs);
    }
792414
public static function start() {
    	$controller = (self::$route->module).'Controller';
    	$view = (self::$route->module).'View';
    	$model = (self::$route->module).'Model';
        $action = (self::$route->action).'Action';

        $module_root = MODULES_ROOT.'/'.self::$route->module;

        switch (true) {
			case (file_exists($module_root) &&
				 file_exists($module_root."/$model.php") &&
				 file_exists($module_root."/$view.php") &&
				 file_exists($module_root."/$controller.php")):
				$namespace = self::$route->module;

				if (class_exists("Module\\$namespace\\$controller")) {
					$app_controller = "Module\\$namespace\\$controller";
					$AppController = new $app_controller();
				} else {
					throw MvcException::UndefinedModule(self::$route->module);
				}

				if (method_exists($AppController, $action)) { $content = $AppController->$action(); } else {
					throw MvcException::UndefinedMethodInController($action, get_class($AppController));
				}
				break;

			default: throw MvcException::UndefinedModule(self::$route->module); break;
		}

        self::setContent($content);
    }
775791
public function runApplication()
    {
        $routeCollection = $this->createRouteCollection();
        $dispatcher = $routeCollection->getDispatcher();

        $request = $this->createRequest();
        $response = $dispatcher->dispatch($request->getMethod(), $request->getPathInfo());
        $response->send();
    }
324956
public function startExceptionHandling()
    {
        $this['exception']->register($this->environment());

        //
        $debug = $this['config']['app.debug'];

        $this['exception']->setDebug($debug);
    }
389641
public static function dispatch()
    {
        $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        $method = $_SERVER['REQUEST_METHOD'];

        $searches = array_keys(static::$patterns);
        $replaces = array_values(static::$patterns);

        $found_route = false;

        self::$routes = preg_replace('/\/+/', '/', self::$routes);

        // Check if route is defined without regex
        if (in_array($uri, self::$routes)) {
            $route_pos = array_keys(self::$routes, $uri);
            foreach ($route_pos as $route) {

                // Using an ANY option to match both GET and POST requests
                if (self::$methods[$route] == $method || self::$methods[$route] == 'ANY' || in_array($method, self::$maps[$route])) {
                    $found_route = true;

                    // If route is not an object
                    if (!is_object(self::$callbacks[$route])) {

                        // Grab all parts based on a / separator
                        $parts = explode('/', self::$callbacks[$route]);

                        // Collect the last index of the array
                        $last = end($parts);

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

                        // Instanitate controller
                        $controller = new $segments[0]();

                        // Call method
                        $controller->{$segments[1]}();

                        if (self::$halts) return;
                    } else {
                        // Call closure
                        call_user_func(self::$callbacks[$route]);

                        if (self::$halts) return;
                    }
                }
            }
        } else {
            // Check if defined with regex
            $pos = 0;
            foreach (self::$routes as $route) {
                if (strpos($route, ':') !== false) {
                    $route = str_replace($searches, $replaces, $route);
                }

                if (preg_match('#^' . $route . '$#', $uri, $matched)) {
                    if (self::$methods[$pos] == $method || self::$methods[$pos] == 'ANY' || in_array($method, self::$maps[$pos])) {
                        $found_route = true;

                        // Remove $matched[0] as [1] is the first parameter.
                        array_shift($matched);

                        if (!is_object(self::$callbacks[$pos])) {

                            // Grab all parts based on a / separator
                            $parts = explode('/', self::$callbacks[$pos]);

                            // Collect the last index of the array
                            $last = end($parts);

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

                            // Instanitate controller
                            $controller = new $segments[0]();

                            // Fix multi parameters
                            if (!method_exists($controller, $segments[1])) {
                                echo "controller and action not found";
                            } else {
                                call_user_func_array(array($controller, $segments[1]), $matched);
                            }

                            if (self::$halts) return;
                        } else {
                            call_user_func_array(self::$callbacks[$pos], $matched);

                            if (self::$halts) return;
                        }
                    }
                }
                $pos++;
            }
        }

        // Run the error callback if the route was not found
        if ($found_route == false) {
            if (!self::$error_callback) {
                self::$error_callback = function () {
                    header($_SERVER['SERVER_PROTOCOL'] . " 404 Not Found");
                    throw new \Exception(Config::get('error_message'));
                };
            } else {
                if (is_string(self::$error_callback)) {
                    self::get($_SERVER['REQUEST_URI'], self::$error_callback);
                    self::$error_callback = null;
                    self::dispatch();
                    return;
                }
            }
            call_user_func(self::$error_callback);
        }
    }
1253622
public function dispatch() {
		while (true) {
			if ($this->_break) {
				break;
			}
			if ($this->_paused) {
				$this->_title('Paused, waiting');
				$this->_log->debug('Paused, waiting.');
			}
			while ($this->_paused) {
				pcntl_signal_dispatch();
				sleep($this->_interval);
			}

			$this->_title('Waiting for job');
			$this->_log->debug('Waiting for job.');

			while (!$this->_job) {
				// FIXME Catch exception. but only handler exceptions.
				$this->_job = $this->_connection->reserve($this->_queues, 5);
				pcntl_signal_dispatch();
			}
			$this->_title("Performing job {$this->_job}");
			$this->_log->debug("Performing job {$this->_job}.");

			try {
				if ($this->_job->perform()) {
					$this->_job->succeed();
				} else {
					$this->_job->fail();
				}
			} catch (Exception $e) {
				$this->_log->notice(get_class($e) . ' while performing job: ' . $e->getMessage());
				$this->_job->fail();
			}
			$this->_job = null;
		}
	}
1371945
public function launch()
    {
        foreach($this->getServers() as $server)
        {
            $server = $this->getContainer()->get($server);
            if (!$server)
            {
                throw new \Exception("Unable to find Server Service.");
            }

            if (!($server instanceof ServerTypeInterface))
            {
                throw new \Exception("Server Service must implement ServerTypeInterface");
            }

            if ($this->getOutput())
            {
                $this->getOutput()->writeln("Launching " . $server->getName() . " on: " . $server->getAddress());
            }
            //launch server into background process?
            $server->launch();
        }
    }
1294699
public function launching()
    {
        /**
         * registering default commands
         */
        $this->with([self::PROVIDES_SERVICE], function (IBladedManager $manager) {
            $manager->registerCommandNamespace('scope', Scope::class);
            \phpQuery::newDocument();
            $manager->registerCommandNamespace('form', Form::class);
            $manager->registerCommandNamespace('template', Template::class);
        });
    }
859662
public function start()
    {
        if (false === ($this->socket = @socket_create(AF_INET, SOCK_STREAM, getprotobyname($this->config['protocol'])))) {
            throw new Exception(sprintf('socket_create(AF_INET, SOCK_STREAM, <%s>) failed: [%d] %s',
                $this->config['protocol'], $code = socket_last_error(), socket_strerror($code)));
        }

        if (false === @socket_bind($this->socket, $this->config['ip'], $this->config['port'])) {
            throw new Exception(sprintf('socket_bind($socket, "%s", %d) failed: [%d] %s',
                $this->config['ip'], $this->config['port'], $code = socket_last_error(), socket_strerror($code)));
        }

        if (false === @socket_getsockname($this->socket, $this->config['ip'], $this->config['port'])) {
            throw new Exception(sprintf('socket_getsockname($socket, "%s", %d) failed: [%d] %s',
                $this->config['ip'], $this->config['port'], $code = socket_last_error(), socket_strerror($code)));
        }

        if (false === @socket_listen($this->socket)) {
            throw new Exception(sprintf('socket_listen($socket) failed: [%d] %s', $code = socket_last_error(), socket_strerror($code)));
        }

        $this->started = true;

        $this->log('Listening for connections on <pop>'.$this.'</pop>', Logger::INFO);
    }