|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- <?php
-
- namespace Lc\CaracoleBundle\Controller\Product;
-
- use Lc\CaracoleBundle\Controller\AbstractController;
- use Symfony\Component\HttpFoundation\JsonResponse;
- use Symfony\Component\HttpFoundation\Request;
- use Symfony\Component\Routing\Annotation\Route;
-
- class FavoriteController extends AbstractController
- {
- /**
- * @Route("/favorite/toggle", name="lc_frontend_favorite_toggle")
- */
- public function toggle(Request $request)
- {
- $user = $this->_getUser();
- $productFamily = $this->_getProductFamily($request);
-
- if ($user->getFavoriteProductFamilies()->contains($productFamily)) {
- $user->removeFavoriteProductFamily($productFamily);
- $isFavorite = false;
- $message = 'Le produit a bien été supprimé de vos favoris';
- } else {
- $user->addFavoriteProductFamily($productFamily);
- $isFavorite = true;
- $message = 'Le produit a bien été ajouté à vos favoris';
- }
-
- $this->_saveUser($user);
-
- return new JsonResponse([
- 'return' => 'success',
- 'is_favorite' => $isFavorite,
- 'message' => $message
- ]);
- }
-
- /**
- * @Route("/favorite/add", name="lc_frontend_favorite_add")
- */
- public function add(Request $request)
- {
- $user = $this->_getUser();
- $productFamily = $this->_getProductFamily($request);
-
- $user->addFavoriteProductFamily($productFamily);
- $this->_saveUser($user);
-
- return new JsonResponse([
- 'return' => 'success',
- 'message' => 'Le produit a bien été ajouté à vos favoris'
- ]);
- }
-
- /**
- * @Route("/favorite/delete", name="lc_frontend_favorite_delete")
- */
- public function delete(Request $request)
- {
- $user = $this->_getUser();
- $productFamily = $this->_getProductFamily($request);
-
- $user->removeFavoriteProductFamily($productFamily);
- $this->_saveUser($user);
-
- return new JsonResponse([
- 'return' => 'success',
- 'message' => 'Le produit a bien été supprimé de vos favoris'
- ]);
- }
-
- private function _getUser()
- {
- $user = $this->getUserCurrent();
- if (!$user) {
- throw new \ErrorException('Vous devez être connecté pour gérer vos favoris');
- }
-
- return $user;
- }
-
- private function _saveUser($user)
- {
- $entityManager = $this->getEntityManager();
- $entityManager->persist($user);
- $entityManager->flush();
- }
-
- private function _getProductFamily($request)
- {
- $idProductFamily = $request->request->get('idProductFamily');
-
- if($idProductFamily) {
- $productFamily = $this->getProductFamilyContainer()->getStore()->getOneById($idProductFamily);
- }
-
- if (isset($productFamily) && $productFamily) {
- return $productFamily;
- } else {
- throw new \ErrorException('Ce produit est introuvable');
- }
- }
- }
|