src/Controller/ProductController.php line 92

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Doctrine\Persistence\ManagerRegistry;
  5. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\Routing\Annotation\Route;
  9. use Symfony\Component\HttpFoundation\JsonResponse;
  10. use Symfony\Contracts\Translation\TranslatorInterface;
  11. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  12. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  13. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  14. use App\Security\Voter\ProductVoter;
  15. use App\Repository\UserRepository;
  16. use App\Repository\OrderRepository;
  17. use App\Repository\BannerRepository;
  18. use App\Repository\ProductRepository;
  19. use App\Repository\ShoppingCartRepository;
  20. use App\Service\ActionService;
  21. use App\Service\UserSharedService;
  22. use App\Service\ShoppingCartService;
  23. use App\Entity\User;
  24. use App\Entity\Product;
  25. use App\Entity\UserShared;
  26. use Psr\Log\LoggerInterface;
  27. #[Route('/product')]
  28. class ProductController extends AbstractController
  29. {
  30.     private $logger;
  31.     private $translator;
  32.     public function __construct(
  33.         LoggerInterface $logger,
  34.         TranslatorInterface $translator
  35.     ) {
  36.         $this->logger $logger;
  37.         $this->translator $translator;
  38.     }
  39.     #[Route('/'name'app_product_index'methods: ['GET'])]
  40.     public function index(): Response
  41.     {
  42.         $this->logger->debug(__METHOD__);
  43.         return $this->redirectToRoute('app_index', [], 301);
  44.     }
  45.     #[Route('/favourite'name'app_product_favourite'methods: ['GET'])]
  46.     public function getAddressData(Request $requestProductRepository $productRepositoryManagerRegistry $manager): JsonResponse
  47.     {
  48.         $this->logger->debug(__METHOD__);
  49.         $productId $request->get('productId');
  50.         if (!$productId) {
  51.             return new JsonResponse([], Response::HTTP_BAD_REQUEST);
  52.         }
  53.         $product $productRepository->find($productId);
  54.         if (!$product) {
  55.             return new JsonResponse([], Response::HTTP_NOT_FOUND);
  56.         }
  57.         $result = [];
  58.         if ($this->getUser()->getFavouriteProducts()->contains($product)) {
  59.             $this->getUser()->removeFavouriteProduct($product);
  60.             $result false;
  61.         } else {
  62.             $this->getUser()->addFavouriteProduct($product);
  63.             $result true;
  64.         }
  65.         $manager->getManager()->flush();
  66.         return new JsonResponse($resultResponse::HTTP_OK, []);
  67.     }
  68.     #[Route('/{slug}'name'app_product_show'methods: ['GET'])]
  69.     public function show(
  70.         Product $product,
  71.         ActionService $actionService,
  72.         OrderRepository $orderRepository,
  73.         UserRepository $userRepository,
  74.         BannerRepository $bannerRepository,
  75.         AuthorizationCheckerInterface $authorizationChecker
  76.     ): Response {
  77.         $this->logger->debug(__METHOD__,  ["id" => $product->getId()]);
  78.         try {
  79.             //$this->denyAccessUnlessGranted(ProductVoter::CAN_SHOW_PRODUCT, $product);
  80.             if (!$authorizationChecker->isGranted(ProductVoter::CAN_SHOW_PRODUCT$product)) {
  81.                 throw new AccessDeniedException('No tienes permiso para ver este producto.');
  82.             }
  83.             $hasAlreadyBought $orderRepository->existsAnOrderForThisProduct($this->getUser(), $product);
  84.             $parameters = [
  85.                 'product'           => $product,
  86.                 'hasAlreadyBought'  => $hasAlreadyBought,
  87.                 'footerBanner'      => $bannerRepository->findByKey('footer_banner')->getQuery()->getOneOrNullResult(),
  88.                 'differentProducer' => false,
  89.             ];
  90.             /** @var \App\Entity\User */
  91.             $user $this->getUser();
  92.             if ($user) {
  93.                 $actionService->saveProductVisualizationAction($user$product);
  94.                 $cart $user->getShoppingCart();
  95.                 if ($cart) {
  96.                     foreach ($cart->getShoppingCartDetails() as $item) {
  97.                         if ($product->getProducer()->getId() !== $item->getProduct()->getProducer()->getId()) {
  98.                             $parameters['differentProducer'] = true;
  99.                         }
  100.                     }
  101.                 }
  102.             }
  103.             $parameters['friendUsersFavourites'] = $userRepository->getTriweersWhoHaveProductAsFavourite($product);
  104.             $parameters['friendUsersWhoBought']  = array_unique(
  105.                 array_merge($userRepository->getTriweersWhoBought($product), $product->getFakeTriweersInOffer()->toArray()),
  106.                 SORT_REGULAR
  107.             );
  108.             return $this->render('product/show.html.twig'$parameters);
  109.         }catch (AccessDeniedException $e) {
  110.             return $this->redirectToRoute('app_index', [], 301);
  111.         } catch (AuthenticationException $e) {
  112.             return $this->redirectToRoute('login');
  113.         }
  114.     }
  115.     /**
  116.      * Validates the token 
  117.      */
  118.     #[Route('/{slug}/{token}'name'app_product_show_with_token')]
  119.     public function showWithToken(
  120.         Request $request,
  121.         Product $product,
  122.         UserSharedService $userSharedService,
  123.         string $token
  124.     ): Response {
  125.         $this->denyAccessUnlessGranted(ProductVoter::CAN_SHOW_PRODUCT$product);
  126.         if (!$token) {
  127.             throw $this->createNotFoundException('No token found in the URL.');
  128.         }
  129.         if (!$userSharedService->checkIfTokenIsValid($token)) {
  130.             throw $this->createNotFoundException('Invalid token found in the URL.');
  131.         }
  132.         $request->getSession()->set(UserShared::TOKEN_NAME$token);
  133.         return $this->redirectToRoute('app_product_show', ['slug' => $product->getSlug()]);
  134.     }
  135.     /**
  136.      * Add a product to the shopping cart and go to shoppingcart view
  137.      */
  138.     #[Route('/shopping-cart/{id}'priority10name'app_product_add_to_shopping_cart'methods: ['GET'])]
  139.     #[IsGranted('buy_product'subject'product')]
  140.     public function addProductToShoppingCart(
  141.         Product $product,
  142.         ShoppingCartService $shoppingCartService,
  143.         ShoppingCartRepository $shoppingCartRepository,
  144.         Request $request
  145.     ): Response {
  146.         /** @var User */
  147.         $loggedUser $this->getUser();
  148.         $this->logger->debug(__METHOD__,  ["userId" => $loggedUser->getId(), "productId" => $product->getId()]);
  149.         $betterPrice $request->cookies->get('better_price') == 'yes';
  150.         $cart        $loggedUser->getShoppingCart();
  151.         if ($cart) {
  152.             if ($request->get('newCart')) {
  153.                 $shoppingCartRepository->remove($loggedUser->getShoppingCart(), true);
  154.                 $loggedUser->emptyShoppingCart();
  155.                 $shoppingCartService->createShoppingCart($loggedUser$product$betterPrice$request->get('isIndividual'));
  156.             } else {
  157.                 $shoppingCartService->addProductToCart($cart$product);
  158.             }
  159.         } else {
  160.             $shoppingCartService->createShoppingCart($loggedUser$product$betterPrice$request->get('isIndividual'));
  161.         }
  162.         return $this->redirectToRoute("app_shopping_cart");
  163.     }
  164.     /**
  165.      * Add a product to the shopping cart and go to shoppingcart view
  166.      */
  167.     #[Route('/shopping-cart/{id}/ajax'priority10name'app_product_add_to_shopping_cart_ajax'methods: ['POST'])]
  168.     #[IsGranted('buy_product'subject'product')]
  169.     public function addProductToShoppingCartAjax(
  170.         Product $product,
  171.         ShoppingCartService $shoppingCartService,
  172.         Request $request
  173.     ): Response {
  174.         /** @var User */
  175.         $loggedUser $this->getUser();
  176.         $this->logger->debug(__METHOD__,  ["userId" => $loggedUser->getId(), "productId" => $product->getId()]);
  177.         $betterPrice $request->cookies->get('better_price') == 'yes';
  178.         $cart        $loggedUser->getShoppingCart();
  179.         $cart
  180.             $shoppingCartService->addProductToCart($cart$product)
  181.             : $shoppingCartService->createShoppingCart($loggedUser$product$betterPrice0);
  182.         $qtyCount = ($loggedUser && $loggedUser->getShoppingCart())
  183.             ? $loggedUser->getShoppingCart()->getShoppingCartDetails()->reduce(fn($sum$i) => $sum $i->getQuantity())
  184.             : 0;
  185.         return new JsonResponse($qtyCountResponse::HTTP_OK, []);
  186.     }
  187. }