Run a console script

@param string		$controller
@param string		$action
@param array 		$params
6971
public static function run( $controller, $action = null, $params = array() ) 
	{
		// always enable the file infos
		// this allows CCFile to print an info when a file gets created or deleted.
		CCFile::enable_infos();

		// execute by default the help action
		if ( empty( $action ) ) 
		{
			$action = 'default';
		} 
		
		$path = CCPath::get( $controller, CCDIR_CONSOLE, EXT );
		
		// check if the file exists, if not try with core path
		if ( !file_exists( $path ) ) 
		{
			if ( !CCPath::contains_namespace( $controller ) ) 
			{
				$path = CCPath::get( CCCORE_NAMESPACE.'::'.$controller, CCDIR_CONSOLE, EXT );
			}
		}
		
		// still nothing?
		if ( !file_exists( $path ) ) 
		{
			CCCli::line( "Could not find controller {$controller}.", 'red' );
			return false;
		}
		
		// all console classes should be on the CCConsole namespace
		// this way you can easly overwrite a console script
		$class = 'CCConsole\\'.$controller;
		
		// add the class to the autoloader 
		\CCFinder::bind( $class, $path );
		
		// create an instance
		$class = new $class( $action, $params );
		
		// run wake function
		if ( method_exists( $class, 'wake' ) )
		{
			call_user_func( array( $class, 'wake' ), $params );
		}
		
		// run the execution
		call_user_func( array( $class, '_execute' ), $action, $params );
		
		// run sleep
		if ( method_exists( $class, 'sleep' ) ) 
		{
			call_user_func( array( $class, 'sleep' ), $params );
		}
	}
422493
public static function redirectTo($module, $controller = 'index', array $params = []): void
    {
        $url = Router::getFullUrl($module, $controller, $params);
        self::redirect($url);
    }
1372677
public function hasAction($controller, $action = null)
    {
        if ($action === null) {
            list($controller, $action) = explode('.', $controller);
        }
        return in_array("{$controller}.{$action}", $this->action_names);
    }
1234223
protected function fire($action, $params)
    {
        if(!isset($this->events[$action])){
            throw new HandlerException('Action handler not exists', HandlerException::ACTION_HANDLER_NOT_EXISTS);
        }

        // prepare params array for handler
        // we provide a client library as a param for further requests
        $callbackParams = $params;
        $callbackParams['client'] = $this->getClient();
        $callbackParams = new \ArrayObject($callbackParams, \ArrayObject::STD_PROP_LIST);

        // fire handlers for every event
        foreach($this->events[$action] as $e){
            $result = call_user_func($e, $callbackParams);
            if(!$result){
                break;
            }
        }

    }
961438
public function setAction(Controller $controller, $action = 'execute')
    {
        $this->controller = $controller;
        $this->action = $action;
    }
516593
private static function execController($controller,$action,$args){
        $controller = new $controller();
        $controller->doAction($action,$args);
    }
1043074
public function invoke($controller, $command)
    {
        $commandMethod = $command . 'Command';

        if (!method_exists($controller, $commandMethod)) {
            throw new NotFoundException([
                '`:controller:::action` is not found',
                'action' => $commandMethod,
                'controller' => get_class($controller)
            ]);
        }

        $args = $this->_buildArgs($controller, $command);

        switch (count($args)) {
            case 0:
                $r = $controller->$commandMethod();
                break;
            case 1:
                $r = $controller->$commandMethod($args[0]);
                break;
            default:
                $r = call_user_func_array([$controller, $commandMethod], $args);
                break;
        }

        return $r;
    }
308947
public function run() {
        $this->_hookManager->runBeforeSystem();

        $urlArray = explode('/', $this->_url);
        //Deletes last element if empty
        $lastElement = end($urlArray);
        if ($lastElement == '') {
            array_pop($urlArray);
        }
        reset($urlArray);

        // If present take the first element as the controller
        $tmpController = isset($urlArray[0]) ? array_shift($urlArray) : 'index';
        $action = null;

        //Prepare the GET params in order to pass them to the Controller
        $myGet = $_GET;
        if(isset($myGet['url'])){
            unset($myGet['url']);
        }

        if ($this->applyStaticRouting($tmpController)) {
            $this->_hookManager->runBefore(); // Runs before controller hooks
            include(ROOT . DS . $tmpController);
            $this->_hookManager->runAfter(); // Runs after controller hooks
        } elseif ($this->applyRouting($tmpController, $action, $urlArray)) {
            ($action === null) ? $action = 'index' : $action;
            $tmpController = '\\pff\\controllers\\'.$tmpController;
            $controller = new $tmpController($tmpController, $this, $action, array_merge($urlArray,$myGet));
        } elseif (file_exists(ROOT . DS . 'app' . DS . 'controllers' . DS . ucfirst($tmpController) . '_Controller.php')) {
            $action = isset($urlArray[0]) ? array_shift($urlArray) : 'index';
            $controllerClassName = '\\pff\\controllers\\'.ucfirst($tmpController) . '_Controller';
            $controller          = new $controllerClassName($tmpController, $this, $action, array_merge($urlArray,$myGet));
        } else {
            throw new RoutingException('Cannot find a valid controller.', 404);
        }

        if (isset($controller)) {
            $this->_action = $action;
            $this->_moduleManager->setController($controller); // We have a controller, let the modules know about it
            ob_start();
            $this->_hookManager->runBefore(); // Runs before controller hooks
            if ((int)method_exists($controller, $this->_action)) {
                call_user_func_array(array($controller, "beforeAction"), $urlArray);
                call_user_func(array($controller, "beforeFilter"));
                call_user_func_array(array($controller, $this->_action), $urlArray);
                call_user_func(array($controller, "afterFilter"));
                call_user_func_array(array($controller, "afterAction"), $urlArray);
                $this->_hookManager->runAfter(); // Runs after controller hooks
                ob_end_flush();
            } else {
                throw new RoutingException('Not a valid action: ' . $action, 404);
            }
        }
    }
