From bac4e706cb1319b392681802d5b2e59b8da74192 Mon Sep 17 00:00:00 2001 From: Ben Borla Date: Sat, 18 Nov 2023 15:35:05 +0800 Subject: [PATCH] feat: added remove to favorite --- api/src/Controller/IndexController.php | 40 ++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/api/src/Controller/IndexController.php b/api/src/Controller/IndexController.php index 57376c8..60f5a55 100644 --- a/api/src/Controller/IndexController.php +++ b/api/src/Controller/IndexController.php @@ -146,6 +146,15 @@ public function addToFavorite( FruitRepository $fruits, FavoriteRepository $favorites, ) { + // @INFO: Check first if we've reached the maximum number of favorited fruits + if ($favorites->count([]) >= Favorite::MAX_FAVORITE) { + return $this->json([ + 'errors' => [ + 'favorites' => ['Maximum favorites reached.'] + ] + ], Response::HTTP_UNPROCESSABLE_ENTITY); + } + $id = (int) $request->attributes->get('id'); $fruit = $fruits->find($id); @@ -176,6 +185,37 @@ public function addToFavorite( ]); } + /** + * Remove fruit to favorites + * + * @param \Symfony\Component\HttpFoundation\Request $request + * @param \App\Repository\FruitRepository $fruits + * + * @return \Symfony\Component\HttpFoundation\JsonResponse + */ + #[Route('/favorite/{id}', name: 'favorite.delete', methods: ['DELETE'])] + public function removeToFavorites( + Request $request, + FavoriteRepository $favorites, + ) { + $id = (int) $request->attributes->get('id'); + $favorite = $favorites->findOneBy(['fruit' => $id]); + + // @INFO: Return 404 if no fruit found or the method type is not DELETE + if ( + !$favorite instanceof Favorite || + $request->getMethod() !== Request::METHOD_DELETE + ) { + return $this->json([], Response::HTTP_NOT_FOUND); + } + + $this->em->remove($favorite); + $this->em->flush(); + + return $this->json($favorite->toArray(), Response::HTTP_OK); + } + + /** * Hydrate the Fruit instance with request data *