@param $config
@param $app

@return null|Response
767797
private function bootHttpSapi($config, $app)
    {
        /*
         * ----------------------------------------------------------------------------
         * Initialize the request
         * ----------------------------------------------------------------------------
         */
        $request = $this->initializeRequest($config);

        /*
         * ----------------------------------------------------------------------------
         * If we haven't installed, then we need to reroute. If we have, and we're
         * on the install page, and we haven't installed, then we need to dispatch
         * early and exit.
         * ----------------------------------------------------------------------------
         */
        if ($response = $this->checkInstall($app, $request)) {
            return $response;
        }

        if ($this->app->isInstalled()) {
            /*
             * ----------------------------------------------------------------------------
             * Check the page cache in case we need to return a result early.
             * ----------------------------------------------------------------------------
             */
            if ($response = $this->checkCache($app, $request)) {
                return $response;
            }

            /*
             * ----------------------------------------------------------------------------
             * Now we load all installed packages, and register their package autoloaders.
             * ----------------------------------------------------------------------------
             */
            $this->initializePackages($app);
        }
    }
992463
public function handle(Request $request, Application $app = null)
    {
        $this->request = $request;

        try {
            // init services providers
            /** @var \Alchemy\Service\ServiceProviderInterface $providers */
            $providers = $app->getServiceProviders();

            foreach ($providers as $provider) {
                $provider->init($app);
            }


            /*
             * "EVENT" KernelEvents::REQUEST using GetResponse Event
             *
             * This event can be used by an application to filter a request before
             * ever all kernel logic being executed, listeners for this event should
             * be registered outside framework logic (should be on application logic).
             */
            if ($this->dispatcher->hasListeners(KernelEvents::REQUEST)) {
                $event = new GetResponseEvent($this, $request, $app);
                $this->dispatcher->dispatch(KernelEvents::REQUEST, $event);

                if ($event->hasResponse()) {
                    //var_dump($event->getResponse()); die("ee");
                    $event = new FilterResponseEvent($this, $request, $event->getResponse());
                    $this->dispatcher->dispatch(KernelEvents::RESPONSE, $event);

                    return $event->getResponse();
                }
            }

            /*
             * try match the url request with a defined route.
             * it any route match the current url a ResourceNotFoundException
             * will be thrown.
             */
            $params = $this->mapper->match($request);
            $uriParams = $params["params"];

            // prepare request params.
            $params = $this->prepareRequestParams(array($params["mapped"], $request->query->all(), $request->request->all()));

            // add prepared params to request as attributes.
            $request->attributes->add($params);

            // resolve controller
            try {
                $controller = $this->resolver->getController($request);
            } catch (\Exception $exception) {
                /*
                 * Detailed exception types are only for development environments
                 * if the current is a non dev environment just overrides the current exception with
                 * a ResourceNotFoundException exception
                 */
                if ($this->config->get('env.type') !== 'dev') {
                    $exception = new ResourceNotFoundException($request->getPathInfo());
                }

                throw $exception;
            }

            if (! $controller) {
                throw new ResourceNotFoundException($request->getPathInfo());
            }

            // setting default annotations namespace
            $this->annotationReader->setDefaultNamespace('\Alchemy\Annotation\\');
            // seeting annotation reader target
            $this->annotationReader->setTarget($params['_controllerClass'], $params['_controllerMethod']);

            $arguments = $this->resolver->getArguments($app, $request, $controller);

            //"EVENT" FILTER_CONTROLLER
            if ($this->dispatcher->hasListeners(KernelEvents::FILTER_CONTROLLER)) {
                $event = new FilterControllerEvent($this, $controller, $request);
                $this->dispatcher->dispatch(KernelEvents::FILTER_CONTROLLER, $event);

                // getting controller; this can be the same or other filtered controller
                $controller = $event->getController();
            }

            //"EVENT" BEFORE_CONTROLLER
            if ($this->dispatcher->hasListeners(KernelEvents::BEFORE_CONTROLLER)) {
                $event = new ControllerEvent($this, $controller, $arguments, $request);
                $this->dispatcher->dispatch(KernelEvents::BEFORE_CONTROLLER, $event);
            }

            // Execute controller action
            $response = call_user_func_array($controller, $arguments);

            // check returned value by method is a array
            if (is_array($response)) {
                // set controller view data object
                foreach ($response as $key => $value) {
                    $controller[0]->view->$key = $value;
                }
            }

            // getting controller's data.
            $controllerData = (array) $controller[0]->view;

            if (! ($response instanceof Response || $response instanceof JsonResponse)) {
                if ($this->annotationReader->getAnnotation('JsonResponse')) {
                    $controllerData = $response;
                    $response = new JsonResponse();
                    $response->setData($controllerData);
                } else {
                    $response = new Response();
                }
            }

            //"EVENT" AFTER_CONTROLLER
            if ($this->dispatcher->hasListeners(KernelEvents::AFTER_CONTROLLER)) {
                if (!isset($event) || !($event instanceof ControllerEvent)) {
                    $event = new ControllerEvent($this, $controller, $arguments, $request);
                }
                $event->setResponse($response);

                $this->dispatcher->dispatch(KernelEvents::AFTER_CONTROLLER, $event);
            }

            // handling view
            $view = $this->handleView(
                $params['_controllerClass'],
                $params['_controllerMethod'],
                $controllerData,
                $this->annotationReader->getAnnotation('View')
            );

            // handling meta ui
            if ($this->annotationReader->getAnnotation('ServeUi')) {
                $view = $this->handleMetaUi(
                    $controllerData,
                    $this->annotationReader->getAnnotation('ServeUi'),
                    $view,
                    $request
                );
            }

            // if there is a view adapter instance, get its contents and set to response content
            if (! empty($view)) {
                foreach ($uriParams as $keyParam => $valParam) {
                    $view->assign($keyParam, $valParam);
                }

                //"EVENT" VIEW dispatch all KernelEvents::VIEW events
                if ($this->dispatcher->hasListeners(KernelEvents::VIEW)) {
                    $event = new ViewEvent($this, $view, $request, $this->annotationReader, $app);
                    $this->dispatcher->dispatch(KernelEvents::VIEW, $event);
                    $view = $event->getView();
                }

                $response->setContent($view->getOutput());
            }

        } catch (ResourceNotFoundException $e) {
            $exceptionHandler = new Exception\Handler();

            if ($request->isXmlHttpRequest()) {
                $response = new JsonResponse();
                $response->setData(array('success'=>false, 'message'=>$e->getMessage()));
            } else {
                $response = new Response($exceptionHandler->getOutput($e), 404);
            }
        } catch (\Exception $e) {
//            echo $e->getMessage();
//            echo "<br><pre>";
//            echo $e->getTraceAsString();
//            die;

            $exceptionHandler = new Exception\Handler();

            if ($request->isXmlHttpRequest()) {
                $response = new JsonResponse();
                $response->setData(array('success'=>false, 'message'=>$e->getMessage()));
            } else {
                $response = new Response($exceptionHandler->getOutput($e), 500);
            }
        }

        if ($this->annotationReader->hasTarget()) {
            $responseAnnotation = $this->annotationReader->getAnnotation('Response');
        } else {
            $responseAnnotation = null;
        }

        // dispatch a response event
        $this->dispatcher->dispatch(
            KernelEvents::RESPONSE,
            new FilterResponseEvent($this, $request, $response, $responseAnnotation)
        );

        return $response;
    }
