container = $container; $this->seedMiddlewareStack($kernel); foreach ($middlewares as $middleware) { if (is_string($middleware)) { $this->lazy($middleware); } else { $this->add($middleware); } } } /** * Invoke the middleware stack */ public function handle(ServerRequestInterface $request): ResponseInterface { return $this->tip->handle($request); } /** * Seed the middleware stack with the inner request handler */ protected function seedMiddlewareStack(RequestHandlerInterface $kernel) { $this->tip = $kernel; } /** * Add a new middleware to the stack * * Middlewares are organized as a stack. That means middlewares * that have been added before will be executed after the newly * added one (last in, first out). */ public function add(MiddlewareInterface $middleware): void { $next = $this->tip; $this->tip = new class ($middleware, $next) implements RequestHandlerInterface { public function __construct(private readonly MiddlewareInterface $middleware, private readonly RequestHandlerInterface $next) {} public function handle(ServerRequestInterface $request): ResponseInterface { return $this->middleware->process($request, $this->next); } }; } /** * Add a new middleware by class name * * Middlewares are organized as a stack. That means middlewares * that have been added before will be executed after the newly * added one (last in, first out). * * @param string $middleware */ public function lazy(string $middleware): void { $next = $this->tip; $this->tip = new class ($middleware, $next, $this->container) implements RequestHandlerInterface { public function __construct( private readonly string $middleware, private readonly RequestHandlerInterface $next, private readonly ?ContainerInterface $container = null ) {} public function handle(ServerRequestInterface $request): ResponseInterface { if ($this->container !== null && $this->container->has($this->middleware)) { $middleware = $this->container->get($this->middleware); } else { $middleware = GeneralUtility::makeInstance($this->middleware); } if (!$middleware instanceof MiddlewareInterface) { throw new \InvalidArgumentException(get_class($middleware) . ' does not implement ' . MiddlewareInterface::class, 1516821342); } return $middleware->process($request, $this->next); } }; } }