Controller loader

This function is used to load and instantiate controllers

@param  string
@param  array
@param  boolean
@return object
193330
private function _load_controller($uri = '', $params = [], $return = false)
    {
        $router = &$this->_ci_get_component('router');

        // Back up current router values (before loading new controller)
        $backup = [];
        foreach (['directory', 'class', 'method', 'module'] as $prop) {
            if ($prop == 'module') {
                $prop = $this->module->getCurrent();
            }
            $backup[$prop] = $router->{$prop};
        }

        // Locate the controller
        $segments = $router->locate(explode('/', $uri));
        $class    = isset($segments[0]) ? $segments[0] : false;
        $method   = isset($segments[1]) ? $segments[1] : "index";

        // Controller not found
        if (!$class) {
            return;
        }

        if (!array_key_exists(strtolower($class), $this->_ci_controllers)) {
            // Determine filepath
            $filepath = APPPATH . 'controllers/' . $router->fetch_directory() . $class . '.php';
            // Load the controller file
            if (file_exists($filepath)) {
                include_once $filepath;
            }
            // Controller class not found, show 404
            if (!class_exists($class)) {
                show_404("{$class}/{$method}");
            }
            // Create a controller object
            $this->_ci_controllers[strtolower($class)] = new $class();
        }

        $controller = $this->_ci_controllers[strtolower($class)];

        // Method does not exists
        if (!method_exists($controller, $method)) {
            show_404("{$class}/{$method}");
        }

        // Restore router state
        foreach ($backup as $prop => $value) {
            $router->{$prop} = $value;
        }

        // Capture output and return
        ob_start();
        $result = call_user_func_array([$controller, $method], $params);

        // Return the buffered output
        if ($return === true) {
            $buffer = ob_get_contents();
            @ob_end_clean();
            return $buffer;
        }

        // Close buffer and flush output to screen
        ob_end_flush();

        // Return controller return value
        return $result;
    }
276021
private function _loadExistingController()
    {
        $file = $this->_controllerPath.ucfirst($this->_url[0]).'.php';

        if (!file_exists($file)) {
            $this->_error();

            return false;
        }
        require $file;

        $namespace = str_replace('/', '\\', APP.'/Controllers/');
        $className = $namespace.$this->_url[0];

        $this->_controller = new $className();

        return true;
    }
988507
public function controllers(array $controllers)
    {
        $group = new Group;
        foreach ($controllers as $controller)
            $group->set($this->controller($controller));
        return $group;
    }
1372187
public function getController($matches = [])
    {

        if (!isset($this->route['controller'])) {
            return false;
        }
        $controller = $this->route['controller'];
        preg_match("/.+?(?=Controllers)(.*)@/", $controller, $matches);
        if (!isset($matches[1])) {
            return false;
        }
        return str_ireplace(['Controllers', 'Controller', '\\'], "", $matches[1]);
    }
70547
final public static function load_controller($backupid = false) {
        // Get the backup id optional param.
        if ($backupid) {
            try {
                // Try to load the controller with it.
                // If it fails at this point it is likely because this is the first load.
                $controller = backup_controller::load_controller($backupid);
                return $controller;
            } catch (Exception $e) {
                return false;
            }
        }
        return $backupid;
    }
133037
public function load($name = null, $configs = [])
	{
		$name = $name ?: $this->getDefaultDriver();

		$configs = array_merge($this->getDriverConfigs($name), $configs);

		return new Filesystem($this->resolveAdapter($configs['driver'], $configs));
	}
87773
public function controller($name)
	{
		if(isset($this->_controllers[$name]) && ($controller = $this->_controllers[$name]))
		{
			$name = is_callable($controller)
				? new CallbackController($controller)
				: $controller
				;

			if(is_object($name))
				return $name;
		}

		if($this->_resolver)
			return $this->_resolver->resolve($name);

		throw new LookupException("No controller defined for route '$name'");
	}
1138966
private function load($resource, string $type = null): array
    {
        if (null === $this->loader) {
            throw new \BadMethodCallException('Cannot import other routing resources: you must pass a LoaderInterface when constructing RouteCollectionBuilder.');
        }

        if ($this->loader->supports($resource, $type)) {
            $collections = $this->loader->load($resource, $type);

            return \is_array($collections) ? $collections : [$collections];
        }

        if (null === $resolver = $this->loader->getResolver()) {
            throw new LoaderLoadException($resource, null, null, null, $type);
        }

        if (false === $loader = $resolver->resolve($resource, $type)) {
            throw new LoaderLoadException($resource, null, null, null, $type);
        }

        $collections = $loader->load($resource, $type);

        return \is_array($collections) ? $collections : [$collections];
    }
1121413
protected function createController($controller)
    {
        if (false === strpos($controller, '::')) {
            throw new \InvalidArgumentException(sprintf('Unable to find controller "%s".', $controller));
        }

        list($class, $method) = explode('::', $controller, 2);

        if ($this->container->has($class)) {
            $controller = $this->container->get($class);
        } else {
            if ( ! class_exists($class)) {
                throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
            }

            $controller = new $class();
        }

        if ($controller instanceof ContainerAwareInterface) {
            $controller->setContainer($this->container);
        }

        return array($controller, $method);
    }
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;
        }
    }