729738
final public static function setApplication(Application $app)
    {
        if (null === self::$_app) {
            self::$_app = $app;
        } else {
            throw new Exception('application 只能被实例化一次', 100500101);
        }
    }
149837
protected function loadIlluminateConfig(Container $app, Repository $config)
    {
        foreach ($this->getIlluminateConfig($app) as $key => $path) {
            $config->set($key, require $path);
        }
    }
285926
protected function configureNewRelic(Application $app)
    {
        if (
            isset($app['newrelic.options']['application_name']) &&
            $app['newrelic.options']['application_name']
        ) {
            $app['newrelic']->setAppName($app['newrelic.options']['application_name']);
        }

        /**
         * @see https://docs.newrelic.com/docs/agents/php-agent/configuration/php-agent-api#api-rum-disable
         */
        if (
            isset($app['newrelic.options']['disable_auto_rum']) &&
            $app['newrelic.options']['disable_auto_rum']
        ) {
            $app['newrelic']->disableAutoRUM();
        }

        /**
         * @see https://docs.newrelic.com/docs/agents/php-agent/configuration/php-agent-api#api-capture-params
         */
        if (
            isset($app['newrelic.options']['capture_params']) &&
            $app['newrelic.options']['capture_params']
        ) {
            $app['newrelic']->captureParams($app['newrelic.options']['capture_params']);
        }

        /**
         * @see https://docs.newrelic.com/docs/agents/php-agent/configuration/php-agent-api#api-ignore-transaction
         */
        if (
            isset($app['newrelic.options']['ignore_transactions']) &&
            $app['newrelic.options']['ignore_transaction']
        ) {
            $app['newrelic']->ignoreTransaction();
        }

        if (
            isset($app['newrelic.options']['custom_metrics']) &&
            is_array($app['newrelic.options']['custom_metrics'])
        ) {

            foreach($app['newrelic.options']['custom_metrics'] as $name => $value) {
                $app['newrelic.custom_metric']($name, $value);
            }

        }

        if (
            isset($app['newrelic.options']['custom_params']) &&
            is_array($app['newrelic.options']['custom_params'])
        ) {

            foreach($app['newrelic.options']['custom_params'] as $name => $value) {
                $app['newrelic.custom_params']($name, $value);
            }

        }

    }
