Generates a controller, view, and sets the instance up.

@param string $controllerName
@param string $instanceName
@param string $namespace
@param string $injectLogger
@param string $injectTemplate
@param array  $actions
346459
public function generate(MoufManager $moufManager, $controllerName, $instanceName, $namespace, $injectLogger = false,
                             $injectTemplate = false, $actions = array())
    {
        $namespace = rtrim($namespace, '\\').'\\';

        $classNameMapper = ClassNameMapper::createFromComposerFile(__DIR__.'/../../../../../../../../composer.json');
        $possibleFileNames = $classNameMapper->getPossibleFileNames($namespace.$controllerName);
        if (!isset($possibleFileNames[0])) {
            throw new SplashException("The class '".$namespace.$controllerName."' cannot be loaded using rules defined in composer autoload section");
        }
        $fileName = $possibleFileNames[0];
        $controllerPhpDirectory = dirname($fileName);
        $errors = array();
        if (!preg_match('/^[a-z_]\w*$/i', $controllerName)) {
            $errors['controllerNameError'] = 'This is not a valid PHP class name.';
        }
        if (!preg_match('/^[a-z_][\w\\\\]*$/i', $namespace)) {
            $errors['namespaceError'] = 'This is not a valid PHP namespace.';
        }

        $namespace = trim($namespace, '\\');

        // Check that instance does not already exists
        if ($moufManager->has($instanceName)) {
            $errors['instanceError'] = 'This instance already exists.';
        }

        $injectTwig = false;
        $importJsonResponse = false;
        $importHtmlResponse = false;
        $importRedirectResponse = false;

        foreach ($actions as $key => $action) {
            // Check if the view file exists
            if ($injectTemplate && $action['view'] == 'twig') {
                $injectTwig = true;
                $importHtmlResponse = true;
                $twigFile = ltrim($action['twigFile'], '/\\');

                $viewDirName = ROOT_PATH.'../../../'.dirname($twigFile);
                $result = $this->createDirectory($viewDirName);
                if (!$result) {
                    $errors['actions'][$key]['twigTemplateFileError'] = 'Unable to create directory "'.$viewDirName.'"';
                }
            }
            if ($injectTemplate && $action['view'] == 'php') {
                $importHtmlResponse = true;

                $phpFile = ltrim($action['phpFile'], '/\\');

                $viewDirName = ROOT_PATH.'../../../'.dirname($phpFile);
                $result = $this->createDirectory($viewDirName);
                if (!$result) {
                    $errors['actions'][$key]['phpTemplateFileError'] = 'Unable to create directory "'.$viewDirName.'"';
                }
            }
            if ($action['view'] == 'redirect') {
                if (!isset($action['redirect']) || empty($action['redirect'])) {
                    $errors['actions'][$key]['redirectError'] = 'Redirection URL cannot be empty.';
                }
                $importRedirectResponse = true;
            }
            if ($action['view'] == 'json') {
                $importJsonResponse = true;
            }
        }

        // TODO: check that URLs are not in error.


        if (!$errors) {
            $result = $this->createDirectory(ROOT_PATH.'../../../'.$controllerPhpDirectory);
            if (!$result) {
                $errors['namespaceError'] = 'Unable to create directory: "'.$controllerPhpDirectory.'"';
            } elseif (file_exists(ROOT_PATH.'../../../'.$controllerPhpDirectory.$controllerName.'.php')) {
                $errors['namespaceError'] = 'The file "'.$controllerPhpDirectory.$controllerName.'.php already exists."';
            } elseif (!is_writable(ROOT_PATH.'../../../'.$controllerPhpDirectory)) {
                $errors['namespaceError'] = 'Unable to write file in directory: "'.$controllerPhpDirectory.'"';
            }

            if (!$errors) {
                ob_start();
                echo '<?php
';
                ?>
namespace <?= $namespace ?>;

use TheCodingMachine\Splash\Annotations\Get;
use TheCodingMachine\Splash\Annotations\Post;
use TheCodingMachine\Splash\Annotations\Put;
use TheCodingMachine\Splash\Annotations\Delete;
use TheCodingMachine\Splash\Annotations\URL;
<?php if ($injectTemplate) {
    ?>
use Mouf\Html\Template\TemplateInterface;
use Mouf\Html\HtmlElement\HtmlBlock;
<?php

}
                ?>
<?php if ($injectLogger) {
    ?>
use Psr\Log\LoggerInterface;
<?php
}
?>
use Psr\Http\Message\ResponseInterface;
<?php if ($injectTwig) {
    ?>
use \Twig_Environment;
use Mouf\Html\Renderer\Twig\TwigTemplate;
<?php

}
                ?>
<?php if ($importJsonResponse) {
    ?>
use Zend\Diactoros\Response\JsonResponse;
<?php

}
                ?>
<?php if ($importRedirectResponse) {
    ?>
use Zend\Diactoros\Response\RedirectResponse;
<?php

}
                ?>
<?php if ($importHtmlResponse) {
    ?>
use Mouf\Mvc\Splash\HtmlResponse;
<?php

}
                ?>

/**
 * TODO: write controller comment
 */
class <?= $controllerName ?> {

<?php if ($injectLogger) {
    ?>
    /**
     * The logger used by this controller.
     * @var LoggerInterface
     */
    private $logger;

<?php

}
                ?>
<?php if ($injectTemplate) {
    ?>
    /**
     * The template used by this controller.
     * @var TemplateInterface
     */
    private $template;

    /**
     * The main content block of the page.
     * @var HtmlBlock
     */
    private $content;

<?php

}
                ?>
<?php if ($injectTwig) {
    ?>
    /**
     * The Twig environment (used to render Twig templates).
     * @var Twig_Environment
     */
    private $twig;

<?php

}
                ?>

    /**
     * Controller's constructor.
<?php
if ($injectLogger) {
    echo "     * @param LoggerInterface \$logger The logger\n";
}
                if ($injectTemplate) {
                    echo "     * @param TemplateInterface \$template The template used by this controller\n";
                    echo "     * @param HtmlBlock \$content The main content block of the page\n";
                }
                if ($injectTwig) {
                    echo "     * @param Twig_Environment \$twig The Twig environment (used to render Twig templates)\n";
                }
                ?>
     */
    public function __construct(<?php
$parameters = array();
                if ($injectLogger) {
                    $parameters[] = 'LoggerInterface $logger';
                }
                if ($injectTemplate) {
                    $parameters[] = 'TemplateInterface $template';
                    $parameters[] = 'HtmlBlock $content';
                }
                if ($injectTwig) {
                    $parameters[] = 'Twig_Environment $twig';
                }
                echo implode(', ', $parameters);
                ?>) {
<?php if ($injectLogger) {
    ?>
        $this->logger = $logger;
<?php

}
                if ($injectTemplate) {
                    ?>
        $this->template = $template;
        $this->content = $content;
<?php

                }
                if ($injectTwig) {
                    ?>
        $this->twig = $twig;
<?php

                }
                ?>
    }

<?php foreach ($actions as $action):


?>
    /**
     * @URL("<?= addslashes($action['url']) ?>")
<?php if ($action['anyMethod'] == 'false') {
    if ($action['getMethod'] == 'true') {
        echo "     * @Get\n";
    }
    if ($action['postMethod'] == 'true') {
        echo "     * @Post\n";
    }
    if ($action['putMethod'] == 'true') {
        echo "     * @Put\n";
    }
    if ($action['deleteMethod'] == 'true') {
        echo "     * @Delete\n";
    }
}
                    // let's detect the {parameters} in the URL and add them if necessary
                if (isset($action['parameters'])) {
                    $parameters = $action['parameters'];
                    foreach ($parameters as $parameter) {
                        echo '     * @param '.$parameter['type'].' $'.$parameter['name']."\n";
                    }
                } else {
                    $parameters = array();
                }
                ?>
     */
    public function <?= $action['method'] ?>(<?php
$parametersCode = array();
                foreach ($parameters as $parameter) {
                    $parameterCode = '$'.$parameter['name'];
                    if ($parameter['optionnal'] == 'true') {
                        if ($parameter['type'] == 'int') {
                            $defaultValue = (int) $parameter['defaultValue'];
                        } elseif ($parameter['type'] == 'number') {
                            $defaultValue = (float) $parameter['defaultValue'];
                        } else {
                            $defaultValue = $parameter['defaultValue'];
                        }
                        $parameterCode .= ' = '.var_export($defaultValue, true);
                    }
                    $parametersCode[] = $parameterCode;
                }
                echo implode(', ', $parametersCode);
                ?>): ResponseInterface {
        // TODO: write content of action here

<?php if ($injectTemplate && $action['view'] == 'twig'): ?>
        // Let's add the twig file to the template.
        $this->content->addHtmlElement(new TwigTemplate($this->twig, <?php var_export($action['twigFile']);
                ?>, array("message"=>"world")));

        return new HtmlResponse($this->template);
<?php elseif ($injectTemplate && $action['view'] == 'php'): ?>
        // Let's add the view to the content.
        // Note: $this is passed as the scope, so in the view file, you can refer to protected
        // and public variables and methods of this constructor using "$this".
        $this->content->addFile(ROOT_PATH.<?php var_export($action['phpFile']) ?>, $this);

        return new HtmlResponse($this->template);
<?php elseif ($action['view'] == 'json'): ?>

        return new JsonResponse([ "status"=>"ok" ]);
<?php elseif ($action['view'] == 'redirect'): ?>

        return new RedirectResponse(<?php var_export($action['redirect']);
                ?>);
<?php endif;
                ?>
    }
<?php endforeach;
                ?>
}
<?php
                $file = ob_get_clean();

                file_put_contents(ROOT_PATH.'../../../'.$fileName, $file);
                chmod(ROOT_PATH.'../../../'.$fileName, 0664);

                // Now, let's create the views files
                foreach ($actions as $action) {
                    if ($injectTemplate && $action['view'] == 'twig') {
                        $twigFile = ltrim($action['twigFile'], '/\\');
                        if(!file_exists(ROOT_PATH.'../../../'.$twigFile)) {
                            $twigTemplateFile = $this->generateTwigView();
                            file_put_contents(ROOT_PATH.'../../../'.$twigFile, $twigTemplateFile);
                            chmod(ROOT_PATH.'../../../'.$twigFile, 0664);
                        }

                    } elseif ($injectTemplate && $action['view'] == 'php') {
                        $phpFile = ltrim($action['phpFile'], '/\\');
                        if(!file_exists(ROOT_PATH.'../../../'.$phpFile)) {
                            $phpTemplateFile = $this->generatePhpView($namespace.'\\'.$controllerName);
                            file_put_contents(ROOT_PATH.'../../../'.$phpFile, $phpTemplateFile);
                            chmod(ROOT_PATH.'../../../'.$phpFile, 0664);
                        }
                    }
                }

                // Now, let's create the instance
                $controllerInstance = $moufManager->createInstance($namespace.'\\'.$controllerName);
                $controllerInstance->setName($instanceName);
                if ($injectLogger) {
                    if ($moufManager->has('psr.errorLogLogger')) {
                        $controllerInstance->getProperty('logger')->setValue($moufManager->getInstanceDescriptor('psr.errorLogLogger'));
                    }
                }
                if ($injectTemplate) {
                    if ($moufManager->has('bootstrapTemplate')) {
                        $controllerInstance->getProperty('template')->setValue($moufManager->getInstanceDescriptor('bootstrapTemplate'));
                    }
                    if ($moufManager->has('block.content')) {
                        $controllerInstance->getProperty('content')->setValue($moufManager->getInstanceDescriptor('block.content'));
                    }
                }
                if ($injectTwig) {
                    if ($moufManager->has('twigEnvironment')) {
                        $controllerInstance->getProperty('twig')->setValue($moufManager->getInstanceDescriptor('twigEnvironment'));
                    }
                }

                $moufManager->rewriteMouf();

                // There is a new class, let's purge the cache
                $moufCache = new MoufCache();
                $moufCache->purgeAll();

                // TODO: purge cache
            }
        }

        if ($errors) {
            $exception = new SplashCreateControllerServiceException('Errors detected : '.var_export($errors, true));
            $exception->setErrors($errors);
            throw $exception;
        }
    }