535339
public static function execute($controller, $request) {   
        switch($request->method()) { 
            case 'POST':
                $data = $controller->store($request->bodyRequest());
                KernelHttp::makeResponse('201', $data);
                break;
            case 'PUT':
                $data = $controller->update($request->bodyRequest());
                KernelHttp::makeResponse('200', $data);
                break;
            case 'DELETE':
                $controller->destroy($request->getInteractionsRequest());
                KernelHttp::makeResponse('200');
                break;
            default: 
                $request->getRequiredParameter() ? $data = $controller->show($request->getInteractionsRequest()) : $data = $controller->index($request->getInteractionsRequest()); 
                KernelHttp::makeResponse('200', $data);
                break;
        } 
    }
1219221
public function run()
    {
        $controller = "Controller\\".$this->controller;
        call_user_func_array(array($controller, $this->action), $this->params);
    }
516678
public function action_controller( $params ) 
	{	
		$options = \CCDataObject::assign( $params );
		
		$name = $options->get( 0, null );
		$parent = $options->get( 1, null );
		
		// get name if we dont have one
		while( !$name ) 
		{
			$name = $this->read( 'Please enter the controller name: ' );
		}
		
		// fix controller suffix
		if ( substr( $name, ( strlen( 'Controller' ) * -1 ) ) != 'Controller' )
		{
			$name .= 'Controller';
		}
		
		// try to resolve the path
		if ( !$path = \CCPath::controllers( str_replace( '_', '/', $name ), EXT ) )
		{
			$this->error( 'Could not resolve the path. Check if the namespace is registered.' ); return;
		}
		
		// parent
		if ( is_null( $parent ) )
		{
			$parent = '\\CCController';
		} 
		
		// view controller
		if ( $options->get( 'view', false ) )
		{
			$parent = '\\CCViewController';
		}
		
		// create the class
		$class = \CCShipyard::create( 'class', $name, $parent );
		
		// get the actions
		$actions = array( 'index' );
		
		if ( $options->get( 'actions', false ) )
		{
			$actions = array_merge( $actions, explode( ',', $options->get( 'actions' ) ) );
		}
		
		foreach( $actions as $action )
		{
			$action = trim( $action );
			
			$class->add( 'function', 'action_'.$action, 'protected', 'echo "'.$name.' '.$action.' action";', ucfirst($action)." action\n@return void|CCResponse" );
			$class->add( 'line', 2 );
		}
		
		// add static init
		if ( !$options->get( 'no-events', false ) )
		{
			$class->add( 'function', 'wake', 'protected', '//', "Controller wake\n@return void|CCResponse" );
			$class->add( 'line', 2 );
			$class->add( 'function', 'sleep', 'protected', '//', "Controller wake\n@return void" );
		}
						
		// check for overwrite
		if ( file_exists( $path ) )
		{
			if ( !$this->confirm( "The class already exists. Do you wish to overwrite it?", true ) ) 
			{
				return;
			}
		}
		
		// write file
		\CCFile::write( $path, $class->output() );
	}
720442
protected function _buildActionArgs($controller, $action, $params)
    {
        $args = [];
        $missing = [];

        $di = $this->_di;

        $parameters = (new \ReflectionMethod($controller, $action . 'Action'))->getParameters();
        foreach ($parameters as $parameter) {
            $name = $parameter->getName();
            $value = null;

            $type = $parameter->getClass();
            if ($type !== null) {
                $type = $type->getName();
            } elseif ($parameter->isDefaultValueAvailable()) {
                $type = gettype($parameter->getDefaultValue());
            }

            if ($className = ($c = $parameter->getClass()) ? $c->getName() : null) {
                if ($di->has($name)) {
                    $value = $di->get($name);
                } elseif ($di->has($className)) {
                    $value = $di->get($className);
                } else {
                    $value = $di->getShared($className);
                }
            } elseif (isset($params[$name])) {
                $value = $params[$name];
            } elseif ($this->request->has($name)) {
                $value = $this->request->get($name);
            } elseif (count($params) === 1 && count($parameters) === 1) {
                $value = $params[0];
            } elseif ($parameter->isDefaultValueAvailable()) {
                $value = $parameter->getDefaultValue();
            }

            if ($value === null) {
                $missing[] = $name;
                continue;
            }

            switch ($type) {
                case 'boolean':
                    $value = (bool)$value;
                    break;
                case 'integer':
                    $value = (int)$value;
                    break;
                case 'double':
                    $value = (float)$value;
                    break;
                case 'string':
                    $value = (string)$value;
                    break;
                case 'array':
                    $value = (array)$value;
                    break;
            }

            if ($parameter->isArray()) {
                $args[] = (array)$value;
            } else {
                $args[] = $value;
            }
        }

        if ($missing) {
            throw new MissingRequiredFieldsException($missing);
        }

        return $args;
    }