396593
protected function getLoggerIfEnabled($app)
    {
        /** @var ApplicationInterface $app */

        if ($this->logger === false) {
            $settings       = $this->getSettings();
            $loggingEnabled =
                array_key_exists(Settings::KEY_LOGS_ENABLED, $settings) === true &&
                $settings[Settings::KEY_LOGS_ENABLED] === true;

            $this->logger = $loggingEnabled === true ? $app[LoggerInterface::class] : null;
        }

        return $this->logger;
    }
730680
public function bootstrap($app)
    {
        if (empty($this->applicationId) || empty($this->apiKey)) {
            throw new InvalidConfigException('applicationId and apiKey are required');
        }

        Yii::$container->set(AlgoliaManager::class, function () {
            return $this->createManager();
        });
    }
1051110
public function app($appConfig)
    {
        $appConfig = array_merge(
            $this['config']->only(['debug', 'log', 'guzzle']),
            $appConfig
        );

        $appConfig['cache'] = $this['config']['cache'];

        return new Application($this['open_platform'], $this['config'], $appConfig);
    }
1194490
final public function get(array $appConfig): array
    {
        $settings = $this->getSettings();

        // check and transform HTTP methods
        $methods = $settings[static::HTTP_METHODS_TO_CHECK] ?? [];
        assert(empty($methods) === false);
        $upperCaseMethods = [];
        foreach ($methods as $method) {
            assert(is_string($method) === true && empty($method) === false);
            $upperCaseMethods[strtoupper($method)] = true;
        }
        $settings[static::INTERNAL_HTTP_METHODS_TO_CHECK_AS_UC_KEYS] = $upperCaseMethods;
        unset($settings[static::HTTP_METHODS_TO_CHECK]);

        // check token key
        $tokenKey = $settings[static::HTTP_REQUEST_CSRF_TOKEN_KEY];
        assert(is_string($tokenKey) === true && empty($tokenKey) === false);

        // check storage key
        $storageKey = $settings[static::TOKEN_STORAGE_KEY_IN_SESSION];
        assert(is_string($storageKey) === true && empty($storageKey) === false);

        // check max tokens
        $maxTokens = $settings[static::MAX_TOKENS];
        assert(is_null($maxTokens) === true || (is_int($maxTokens) === true && $maxTokens > 0));

        // check max tokens
        $maxTokensThreshold = $settings[static::MAX_TOKENS];
        assert(is_int($maxTokensThreshold) === true && $maxTokensThreshold >= 0);

        $errorResponseMethod = $settings[static::CREATE_ERROR_RESPONSE_METHOD] ?? null;
        $expectedArgs        = [ContainerInterface::class, ServerRequestInterface::class];
        $expectedRet         = ResponseInterface::class;
        assert(
            $this->checkPublicStaticCallable($errorResponseMethod, $expectedArgs, $expectedRet) === true,
            'CSRF error response method should have signature ' .
            '(ContainerInterface, ServerRequestInterface): ResponseInterface.'
        );

        return $settings;
    }
1302449
public function bootstrap(Application $app): void
    {
        if ($app->bound('config') && $app->environment('testing')) {
            return;
        }

        $items = [];
        $loader = new FileLoader(new Filesystem(), $app->configPath());

        // First we will see if we have a cache configuration file. If we do, we'll load
        // the configuration items from that file so that it is very quick. Otherwise
        // we will need to spin through every configuration file and load them all.
        if (\file_exists($cached = $app->getCachedConfigPath())) {
            $items = require $cached;
        }

        $this->setEnvironment($app, $items['*::app']['env'] ?? null);

        \tap(new Repository($loader, $app->environment()), function ($config) use ($app, $items) {
            $app->instance('config', $config);
            $config->setFromCache($items);

            \date_default_timezone_set($config->get('app.timezone', 'UTC'));
        });

        \mb_internal_encoding('UTF-8');
    }