999869
protected function execPageAction($actionName, $parameters)
    {
        $result = null;

        if (!$this->actionExists($actionName)) {
            if (Config::get('app.debug', false)) {
                throw new SystemException(sprintf(
                    "Action %s is not found in the controller %s",
                    $actionName,
                    get_class($this)
                ));
            } else {
                Response::make(View::make('backend::404'), 404);
            }
        }

        // Execute the action
        $result = call_user_func_array([$this, $actionName], $parameters);

        // Expecting \Response and \RedirectResponse
        if ($result instanceof \Symfony\Component\HttpFoundation\Response) {
            return $result;
        }

        // No page title
        if (!$this->pageTitle) {
            $this->pageTitle = 'backend::lang.page.untitled';
        }

        // Load the view
        if (!$this->suppressView && $result === null) {
            return $this->makeView($actionName);
        }

        return $this->makeViewContent($result);
    }
875005
private function _createInstance($namespace, $class, $params, $method_name, $data)
    {
        $ns_class = $namespace . $class;

        //create a reflection class so that we can pass parameters to the constructor

        $ref_class = new \ReflectionClass($ns_class);

        if (is_array($params) && sizeof($params) > 0) {

            $instance = $ref_class->newInstanceArgs($params);

        } else {

            $instance = new $ns_class();
        }
        
        $this->logger->info("$namespace object created for $class class");
   
        //call the method along with parameters, if they exist !
        if (method_exists($instance, $method_name))
        {
            if(is_callable(array($instance, $method_name)))
            {
                $last_hook = $this->loading[count($this->loading) - 1];
                $this->loaderHooks($instance,"pre_$last_hook",$class,$method_name,$data);
                call_user_func_array(array($instance, $method_name), $data);
                $this->loaderHooks($instance,"post_$last_hook",$class,$method_name,$data);
            }
        }elseif(is_object($instance)) 
        {
            $last_hook = $this->loading[count($this->loading) - 1];
            $this->loaderHooks($instance,"pre_$last_hook",$class,$method_name,$data);
        }
        else if(strpos($namespace,'controller') > 0)
        {
            header("HTTP/1.0 404 Not Found");
            Base::getInstance()->hook('404',array(
                'file' => $ref_class,
                'controller' => $class,
                'method' => $method_name,
                'message' => '404'
            ));
            die();
        }

        $this->clearCurrentLoader();

        return $instance;
    }
