エグゼキュータ

@param	array		$params		パラメータ
@param	Controller	$instance	インスタンスを再利用する場合のインスタンス
@return	Controller	インスタンス
346359
public static function Execute ($params, $instance = null) {
		$instance = new static;
		if ($instance !== null) {
			$class_name = static::class;
			if (!($instance instanceof $class_name)) {
				throw CoreException::RaiseSystemError('再利用するインスタンスのクラスが合いません。class_name:%s, instance_class_name:%s', [$class_name, (new \ReflectionObject($instance))->getName()]);
			}
		} else {
			$instance = new static;
		}

		$params = LazyArrayObject::Create($params);
		$instance->options		= LazyArrayObject::RecursiveCreate($params->options ?: []);
		$instance->render		= LazyArrayObject::RecursiveCreate($params->render ?: []);
		$instance->error		= LazyArrayObject::RecursiveCreate($params->error ?: []);

		Environment::IsCli() && $instance->adjustCliParameters();

		$instance->request		= Request::GetInputVars([]);

		if (isset($instance->options->default_parameters)) {
			foreach ($instance->options->default_parameters as $parameter_name => $parameter_value) {
				if (!isset($params->parameter[$parameter_name]) || $params->parameter[$parameter_name] == '') {
					$params->parameter[$parameter_name] = $parameter_value;
				}
			}
		}

		if (isset($instance->options['redirect'])) {
			$instance->nextRule = IController::NEXT_REDIRECT;
			$instance->nextUrl = $instance->options['redirect'];
			return $instance;
		}

		$instance->params		= $params;

//@TODO 様子見
//		$instance->overWriteParameterSet($params->parameter ?: []);
		$instance->route		= LazyArrayObject::Create($params->parameter ?? []);

		$instance->controller	= str_replace('/', '_', $params->controller ?? 'index');
		$instance->action		= str_replace('/', '_', $params->action ?? 'index');

		$instance->layout		= $instance->options->layout ?: 'default';

		$instance->templateDir	= $instance->options->template_dir ?: $instance->controller;
		$instance->templateExtDirList	= $instance->options->template_ext_dir_list ? $instance->options->template_ext_dir_list->getArrayCopy() : [];

		$instance->template		= $instance->options->template ?: $instance->action;
		if (is_array($instance->template) || $instance->template instanceof \ickx\fw2\vartype\arrays\LazyArrayObject) {
			switch (count($instance->template)) {
				case 2:
					$instance->templateDir	= $instance->template['controller'] ?? $instance->template[0];
					$instance->template		= $instance->template['action'] ?? $instance->template[1];
					break;
				default:
					$instance->template		= $instance->template['action'] ?? $instance->template[0];
					break;
			}
		}

		if (!$instance->canKeepTrigger() && $instance->trigger === null) {
			$instance->trigger = $instance->searchTrigger($instance->currentRule = $instance->getActionRule());
		}

		$instance->rule			= $instance->purseActionRule($instance->trigger);

		$instance->setUpDefaultEvents();

		if (method_exists($instance, 'setupEvents')) {
			Objects::InvokeOverrideMethod($instance, 'setupEvents');
		}

		$setup_action_events = [$instance, Strings::ToLowerCamelCase($instance->action.'_setup_events')];
		!is_callable($setup_action_events) ?: $setup_action_events();

		$instance->dispatchEvents();

		if (!$instance->canKeepTrigger()) {
			$instance->releaseTrigger($instance->trigger);
		}
		$instance->keepTrigger = false;

		return $instance;
	}