954190
final public function get(array $appConfig): array
    {
        $this->appConfig = $appConfig;

        $defaults = $this->getSettings();

        $credentialsValidator = $defaults[static::KEY_USER_CREDENTIALS_VALIDATOR];
        assert(
            $this->checkPublicStaticCallable(
                $credentialsValidator,
                [ContainerInterface::class, 'string', 'string']
            ),
            "Invalid credentials validator."
        );

        $scopeValidator = $defaults[static::KEY_USER_SCOPE_VALIDATOR] ?? null;
        assert(
            $this->checkPublicStaticCallable(
                $scopeValidator,
                [
                    ContainerInterface::class,
                    'int',
                    function (ReflectionParameter $parameter) {
                        return $parameter->allowsNull() === true && $parameter->isArray() === true;
                    },
                ]
            ),
            "Invalid scope validator."
        );

        $customPropsProvider = $defaults[static::KEY_TOKEN_CUSTOM_PROPERTIES_PROVIDER] ?? null;
        assert(
            $customPropsProvider === null ||
            $this->checkPublicStaticCallable(
                $customPropsProvider,
                [ContainerInterface::class, TokenInterface::class],
                'array'
            ),
            "Invalid token custom properties provider."
        );

        $customUnAuthFactory = $defaults[static::KEY_FAILED_CUSTOM_UNAUTHENTICATED_FACTORY] ?? null;
        assert(
            $customUnAuthFactory === null ||
            $this->checkPublicStaticCallable(
                $customUnAuthFactory,
                [],
                ResponseInterface::class
            ),
            "Invalid custom factory."
        );

        $approvalUri = $defaults[static::KEY_APPROVAL_URI_STRING];
        assert(empty($approvalUri) === false, "Invalid Approval URI `$approvalUri`.");

        $errorUri = $defaults[static::KEY_ERROR_URI_STRING];
        assert(empty($errorUri) === false, "Invalid Error URI `$errorUri`.");

        $defaultClientId = $defaults[static::KEY_DEFAULT_CLIENT_ID];
        assert(empty($defaultClientId) === false, "Invalid Default Client ID `$defaultClientId`.");

        $userTable = $defaults[static::KEY_USER_TABLE_NAME];
        assert(empty($userTable) === false, "Invalid User Table Name `$userTable`.");

        $userPk = $defaults[static::KEY_USER_TABLE_NAME];
        assert(empty($userPk) === false, "Invalid User Primary Key Name `$userPk`.");

        return $defaults + [
                static::KEY_APPROVAL_URI_STRING              => $approvalUri,
                static::KEY_ERROR_URI_STRING                 => $errorUri,
                static::KEY_DEFAULT_CLIENT_ID                => $defaultClientId,
                static::KEY_USER_TABLE_NAME                  => $userTable,
                static::KEY_USER_PRIMARY_KEY_NAME            => $userPk,
                static::KEY_USER_CREDENTIALS_VALIDATOR       => $credentialsValidator,
                static::KEY_USER_SCOPE_VALIDATOR             => $scopeValidator,
                static::KEY_TOKEN_CUSTOM_PROPERTIES_PROVIDER => $customPropsProvider,
            ];
    }
691
static public function launch($config, $run = true)
	{
		if (is_string($config)) {
		    $config = ['basePath' => $config];
		}
		
		$app = new static($config);
		
		if ($run) {
		    return $app->run();
		}
		
		return $app;
	}