7014
final protected function redirect($module, $controller = null, $action = null, array $params = array(), $hash = null) {
        header('Location: ' . $this->view->url($module, $controller, $action, $params, $hash));
        exit;
    }
609813
static function run($module_name = null, $controller_name = null, $action = null) {
        try {
            $request = self::getRequest();
            if (self::getConfig()->get('security.csrf_defender')) {
                if ($request->isPost()) {
                    $csrf_token = $request->getPost('_csrftoken');
                    if ($csrf_token != $request->getCookie('_csrftoken')) {
                        exit('CsrfToken Invalid!');
                    }
                } else {
                    if (!$request->hasCookie('_csrftoken')) {
                        setcookie('_csrftoken', \Hiano\Token\Token::generate('_csrftoken'), 0, '/');
                    }
                }
            }


            $module_name or $module_name = self::getModuleName(); // $request->getParameter('module');
            $controller_name or $controller_name = self::getControllerName(); // $request->getParameter('controller');
            $action or $action = self::getActionName(); // $request->getParameter('action');

            $app_path = realpath(HIANO_APP_PATH);
            $controller_dir = $app_path . '/Controller/';
            $view_dir = $app_path . '/View/';
            $module_main_file = $controller_dir . ucfirst($module_name) . '/main.php';
            if (file_exists($module_main_file)) {
                include $module_main_file;
            }

            $view = self::getView();

            $view->set('app', array(
                'parameter' => $request->getParameter(),
                'post' => $request->getPost(),
                'cookie' => $request->getCookie(),
                'session' => $_SESSION,
                'server' => $_SERVER,
                'csrf' => array(
                    'name' => '_csrftoken',
                    'value' => $request->getCookie('_csrftoken')
                )
            ));

            $tpl_dir = $view_dir . '/' . ucfirst($module_name) . '/' . ucfirst($controller_name);
            $view->addTemplateDir($view_dir);
            $view->addTemplateDir($tpl_dir);
            $view->setTemplate($action);


            $ctrl = self::getController($module_name, $controller_name, $request, $view);
            $filter_chain = new Filter\FilterChain(function() use ($ctrl, $view) {
                $action_ret = self::dispatchAction($ctrl, self::getActionName());
                if (is_array($action_ret)) {
                    echo json_encode($action_ret);
                } elseif (is_string($action_ret)) {
                    echo $action_ret;
                } elseif ($action_ret === TRUE or $action_ret === NULL) {
                    $view->display();
                } elseif ($action_ret === FALSE) {
                    //do nothing
                } else {
                    throw new \Exception('错误的动作返回值！');
                }
            });
            if ($filters = self::$filter) {
                $filter_count = count($filters);
                for ($i = 0; $i < $filter_count; $i++) {
                    $f = self::loadFilter($filters[$i]);
                    $filter_chain->addFilter($f);
                }
            }
            $filter_chain->execute();
        } catch (Controller\NoActionException $e) {
            self::forward404();
        } catch (Controller\NoControllerException $e) {
            self::forward404();
        } catch (Controller\NoModuleException $e) {
            self::forward404();
        } catch (\Hiano\RedirectException $e) {
            call_user_func(self::$redirect_handler, $e);
        } catch (StopException $e) {
            
        } catch (\Hiano\ErrorException $e) {
            call_user_func(self::$error_handler, $e);
        }
    }
875572
protected function _runFunction($action)
    {
        $controller = $this->_current['controller'];

        $path = $controller . '.' . $action . '.function';

        $function = Hash::get(self::$_data, $path);

        $this->_selected['action'] = $action;

        if ($function) {
            $function($this, $this->Controller);
        }
    }
377299
public function addAction($controller, $action = null)
    {
        if ($action === null) {
            list($controller, $action) = explode('.', $controller);
        }
        $this->actions[] = array(
            'controller' => null,
            'controller_name' => $controller,
            'action' => $action,
            'result' => null,
        );
        $this->action_names[] = "{$controller}.{$action}";
    }
146695
public function handleController(
        $controller, $action = null, array $params = null, $model = null
    ) {

        ! $model || $model = $this->modelFactory->create(null, $model);

        $this->setController(
            $this->controllerFactory->create($params, $controller, $model)
        );

        if (!is_null($action)) {
            $this->setControllerResult(
                $this->executeMethod($this->getController(), $action, $params, $model)
            );
        }
    }