106679
public function loadAny()
    {
        if ($this->loaded()) {
            $this->unload();
        }
        $this->hook('beforeLoad', array('loadAny', array()));

        $this->controller->loadByConditions($this);

        $this->endLoad();

        return $this;
    }
608122
public function load( $q = null, $collection = false )
	{
		$alias = $this->getAlias();
		$array = $this->loadArray( $q, $collection );
		$t = $this;
		$ret = array_map_val( $array[$alias], function()use($t)
		{
			$row = func_get_arg(0);
			$obj = $t->modelFactory( $row );
			$obj->changedColumnsReset();
			return $obj;
		} );
		return $ret;
	}
1178976
public function createController ($stripPath = NULL)
	{
		
		// Instantiate controller
		
		$controllerObj		= new $this->controller;
		
		// Set controller variables from the url processor
		
		$controllerObj->controller	= $this->controller;
		$controllerObj->action		= $this->action;
		
		// Strip initial path from controller
		
		if ($stripPath && substr ($controllerObj->controller, 0, strlen ($stripPath)) == $stripPath)
		{
			$controllerObj->controller = substr ($controllerObj->controller, strlen ($stripPath));
		}
		
		// Return controller object
		
		return $controllerObj;
		
	}
464164
protected function loadController() {
		//try to load the controller
		$config = $this->getConfig();
		$controller = null;
		if (!empty($config['controllerConfig']['name'])) {
			$className = $this->getSite()->getControllerClass($config['controllerConfig']['name']);
			if (class_exists($className)) {
				$controller = new $className($this->getSite(),$config['controllerConfig']);
				$controller->evaluate();
			}
		}
		if (!$controller) {
			$this->logger->warn("Did not find Controller Class");
			$this->getSite()->setRedirectUrl($config['PATH_HTTP']);
		}
	}
1086796
public function load($resource, $type = null)
    {
        if ($this->loaded) {
            throw new RuntimeException('Do not add this loader twice');
        }

        $routes = new RouteCollection();

        $routes->add($this->inputControllerRouteName, new Route($this->inputResizeControllerRoute, [
            '_controller' => 'elcodi.controller.metric_input:addEntryAction',
        ]));

        $this->loaded = true;

        return $routes;
    }
575001
public function performAction($controller, $action) {
		// Replace namespace with directory separator
		$controllerFile = str_replace("\\", DIRECTORY_SEPARATOR, $controller);

		// Check if controller exists
		if ( false == is_file( $controllerLocation = APP . 'Controllers/' . $controllerFile . '.php' ) )
			throw new ControllerNotFoundException();

		// Include and init the controller
		$controllerClass = "\\Application\\Controllers\\{$controller}";
		$controllerObj = new $controllerClass($this);

		// Check if the action exists
		if ( 'Errors' != $controller && false == method_exists($controllerObj, $action.= "Action" ) )
			throw new ActionNotFoundException();
		// Check if the error display action exists
		elseif ( $controller == $this->defaultRoute['_controller'] && false == method_exists($controllerObj, $action = "display" . $action ) )
			throw new ErrorActionNotFoundException();

		// Run the action
		$data = $controllerObj->{$action}();

		// Data fetching
		if ( false === $controllerObj->__returnActionPerformed ):
			// Format returned data
			if ( false == is_array( $data ) )
				$data = (array) $data;

			// Start reflection for data loading
			$ref = new \ReflectionObject($controllerObj);
			$properties = $ref->getProperties(\ReflectionProperty::IS_PUBLIC);
			$controllerData = array();

			// Get public data
			foreach ( $properties as $property ):
				// Don't add internal variabels
				if ( '__returnActionPerformed' == $property->getName() )
					continue;

				// Add property to controller data
				$controllerData[$property->getName()] = $property->getValue($controllerObj);
			endforeach;

			// Merge data from controller and action
			$data = array_merge($controllerData, $data);
		endif;

		// Return the object
		return $data;
	}
46304
public function load()
    {
        if (!empty($this->_statements)) {
            return;
        }

        foreach ($this->data as $type=>$item) {
            if (!is_array($item)) {
                $item = array( $item );
            }
            $use_statements = Config::get('use-statements');
            $adapter_name = isset($use_statements[$type]) ? $use_statements[$type] : null;
            if (!empty($adapter_name)) {
                $cls_name = 'AssetsManager\Package\PresetAdapter\\'.$adapter_name;
                if (@class_exists($cls_name)) {
                    $interfaces = class_implements($cls_name);
                    $config_interface = Config::getInternal('assets-preset-adapter-interface');
                    if (in_array($config_interface, $interfaces)) {
                        if (!isset($this->_statements[$type])) {
                            $this->_statements[$type] = array();
                        }
                        foreach ($item as $item_ctt) {
                            if (!is_array($item_ctt)) {
                                $item_ctt = array( $item_ctt );
                            }
                            $statement = new $cls_name($item_ctt, $this);
                            $statement->parse();
                            $this->_statements[$type][] = $statement;
                        }
                    } else {
                        throw new \DomainException(
                            sprintf('Preset statement class "%s" must implement interface "%s"!',
                                $cls_name, $config_interface)
                        );
                    }
                } else {
                    throw new \DomainException(
                        sprintf('Preset statement class "%s" not found!', $cls_name)
                    );
                }
            } else {
                throw new \LogicException(
                    sprintf('Unknown preset statement type "%s" in preset "%s"!', $type, $this->getName())
                );
            }
        }
    }