build($request); return (new Relay($queue))->handle($request); } /** * @return MiddlewareInterface[] */ private function build(RequestInterface $request): array { $mapping = []; foreach ($this->getMatchedMiddlewareReferences($request) as $middlewareClass) { $middleware = $this->getServiceLocator()->get($middlewareClass); if (!$middleware instanceof MiddlewareInterface) { throw new LogicException(sprintf('Incorrect middleware configuration for %s', $middlewareClass)); } $mapping[] = $middleware; } return array_merge( [ function ($request, $next) { return $this->originalResponse ?? new Response(); } ], $mapping, [ function ($request, $next) { return new Response(); } ] ); } public function withOriginalResponse(ResponseInterface $response): self { $this->originalResponse = $response; return $this; } /** * @return string[] */ private function getMatchedMiddlewareReferences(RequestInterface $request): array { return $this->getOption(self::OPTION_MAP, [])[$request->getUri()->getPath()] ?? []; } }