getAttribute('user'); if (!$user instanceof User || !$user->isAdmin()) { return $this->forbidden($request); } return $handler->handle($request); } private function forbidden( ServerRequestInterface $request ): ResponseInterface { $response = new Response(403); if ($this->wantsJson($request)) { $response->getBody()->write( json_encode(['error' => 'forbidden']) ); return $response->withHeader( 'Content-Type', 'application/json' ); } $html = file_get_contents( __DIR__ . '/../../views/templates/forbidden.php' ); $response->getBody()->write($html); return $response->withHeader('Content-Type', 'text/html'); } private function wantsJson(ServerRequestInterface $request): bool { $path = $request->getUri()->getPath(); if (str_starts_with($path, '/api/')) { return true; } $accept = $request->getHeaderLine('Accept'); if (str_contains($accept, 'application/json')) { return true; } return false; } }