Seed middleware stack with first callable

@param callable $kernel The last item to run as middleware

@throws RuntimeException if the stack is seeded more than once
977864
protected function seedMiddlewareStack(callable $kernel = null)
    {
        if (!is_null($this->tip)) {
            throw new RuntimeException('MiddlewareStack can only be seeded once.');
        }
        if ($kernel === null) {
            $kernel = $this;
        }
        $this->tip = $kernel;
    }
852971
def kernel(self, kernel):
        
        result = javabridge.static_call(
            "weka/classifiers/KernelHelper", "setKernel",
            "(Ljava/lang/Object;Lweka/classifiers/functions/supportVector/Kernel;)Z",
            self.jobject, kernel.jobject)
        if not result:
            raise Exception("Failed to set kernel!")
25029
public function withBulkProcessing(callable $callback)
    {
        $bulkProcessing = $this->bulkProcessing;
        $this->bulkProcessing = true;
        try {
            /** @noinspection PhpUndefinedMethodInspection */
            $callback->__invoke();
        } catch (\Exception $exception) {
            $this->bulkProcessing = $bulkProcessing;
            throw $exception;
        }
        $this->bulkProcessing = $bulkProcessing;
    }
784580
public function process(RequestInterface $request)
    {
        if ($this->processingStack !== null) {
            throw new \RuntimeException('Middleware stack is already processing.');
        }
        if (!count($this->middlewares)) {
            throw new \RuntimeException('Middleware stack is empty.');
        }
        if (!($request instanceof ServerRequestInterface)) {
            throw new \InvalidArgumentException('ServerRequest request expected.');
        }
        $this->processingStack = array_reverse($this->middlewares);
        /** @var ServerMiddlewareInterface $middleware */
        $middleware = array_shift($this->processingStack);
        return $middleware->process($request, $this);
    }
73134
public function setKernelOptions($kernelOptions)
    {
        $this->kernelOptions = $kernelOptions;

        //Convert root_dir to be relative to the resque bundle paths, this makes it possible to deploy workers in different places
        if (array_key_exists('kernel.root_dir', $this->kernelOptions)) {
            $this->kernelOptions['kernel.root_dir'] = $this->getRelativePath(__DIR__, $this->kernelOptions['kernel.root_dir']);
        }

        return $this;
    }
422212
private function addMiddleware(callable $callable, $stackName, $whenStackName)
    {
        // 禁止中间件执行过程中又添加中间件到栈中
        if ($this->middlewareLock) {
            throw new \RuntimeException(
                'Middleware can’t be added once the stack is dequeuing'
            );
        }

        if (!$this->tip) {
            $this->seedMiddlewareStack();
        }

        // 对callable做封装，以执行自动遍历
        $this->{$stackName}->enqueue(
            function ($request, $response) use (
                $callable, 
                $stackName, 
                $whenStackName
            ) {
                // return [Request, Response] or WhenCallable
                $result = call_user_func($callable, $request, $response);

                // callable返回WhenCallable，表示是有条件决断的中间件
                if ($result instanceof WhenCallable) {
                    // 返回条件满足时要执行的callable
                    $callable = $result->resolve($request, $response);
                    // 入栈继续等待
                    if ($callable===false) {
                        $this->{$whenStackName}->attach($result);
                    }
                    else {
                        // return [Request, Response]
                        $result = call_user_func($callable, $request, $response);
                    }
                }

                // 不是WhenCallable条件未达到的情况
                if ($callable!==false) {
                    
                    $this->checkReturn($result);

                    list ($request, $response) = $result;
                    // 执行处于等待中的决断
                    $this->{$whenStackName}->rewind();

                    while ($this->{$whenStackName}->valid()) {

                        $callable = $this->{$whenStackName}->current();
                        
                        $callable = $callable->resolve($request, $response);
                        // 条件决断再次失败
                        if ($callable===false) {
                            // null
                        }
                        else {
                            // return [req,res]
                            $result = call_user_func($callable, $request, $response);

                            $this->checkReturn($result);

                            list ($request, $response) = $result;

                            $this->{$whenStackName}->detach($callable);
                        }

                        $this->{$whenStackName}->next();
                    }
                }

                // 执行下个中间件
                if (!$this->{$stackName}->isEmpty()) {
                    $next = $this->{$stackName}->dequeue();
                    $result = $next($request, $response);
                }

                // [Request, Response]
                return $result;
            }
        );

        return $this;
    }
