listCommentsForPost->execute( new ListCommentsForPostRequest(postId: $postId), ); } catch (BadRequestException $exception) { return new JsonResponse( ['error' => $exception->getMessage()], 400, ); } return new JsonResponse([ 'comments' => array_map( function (Comment $comment) { return $this->serialize($comment); }, $comments, ), ], 200); } public function create(Request $request, int $postId): JsonResponse { /** @var User $user */ $user = $request->attributes->get('user'); try { $comment = $this->createComment->execute(new CreateCommentRequest( postId: $postId, userId: $user->getId(), body: $request->input('body'), )); } catch (BadRequestException $exception) { return new JsonResponse( ['error' => $exception->getMessage()], 400, ); } catch (DomainException $exception) { return new JsonResponse( ['error' => $exception->getMessage()], 404, ); } return new JsonResponse([ 'comment' => $this->serialize($comment), ], 201); } public function delete(Request $request, int $id): JsonResponse { /** @var User $user */ $user = $request->attributes->get('user'); try { $this->deleteComment->execute(new DeleteCommentRequest( commentId: $id, requesterId: $user->getId(), requesterIsAdmin: $user->isAdmin(), )); } catch (BadRequestException $exception) { return new JsonResponse( ['error' => $exception->getMessage()], 400, ); } catch (ForbiddenException $exception) { return new JsonResponse( ['error' => $exception->getMessage()], 403, ); } return new JsonResponse(null, 204); } /** * @return array{ * id: int, * postId: int, * userId: int, * authorDisplayName: string, * body: string, * createdAt: string * } */ private function serialize(Comment $comment): array { $author = $this->userRepo->find($comment->getUserId()); return [ 'id' => $comment->getId(), 'postId' => $comment->getPostId(), 'userId' => $comment->getUserId(), 'authorDisplayName' => $author === null ? '' : $author->getDisplayName(), 'body' => $comment->getBody(), 'createdAt' => $comment->getCreatedAt()->format(DATE_ATOM), ]; } }