1249704
private function parseAnnotations(EventParam $e)
    {
        $controllerParser = TcpControllerParser::getInstance();
        foreach(ServerManage::getServers() as $name => $server)
        {
            if(!$server instanceof \Imi\Server\TcpServer\Server)
            {
                continue;
            }
            RequestContext::create();
            RequestContext::set('server', $server);
            $route = $server->getBean('TcpRoute');
            foreach($controllerParser->getByServer($name) as $className => $classItem)
            {
                $classAnnotation = $classItem['annotation'];
                // 类中间件
                $classMiddlewares = [];
                foreach(AnnotationManager::getClassAnnotations($className, TcpMiddleware::class) ?? [] as $middleware)
                {
                    if(is_array($middleware->middlewares))
                    {
                        $classMiddlewares = array_merge($classMiddlewares, $middleware->middlewares);
                    }
                    else
                    {
                        $classMiddlewares[] = $middleware->middlewares;
                    }
                }
                foreach(AnnotationManager::getMethodsAnnotations($className, TcpAction::class) as $methodName => $actionAnnotations)
                {
                    $routes = AnnotationManager::getMethodAnnotations($className, $methodName, TcpRoute::class);
                    if(!isset($routes[0]))
                    {
                        throw new \RuntimeException(sprintf('%s->%s method has no route', $className, $methodName));
                    }
                    // 方法中间件
                    $methodMiddlewares = [];
                    foreach(AnnotationManager::getMethodAnnotations($className, $methodName, TcpMiddleware::class) ?? [] as $middleware)
                    {
                        if(is_array($middleware->middlewares))
                        {
                            $methodMiddlewares = array_merge($methodMiddlewares, $middleware->middlewares);
                        }
                        else
                        {
                            $methodMiddlewares[] = $middleware->middlewares;
                        }
                    }
                    // 最终中间件
                    $middlewares = array_values(array_unique(array_merge($classMiddlewares, $methodMiddlewares)));
                    
                    foreach($routes as $routeItem)
                    {
                        $route->addRuleAnnotation($routeItem, new RouteCallable($className, $methodName), [
                            'middlewares' => $middlewares,
                        ]);
                    }
                }
            }
            RequestContext::destroy();
        }
    }
572686
public static function getScaffoldController(
        Controller $instance, $options = [])
    {

        $options = array_merge(
            [
                'controller' => $instance,
                'request' => $instance->request,
                'response' => $instance->response,
                'view' => $instance->view,
                'layout' => $instance->layout,
                'basePath' => $instance->basePath
            ],
            $options
        );
        return new static($options);
    }
651729
public function setInstance($instance = 'default')
    {
        $this->get($instance);

        $this->session->put($this->prefix.'.instance', $instance);

        if (!in_array($instance, $this->getInstances())) {
            $this->session->push($this->prefix.'.instances', $instance);
        }
        $this->events->dispatch('laracart.new');

        return $this;
    }
325570
private function getInstanceCode(Instance $instance) : Code
    {
        $node = ($this->normalizer)($instance->value);

        return new Code(new Node\Stmt\Return_($node), false);
    }
621810
protected function prepareDataProvider($params = []) {
        if (!isset($params['attr']))
            throw new Exception('Require parameter "attr"!');

        $prefix = is_null($this->controller->module) ? $this->controller->module->uniqueId : $this->controller->module->id;
        $prefix.= DIRECTORY_SEPARATOR . $params['attr'];
        $uploadPath = $this->uploadPath . DIRECTORY_SEPARATOR . $prefix;
        $uploadUrl = str_replace('\\', '/', $this->uploadUrl . '/' . $prefix);

        $data = [];
        if (@file_exists($uploadPath)) {
            $whiteExts = array_map(function($value) {
                return "*.{$value}";
            }, $this->whiteExts);
            $files = FileHelper::findFiles($uploadPath, ['only' => $whiteExts]);

            foreach ($files as $file) {
                $fileName = basename($file);
                $data[] = [
                    'title' => $fileName,
                    'thumb' => Url::to($uploadUrl . '/' . $fileName),
                    'image' => Url::to($uploadUrl . '/' . $fileName),
                ];
            }
        }
        return $data;
    }