1186299
public function handle(Kernel $kernel)
    {
        if (! $this->confirmToProceed()) {
            return;
        }

        $driver = $this->getDriver();
        $action = $this->argument('action');
        $database = $this->option('database');
        $queue = $this->option('queue') ?? $this->tenant->config()['queue'] ?? 'default';
        $delay = $this->option('delay');

        if (! \in_array($action, $this->actions)) {
            throw new InvalidArgumentException("Action [{$action}] is not available for this command.");
        }

        $command = "tenanti:{$action}";
        $parameters = ['driver' => $driver, '--database' => $database, '--force' => true];

        $this->tenant->driver($driver)
            ->executeForEach(function ($entity) use ($kernel, $command, $parameters, $queue, $delay) {
                $job = $kernel->queue(
                    $command, \array_merge($parameters, ['--id' => $entity->getKey()])
                )->onQueue($queue);

                if ($delay > 0) {
                    $job->delay($delay);
                }
            });
    }
923644
protected function kernel()
    {
        $s = $this->grabkey('kern.version');
        $a = preg_split('/:/', $s);
        if (isset($a[2])) {
            $this->sys->setKernel($a[0].$a[1].':'.$a[2]);
        } else {
            $this->sys->setKernel($s);
        }
    }
64159
static public function instance( KernelAwareContext $context )
    {
        static $instance = null;
        if ( $instance === null )
        {
            $class = get_called_class();
            $instance = new $class();
            $instance->setContext( $context );
        }

        return $instance;
    }
621732
public function runMiddleware($middleware)
    {
        if ($middleware instanceof Middleware) {
            $middleware->setVitex($this);
            $middleware->call();
            return $this;
        }
        throw new Exception("中间件参数不是有效的中间件");
    }
100780
public static function removeMiddleware($middleware)
    {
        $kernelFile = self::read();
        if (str_contains($kernelFile, $middleware)) {
            $kernelFile = preg_replace('^.*' . $middleware . '.*$', '', $kernelFile);
            self::save($kernelFile);
        }
    }
812979
public function callMiddlewareStack(ServerRequestInterface $request, ResponseInterface $response)
    {

        if (!$this->tip) {
            $this->seedMiddlewareStack();
        }

        $this->deferredBefore = new \SplObjectStorage();
        $this->deferredAfter  = new \SplObjectStorage();

        $this->callableStackBefore->rewind();
        $this->callableStackAfter->rewind();
    
        $before = null;

        if (!$this->callableStackBefore->isEmpty()) {
            $before = $this->callableStackBefore->dequeue();
        }
        
        $after = null;

        if (!$this->callableStackAfter->isEmpty()) {
            $after = $this->callableStackAfter->dequeue();
        }

        $this->middlewareLock = true;

        if ($before) {
            list ($request, $response) = $before($request, $response);
        }
        
        $response = call_user_func($this->tip, $request, $response);
        
        //
        if ($after) {
            list ($request, $response) = $after($request, $response);
        }
        
        $this->middlewareLock = false;

        return $response;
    }
365105
public function pushMiddleware(callable $middleware, string $name = null)
    {
        if (!is_null($name)) {
            $this->middlewares[$name] = $middleware;
        } else {
            array_push($this->middlewares, $middleware);
        }

        return $this;
    }