127662
public function onKernelController(FilterControllerEvent $event)
    {
        $request = $event->getRequest();

        if ($template = $this->getTemplate($request, $event->getController())) {
            $request->attributes->set('_template', $template);
        }
    }
1212054
@Override
    public Object invoke(Object controller, String action) throws Throwable {
        if(action == null) action = this.defaultActionName;
        ActionInvoker handle = actions.get(action);
        if(handle == null) throw new IllegalArgumentException("Invalid action name: " + action);
        return handle.invoke(controller);
    }
753175
private function methodInvoke($name, $namespace)
    {
        $name = ucfirst($name);

        $this->uses[] = $namespace . '\\' . $name;

        $namespace = '\\' . $namespace . '\\';

        $parameters = [
            new ParameterGenerator(
                'command', $namespace . $name
            ),
        ];

        return new MethodGenerator(
            '__invoke',
            $parameters,
            MethodGenerator::FLAG_PUBLIC,
            '',
            new DocBlockGenerator(
                'Handle command',
                null,
                [
                    new ParamTag('command', [ $namespace . $name]),
                ]
            )
        );
    }
516593
private static function execController($controller,$action,$args){
        $controller = new $controller();
        $controller->doAction($action,$args);
    }
989319
private function createController($name, $controllerFile, $module, $type, $author, $email)
    {
        $templateFile = __DIR__.DIRECTORY_SEPARATOR."templates".DIRECTORY_SEPARATOR."front_controller_".$type.".tpl";

        if (file_exists($templateFile)) {
            $template = file_get_contents(
                $templateFile
            );

            $template = str_replace('$name', $name, $template);
            $template = str_replace('$module',$module, $template);
            $template = str_replace('$author', $author, $template);
            $template = str_replace('$email', $email, $template);

            file_put_contents($controllerFile.'.js', $template);
        } else {
            throw new \Exception('Não foi encontrado template válido para o tipo de controlador type='.$type);
        }
    }
