service = $service; $this->factory = $factory; $this->exceptions = $exception_routes; } public function __invoke(Request $request, Handler $handler): Response { $path = $request->getUri()->getPath(); if (in_array($path, $this->exceptions) or $this->service->isValid($request)) { return $handler->handle($request); } $response = $this->factory->createResponse(); $response->getBody()->write(json_encode(['message' => 'Not authorized.'])); return $response ->withStatus(401) // unauthorized ->withHeader('content-type', 'application/json'); } }