1231561
protected function invokeClass($instance, $action, $vars = []) {
        timer('controller response');
        if (is_string($instance)) {
            $instance = new $instance;
        }
        if (method_exists($instance, 'init')) {
            $instance->init();
        }
        if (method_exists($instance, 'invokeMethod')) {
            return call_user_func(array($instance, 'invokeMethod'), $action, $vars);
        }
        throw new Exception(
            __('UNKNOWN CLASS')
        );
    }
1230363
protected function callWithinStack( $instance, $route, $request, $method )
	{
		$middleware = HttpFactory::i()->isMiddlewareDisabled() ? [] : $this->getMiddleware( $instance, $method );

		// Here we will make a stack onion instance to execute this request in, which gives
		// us the ability to define middlewares on controllers. We will return the given
		// response back out so that "after" filters can be run after the middlewares.
		return ( new Pipeline() )->send( $request )->through( $middleware )->then( function ( $request ) use ( $instance, $route, $method )
		{
			return $this->router->prepareResponse( $request, $this->call( $instance, $route, $method ) );
		} );
	}
766584
public static function getInstance($param = null)
    {
        if (self::$instance === null) {
            if (isset($param['type'])) {
                $type = $param['type'];
                unset($param['type']);
            } else {
                throw new \LogicException('Config Type was not specified in the param array $param[\'type\']');
            }

            self::$instance = ConfigFactory::make($type, $param);
        }

        // return singelton instance
        return self::$instance;
    }
1177136
protected function getCallParams($controller, $method, $params)
		{
			// variables
			$values     = is_array($params) ? $params : explode('/', $params);
			$ref        = new ReflectionMethod($controller, $method);
			$params     = $ref->getParameters();
			$args       = [];
	
			// map route segments to the method's parameters
			foreach ($params as /** @var \ReflectionParameter */ $param)
			{
				// parse signature [match, optional, type, name, default]
				preg_match('/<(required|optional)> (?:([\\\\a-z\d_]+) )?(?:\\$(\w+))(?: = (\S+))?/i', (string)$param, $matches);
	
				// assign untyped segments
				if ($matches[2] == null)
				{
					$args[$matches[3]] = array_shift($values);
				}
			}
	
			// append any remaining values
			return array_merge($args, $values);
		}
439195
protected function call($instance, $route, $method)
    {
        $parameters = $this->resolveClassMethodDependencies(
            $route->parametersWithoutNulls(), $instance, $method
        );

        if ($this->creator && method_exists($this->creator, 'modifyMethodParameters')) {
            $this->creator->modifyMethodParameters($instance, $method, $parameters);
        }

        return $instance->callAction($method, $parameters);
    }
1000182
public function getModelDataTable($instances, $model, $totalCount, $page = 1) {
		$adminRoute = $this->controller->_getBaseRoute ();
		$files = $this->controller->_getFiles ();
		$dataTable = $this->getDataTableInstance ( $instances, $model, $totalCount, $page );
		$attributes = $this->controller->_getAdminData ()->getFieldNames ( $model );
		$this->setDataTableAttributes ( $dataTable, $attributes, $model, $instances );
		$dataTable->setCaptions ( $this->getCaptions ( $attributes, $model ) );

		$dataTable->addClass ( "small very compact" );
		$lbl = new HtmlLabel ( "search-query", "<span id='search-query-content'></span>" );
		$icon = $lbl->addIcon ( "delete", false );
		$lbl->wrap ( "<span>", "</span>" );
		$lbl->setProperty ( "style", "display: none;" );
		$icon->getOnClick ( $adminRoute . $files->getRouteRefreshTable (), "#lv", [ "jqueryDone" => "replaceWith","hasLoader" => "internal" ] );

		$dataTable->addItemInToolbar ( $lbl );
		$dataTable->addSearchInToolbar ();
		$dataTable->setToolbarPosition ( PositionInTable::FOOTER );
		$dataTable->getToolbar ()->setSecondary ();
		return $dataTable;
	}