845700
public function register(KernelInterface $kernel): void
    {
        $kernel->closure(RoutingMiddleware::class, function () use ($kernel) {
            return new RoutingMiddleware($kernel[RouterInterface::class], $kernel[ResponseFactoryInterface::class], $kernel[StreamFactoryInterface::class]);
        });

        $kernel->closure(DispatcherMiddleware::class, function () use ($kernel) {
            return new DispatcherMiddleware(new Pipeline($kernel));
        });

        $kernel->closure(ContentTypeByDefaultMiddleware::class, function () {
            return new ContentTypeByDefaultMiddleware();
        });
        /*
        $kernel->closure(OriginalRequestMiddleware::class, function ($c) {
            return new OriginalRequestMiddleware();
        });*/

        $kernel->closure(CharsetByDefaultMiddleware::class, function () {
            return new CharsetByDefaultMiddleware();
        });
        /*
        $kernel->closure(BodyParserMiddleware::class, function ($c) {
            return new BodyParserMiddleware();
        });*/

        /*
                $kernel[EmitterMiddleware::class] = function ($c) {
                    return new EmitterMiddleware();
                };
        */

        $kernel->closure(CheckMaintenanceMiddleware::class, function () {
            return new CheckMaintenanceMiddleware();
        });

        $kernel->closure(MethodOverrideMiddleware::class, function () {
            return new MethodOverrideMiddleware();
        });

        $kernel->closure(ContentLengthMiddleware::class, function () {
            return new ContentLengthMiddleware();
        });

        /*
           $kernel['controllerResolver'] = function ($container) {
               return new ControllerResolver($container);
           };
        */

        //$this->factory = new MiddlewareFactory($this->container);

        //$this->loadConfig($config_path_or_file_or_array, $config_cache_file);

        // TODO : déplacer ces initialisations dans le constructeur d'une classe CONTAINER externalisée

        // TODO : ajouter l'initialisation d'un logger ?????

        // TODO : vérifier l'utilité de mettre cela dans un container, normalement on va toujours passer par le router, donc le mettre dans un container n'est pas vraiment nécessaire, surtout que dans les controller on ne va pas réutiliser le router, car la méthode redirect ou getPathFor se trouve directement dans $app et pas dans la classe Router.
        // register the router in the pimple container

        /*
            $this['session'] = function ($c) {
                // TODO : déplacer la classe session dans le répertoire "components"
                return new Session();
            };
        */

        /*
            $this['router'] = function ($c) {
                return new Router($c->get('basePath'), $this->container);
            };
        */

        // Create request class closure.
        /*
            $this['request'] = function ($c) {
                return Request::fromGlobals();
            };
        */

        // -----------------------------------------------------------------------------
        // Service providers
        // -----------------------------------------------------------------------------
        // Twig
        // TODO : s'inspirer de ce bout de code pour passer des variables global directement à phpRenderer
        /*
        $view = new \Slim\Views\Twig(
            $app->settings['view']['template_path'],
            $app->settings['view']['twig']
        );
        $view->addExtension(new Twig_Extension_Debug());
        $view->addExtension(new \Slim\Views\TwigExtension($app->router, $app->request->getUri()));
        */
        /* @var \Twig_Environment $env */
        /*
        $env = $view->getEnvironment();
        foreach ($app->settings['view']['globals'] as $global => $value) {
            $env->addGlobal($global, $value);
        }
        $container->register($view);*/

        // LOAD Referral Spammer List
        //$spammerList = config('app.referral_spam_list_location', base_path('vendor/matomo/referrer-spam-blacklist/spammers.txt'));
    }
969097
private function middlewareGenerator()
    {
        $middlewares = $this->middleware;
        ksort($middlewares);

        foreach ($middlewares as $priorityGroup) {
            foreach ($priorityGroup as $middleware) {
                yield $middleware;
            }
        }
    }
1016249
protected function addMiddleware($middleware)
    {
        $kernel = $this->app['Illuminate\Contracts\Http\Kernel'];

        if (is_array($middleware)) {
            foreach ($middleware as $ware) {
                $kernel->pushMiddleware($ware);
            }
        } else {
            $kernel->pushMiddleware($middleware);
        }
    }
532583
public function prepend(ContainerBuilder $container)
    {
        $bundles = $container->getParameter('kernel.bundles');

        if (!isset($bundles['GosPubSubRouterBundle'])) {
            throw new RuntimeException('The GosWebSocketBundle requires the GosPubSubRouterBundle.');
        }

        $config = $this->processConfiguration(new Configuration(), $container->getExtensionConfig($this->getAlias()));

        // GosPubSubRouterBundle
        if (isset($config['server'])) {
            $pubsubConfig = $config['server']['router'] ?? [];

            $container->prependExtensionConfig(
                'gos_pubsub_router',
                [
                    'routers' => [
                        'websocket' => $pubsubConfig,
                    ],
                ]
            );
        }

        // TwigBundle
        if (isset($bundles['TwigBundle'])) {
            if (isset($config['shared_config'], $config['server']) && $config['shared_config']) {
                $twigConfig = ['globals' => []];

                if (isset($config['server']['host'])) {
                    $twigConfig['globals']['gos_web_socket_server_host'] = $config['server']['host'];
                }

                if (isset($config['server']['port'])) {
                    $twigConfig['globals']['gos_web_socket_server_port'] = $config['server']['port'];
                }

                if (!empty($twigConfig['globals'])) {
                    $container->prependExtensionConfig('twig', $twigConfig);
                }
            }
        }

        // MonologBundle
        if (isset($bundles['MonologBundle'])) {
            $monologConfig = [
                'channels' => ['websocket'],
                'handlers' => [
                    'websocket' => [
                        'type' => 'console',
                        'verbosity_levels' => [
                            'VERBOSITY_NORMAL' => $container->getParameter('kernel.debug') ? Logger::DEBUG : Logger::INFO,
                        ],
                        'channels' => [
                            'type' => 'inclusive',
                            'elements' => ['websocket'],
                        ],
                    ],
                ],
            ];

            $container->prependExtensionConfig('monolog', $monologConfig);
        }
    }