741006
public function onKernelController(FilterControllerEvent $event): void
    {
        $controller = $event->getController();
        if (\is_array($controller)) {
            [$controller] = $controller; // Ignoring action
        }
        if (!$controller instanceof AdminInjectableInterface && !$controller instanceof ActionInjectableInterface) {
            return;
        }

        $request = $event->getRequest();
        if (!$request->attributes->has('_admin')) {
            $routeName = $request->attributes->get('_route');

            $m = "Missing request attribute '_admin' for route {$routeName}, this means you declared";
            $m .= ' this route outside the admin configuration, please use the admin configuration';
            throw new \LogicException($m);
        }
        $admin = $request->attributes->get('_admin');
        if (!$admin instanceof Admin) {
            throw new \UnexpectedValueException('_admin request attribute is not an Admin object');
        }
        if ($controller instanceof AdminInjectableInterface) {
            $controller->setAdmin($admin);
        }

        if (!$request->attributes->has('_action')) {
            $routeName = $request->attributes->get('_route');

            $m = "Missing request attribute '_action' for route {$routeName},";
            $m .= 'this means you declared this route outside the admin configuration, please include the _action';
            $m .= 'attribute in your route definition or use the admin configuration';
            throw new \LogicException($m);
        }
        $admin->setCurrentAction($request->attributes->get('_action'));
        if ($controller instanceof ActionInjectableInterface) {
            $controller->setAction($admin->getCurrentAction());
        }
    }
1130222
private void injectController(AppController controller) {
        Injector injector = Configuration.getInjector();
        if (injector != null) {
            injector.injectMembers(controller);
        }
    }