56397
public function getUrlsList($instanceName)
    {
        // FIXME: $instanceName is no more needed! o_O
        $urlsList = [];

        if ($this->controllerDetector) {
            $detectedControllers = array_values($this->controllerDetector->getControllerIdentifiers($this->controllerAnalyzer));
            $detectedControllers = array_combine($detectedControllers, $detectedControllers);

            $controllers = $this->controllers + $detectedControllers;
        } else {
            $controllers = $this->controllers;
        }

        foreach ($controllers as $controllerInstanceName) {
            $routes = $this->controllerAnalyzer->analyzeController($controllerInstanceName);

            $urlsList = array_merge($urlsList, $routes);
        }

        return $urlsList;
    }
828884
protected function getRequestedInstanceConfig($paramName = 'instanceId')
    {
        $instanceId = $this->getInstanceIdParam($paramName, null);

        if ($instanceId === null) {
            throw new \Exception("Route param '{$paramName}' required");
        }

        return $this->getInstanceConfig($instanceId);
    }
843951
public function runController($controller, $method, Array $params) {
    $transactional = $controller instanceof \Psc\CMS\Controller\TransactionalController;
    
    try {
      try {
        $this->logf('running Controller: %s::%s(%s)', Code::getClass($controller), $method, implode(', ',array_map(function ($param) { return Code::varInfo($param); }, $params)));
        $cb = new Callback($controller, $method);
        $controllerResponse = $cb->call($params);
        
        $this->log('Converting Controller Response');
        $this->setResponseFromControllerResponse($controllerResponse);
        $this->log('Response Format: '.($this->response->getFormat() ?: 'null'));
        $this->log('successful run');
        
        $this->log('überprüfe ResponseMetadataController');
        if ($controller instanceof \Psc\CMS\Controller\ResponseMetadataController && ($meta = $controller->getResponseMetadata()) != NULL) {
          $this->response->setMetadata($meta);
          $this->log('Metadaten übertragen');
        }
        
      /* PDO Exceptions */
      } catch (\PDOException  $e) {
        throw \Psc\Doctrine\Exception::convertPDOException($e);
      }

    } catch (\Exception $e) {
      if ($transactional && $controller->hasActiveTransaction())
        $controller->rollbackTransaction();
      
      $this->handleException($e);
    }
  }
290283
public function register_router_controller($router, $params, $controller)
    {
        if (!is_array($params)) {
            $params = array($params);
        }
        $route = $params[0];
        $method = isset($params[1]) ? $params[1] : 'GET|POST';
        $name = isset($params[2]) ? $params[2] : $controller;
        if (in_array($name, $this->controllers_routes)) {
            $name = null;
        } else {
            $this->controllers_routes[] = $name;
        }
        $this->controllers_url_routes[] = $controller . ' ' . $route . ' [' . $method . ']';
        if(!isset(self::$routes[$name])) {
            $router->map($method, $route, array($this, $controller), $name);
            self::$routes[$name] = true;
        } else {
            $router->map($method, $route, array($this, $controller));

        }
    }
1213806
static function load($controller, $action = '', $params = array())
	{

		$class_name = ucfirst($controller);
		$method = $action;
		$tc = "Controller\\" . $class_name;
		if (!class_exists($tc)) return self::er("Class $tc does not exist.");
		$this_object = new $tc($params);


		if (!method_exists($this_object, $method)) {
			return self::er("Method $method in $tc does not exist.");
		}


		if (!is_callable(array($this_object, $method))) return self::er("Method $method in $tc is not callable.");
		if (is_callable(array($this_object, "__before"))) {
			call_user_func(array($this_object, "__before"));
		}


		call_user_func(array($this_object, $method));

		if (is_callable(array($this_object, "__after"))) {
			call_user_func(array($this_object, "__after"));
		}
		return $this_object;
	}