777610
public function register(App $app)
    {
        $app["logger.service"] = $app->protect(
            function (string $loggerName = "") use ($app) {
                $cacheName = "logger.service-{$loggerName}";
                if (isset($app[$cacheName])) {
                    return $app[$cacheName];
                }
                /*
                 * Check the config service has been defined and provides correct
                 * object
                 */
                if (isset($app["config.service"]) === false
                    || get_class($app["config.service"]) !== "SlaxWeb\\Config\\Container") {
                    throw new \SlaxWeb\Bootstrap\Exception\LoggerConfigException(
                        "Config component provider must be registered before you can use the Logger component."
                    );
                }

                $config = $app["config.service"];
                if ($loggerName === "") {
                    $loggerName = $config["logger.defaultLogger"];
                }

                $logger = new MLogger($loggerName);
                foreach ($config["logger.loggerSettings"][$loggerName] as $type => $settings) {
                    // load propper handler and instantiate the Monolog\Logger
                    $handler = null;
                    switch ($type) {
                        case Helper::L_TYPE_FILE:
                            $app["temp.logger.settings"] = $settings;
                            $handler = $app["logger.{$type}.service"];
                            unset($app["temp.logger.settings"]);
                            break;
                        default:
                            throw new \SlaxWeb\Bootstrap\Exception\UnknownLoggerHandlerException(
                                "The handler you are tring to use is not known or not supported."
                            );
                    }
                    $logger->pushHandler($handler);
                }

                return $app[$cacheName] = $logger;
            }
        );

        $app["logger.StreamHandler.service"] = $app->factory(
            function (App $cont) {
                $settings = $cont["temp.logger.settings"];

                // if the log file name does not begin with a dir separator, treat
                // it as relative path and prepend 'logFilePath'
                if ($settings[0][0] !== DIRECTORY_SEPARATOR) {
                    $settings[0] = ($cont["config.service"]["logger.logFilePath"] ?? "")
                        . $settings[0];
                }
                return new \Monolog\Handler\StreamHandler(...$settings);
            }
        );
    }
856744
public function register(App $app)
    {
        $app["config.service"] = function (App $app) {
            return new \SlaxWeb\Config\Container(
                $app["configHandler.service"]
            );
        };

        $app["configHandler.service"] = function (App $app) {
            switch ($app["configHandler"]) {
                case \SlaxWeb\Config\Container::PHP_CONFIG_HANDLER:
                    return new \SlaxWeb\Config\PhpHandler(
                        [$app["configResourceLocation"]]
                    );
                case \SlaxWeb\Config\Container::XML_CONFIG_HANDLER:
                    return new \SlaxWeb\Config\XmlHandler(
                        [$app["configResourceLocation"]],
                        new \Desperado\XmlBundle\Model\XmlReader
                    );
                case \SlaxWeb\Config\Container::YAML_CONFIG_HANDLER:
                    return new \SlaxWeb\Config\YamlHandler(
                        [$app["configResourceLocation"]]
                    );
                default:
                    $availOpts = [
                        \SlaxWeb\Config\Container::PHP_CONFIG_HANDLER,
                        \SlaxWeb\Config\Container::XML_CONFIG_HANDLER,
                        \SlaxWeb\Config\Container::YAML_CONFIG_HANDLER
                    ];
                    throw new \SlaxWeb\Bootstrap\Exception\InvalidConfigHandlerException(
                        "Handler type property 'configHandler' must be one of "
                        . json_encode($availOpts)
                    );
            }
        };
    }
687848
public function bootstrap(Application $app)
    {
        $items = [];

        $app->instance('config', $config = new Repository($items));

        $this->loadConfigurationFiles($app, $config);

        mb_internal_encoding('UTF-8');
    }
898623
protected function runDeployHooks(array $appConfig, $appDir)
    {
        if (empty($this->settings['run-deploy-hooks'])) {
            return null;
        }
        if (empty($appConfig['hooks']['deploy']) && empty($appConfig['hooks']['post_deploy'])) {
            $this->output->writeln('No deploy or post_deploy hooks found');
            return null;
        }
        $result = null;
        if (!empty($appConfig['hooks']['deploy'])) {
            $this->output->writeln('Running deploy hooks');
            $result = $this->runHook($appConfig['hooks']['deploy'], $appDir);
        }
        if (!empty($appConfig['hooks']['post_deploy']) && $result !== false) {
            $this->output->writeln('Running post_deploy hooks');
            $result = $this->runHook($appConfig['hooks']['post_deploy'], $appDir);
        }

        return $result;
    }
716684
public function boot(Application $app)
    {
        $config = $app['config'];
        if (isset($config['orm.subscribers'])) {
            $app->extend('db.event_manager', function($eventMgr) use($app, $config) {
                /** @var EventManager $eventMgr */
                foreach ($config['orm.subscribers'] as $class) {
                    if (isset($app[$class])) {
                        $eventMgr->addEventSubscriber($app[$class]);
                    } else {
                        $eventMgr->addEventSubscriber(new $class());
                    }
                }
                return $eventMgr;
            });
        }
    }