17637
public function render($controllerName)
    {
        $controller = $this->getControllerName($controllerName);
        if (null === $controller) {
            throw new ControllerNotFoundException(sprintf('Could not find controller "%s".', $controllerName));
        }

        $route = $this->getRoute($controller);
        if (null === $route) {
            throw new RouteNotFoundException(sprintf('Could not find route for controller "%s".', $controllerName));
        }

        $this->routeRenderer->render($route[1], $route[0]);
    }
101238
public function setController($name, $controller=null)
	{
	    if ($name instanceof Controller) {
	        $controller = $name;
	        $sname = $controller->getName();
	    } elseif ($controller instanceof Controller) {
	        $sname = $name && !is_numeric($name) ? $name : $controller->getName();
	    } else {
	        if ($controller) {
	            $class_name = Ioc::findClass($controller, 'controller');
	        } else {
	            $class_name = Ioc::findClass($name, 'controller');
	        }
	        
	        if ($class_name && is_subclass_of($class_name, "\\Wslim\\Console\\Controller")) {
	            $sname = is_numeric($name) ? null : $name;
	            $controller =  new $class_name($sname);
	            if (!$sname) {
	                $sname = $controller->getName();
	            }
	        } else {
	            throw new \LogicException(sprintf('Controller class "%s" is not exists.', $controller));
	        }
	    }
	    
	    if (!$controller->isEnabled()) {
	        return;
	    }
	    
	    if (null === $controller->getDefinition()) {
	        throw new \LogicException(sprintf('Controller class "%s" is not correctly initialized. You probably forgot to call the parent constructor.', get_class($controller)));
	    }
	    
	    $this->controllers[$sname] = $controller;
	    
	    foreach ($controller->getAliases() as $alias) {
	        $this->controllers[$alias] = $controller;
	    }
	    
	    return $controller;
	}
1320324
public function lookupController(N2nContext $n2nContext, ControllerContext $delegateControllerContext): Controller {
		$manageState = $n2nContext->lookup(ManageState::class);
		CastUtils::assertTrue($manageState instanceof ManageState);
		$loginContext = $n2nContext->lookup(LoginContext::class);
		CastUtils::assertTrue($loginContext instanceof LoginContext);
		$rocket = $n2nContext->lookup(Rocket::class);
		CastUtils::assertTrue($rocket instanceof Rocket);
		
		$em = $this->eiMask->getEiType()->lookupEntityManager($n2nContext->lookup(PdoPool::class));
		$manageState->setEntityManager($em);
		$manageState->setDraftManager($rocket->getOrCreateDraftManager($em));
		$manageState->setEiPermissionManager($loginContext->getSecurityManager()->getEiPermissionManager());
		
		$eiLifecycleMonitor = new EiLifecycleMonitor($rocket->getSpec());
		$eiLifecycleMonitor->initialize($manageState->getEntityManager(), $manageState->getDraftManager(), $n2nContext);
		$manageState->setEiLifecycleMonitor($eiLifecycleMonitor);
		
		return new EiController($this->eiMask);
	}
250477
public function createController($resourceNamePlural)
    {
        if (isset($this->controllers[$resourceNamePlural]) == false) {
            throw new ControllerNotFoundException('the controller for "'.$resourceNamePlural.'" does not exist');
        }

        $controller = $this->createNew($this->controllers[$resourceNamePlural]);

        if (!$controller instanceof BaseController) {
            throw new InvalidControllerException('the controller "'.$this->controllers[$resourceNamePlural].'"" is not an instance of BaseController');
        }

        return $controller;
    }
342773
public function instanceController(): Controller
    {
        $this->sawContainer->setEnvironment(SawEnv::controller());

        return new Controller(
            $this->container->get('WorkCycle'),
            $this->container->get(ControllerCore::class),
            $this->container->get('ControllerServer'),
            $this->container->get(CommandDispatcher::class),
            $this->daemonConfig->getControllerPid() // todo
        );
    }
984696
public function onKernelController(FilterControllerEvent $event)
    {
        $controller = $event->getController();

        if (!is_array($controller)) {
            return;
        }

        if ($controller[0] instanceof ResourceControllerInterface
            || $controller[0] instanceof DashboardController) {
            $this->aclOperator->loadAcls();
        }
    }
1348808
public function generateController($group, $module, $model, $mode, $output, $file = "", $customTemplate = "")
    {
        $generator = new ControllerGenerator($group, $module, $model, $mode, $output, $file, $customTemplate);
        $generator->run();
    }