/** * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable $next * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null) { $request = $this->decorateRequest($request); $response = $this->decorateResponse($response); $relay = $this->relayBuilder->newInstance($this->middleware); $error = $this->errorHandler; $notFound = $this->notFoundHandler; try { $response = $relay($request, $response); } catch (\Exception $ex) { $response = $error($request, $response, $ex); } if (!$response instanceof ResponseInterface) { throw new Exception\InvalidResponse(); } if (null === $this->routeMap->getRouteMatch()) { $response = $notFound($request, $response); } return $next ? $next($request, $response) : $response; }