src/Controller/MainController.php line 65

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Form\UserModificationFormType;
  5. use App\Repository\CategoryRepository;
  6. use App\Repository\ProductRepository;
  7. use App\Repository\UserRepository;
  8. use App\Services\Cart;
  9. use App\Services\SearchFilterPagination;
  10. use App\Services\Pagination;
  11. use App\Services\SearchProductsPagination;
  12. use Doctrine\ORM\EntityManagerInterface;
  13. use Exception;
  14. use Google\Service\CloudResourceManager\SearchProjectsResponse;
  15. use Google\Service\CustomSearchAPI\Search;
  16. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  17. use Symfony\Component\HttpFoundation\JsonResponse;
  18. use Symfony\Component\HttpFoundation\Request;
  19. use Symfony\Component\HttpFoundation\Response;
  20. use Symfony\Component\Mailer\MailerInterface;
  21. use Symfony\Component\Mime\Email;
  22. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  23. use Symfony\Component\Routing\Annotation\Route;
  24. use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
  25. class MainController extends AbstractController
  26. {
  27.     #[Route('/'name'app_home')]
  28.     public function index(ProductRepository $productRepoCategoryRepository $catRepoRequest $request): Response
  29.     {
  30.         $products $productRepo->findAll();
  31.         $categories $catRepo->findAll();
  32.         
  33.         //TO COPY TO EVERY ROUTE THAT DISPLAY CART
  34.         $session $request->getSession();
  35.         $cart = new Cart($session);
  36.         $totalQuantity $cart->getCartTotalQuantity();
  37.         $maxQuantity $cart->getMaxQuantityAllowed();
  38.         $cartProducts $cart->getCartProducts($productRepo);
  39.         $totalPrice $cart->getTotalPrice($productRepo);
  40.         $response $this->render('main/index.html.twig', [
  41.             'products' => $products,
  42.             'categories' => $categories,
  43.             //TO COPY TO EVERY ROUTE THAT DISPLAY CART
  44.             'totalQuantity' => $totalQuantity,
  45.             'maxQuantity' => $maxQuantity,
  46.             'cartProducts' => $cartProducts,
  47.             'totalPrice' => $totalPrice,
  48.         ]);
  49.         
  50.         $response->headers->set('Cache-Control',
  51.         'no-store, no-cache, must-revalidate, max-age=0');
  52.         $response->headers->set('Pragma''no-cache');
  53.         $response->headers->set('Expires''0');
  54.         
  55.         return $response;
  56.     }
  57.     #[Route('/produit/{id}'name'product')]
  58.     public function produit($idRequest $requestProductRepository $productRepoCategoryRepository $catRepo): Response
  59.     {
  60.         $product $productRepo->find($id);
  61.         $categories $catRepo->findAll();
  62.         $session $request->getSession();
  63.         $cart = new Cart($session);
  64.         $totalQuantity $cart->getCartTotalQuantity();
  65.         $maxQuantity $cart->getMaxQuantityAllowed();
  66.         $cartProducts $cart->getCartProducts($productRepo);
  67.         $totalPrice $cart->getTotalPrice($productRepo);
  68.         $stock $product->getStock();
  69.         
  70.         $comeFromPage $request->headers->get('referer');
  71.         //Get instagram links
  72.         $filePath $this->getParameter('kernel.project_dir').'/public/instagram_links.json';
  73.         $jsonFile file_get_contents($filePath);
  74.         $instagramLinks json_decode($jsonFiletrue);
  75.         
  76.         return $this->render('main/product.html.twig',
  77.         [
  78.             'product' => $product,
  79.             'categories' => $categories,
  80.             'comeFromPage' => $comeFromPage,
  81.             'totalQuantity' => $totalQuantity,
  82.             'maxQuantity' => $maxQuantity,
  83.             'cartProducts' => $cartProducts,
  84.             'totalPrice' => $totalPrice,
  85.             'stock' => $stock,
  86.             'instagramLinks' => $instagramLinks,
  87.             'test' => $cart->test()
  88.         ]);
  89.     }
  90.     //DOUBLON ACCOUNT ! VOIR REGISTRATION CONTROLLER ! Vérifier l'utilité de cette route !
  91.     #[Route('/account'name'account')]
  92.     public function account(CategoryRepository $catRepoRequest $request): Response
  93.     {
  94.         $categories $catRepo->findAll();
  95.         //TO COPY TO EVERY ROUTE THAT DISPLAY CART
  96.         $session $request->getSession();
  97.         $cart = new Cart($session);
  98.         $totalQuantity $cart->getCartTotalQuantity();        
  99.         return $this->render('main/account.html.twig', [
  100.             'categories' => $categories
  101.             'totalQuantity' => $totalQuantity
  102.         ]);
  103.     }
  104.     #[Route('/user-account'name'user_account')]
  105.     public function userAccount(ProductRepository $productRepoCategoryRepository $catRepoRequest $request): Response
  106.     {
  107.         $categories $catRepo->findAll();
  108.         //TO COPY TO EVERY ROUTE THAT DISPLAY CART
  109.         $session $request->getSession();
  110.         $cart = new Cart($session);
  111.         $totalQuantity $cart->getCartTotalQuantity();
  112.         $maxQuantity $cart->getMaxQuantityAllowed();
  113.         $cartProducts $cart->getCartProducts($productRepo);
  114.         $totalPrice $cart->getTotalPrice($productRepo); 
  115.         return $this->render('account/user_account.html.twig', [
  116.             'categories' => $categories,
  117.             //TO COPY TO EVERY ROUTE THAT DISPLAY CART
  118.             'totalQuantity' => $totalQuantity,
  119.             'maxQuantity' => $maxQuantity,
  120.             'cartProducts' => $cartProducts,
  121.             'totalPrice' => $totalPrice        
  122.         ]);
  123.     }
  124.     #[Route('/edit-account/{id}'name'edit_account')]
  125.     public function editAccount($idUserRepository $userRepoProductRepository $productRepoRequest $requestEntityManagerInterface $entityManagerCategoryRepository $catRepo): Response
  126.     {
  127.         $user $userRepo->find($id);
  128.         $categories $catRepo->findAll();
  129.         //TO COPY TO EVERY ROUTE THAT DISPLAY CART
  130.         $session $request->getSession();
  131.         $cart = new Cart($session);
  132.         $totalQuantity $cart->getCartTotalQuantity();   
  133.         $maxQuantity $cart->getMaxQuantityAllowed();
  134.         $cartProducts $cart->getCartProducts($productRepo);
  135.         $totalPrice $cart->getTotalPrice($productRepo);        
  136.         $form $this->createForm(UserModificationFormType::class, $user);
  137.         $form->handleRequest($request);
  138.         if ($form->isSubmitted() && $form->isValid())
  139.         {
  140.             $entityManager->flush();
  141.             //If $id == à celui de l'admin
  142.             //return $this->redirectToRoute('admin_index');
  143.             
  144.             return $this->redirectToRoute('user_account');
  145.         }
  146.         return $this->render('account/edit_account.html.twig', [
  147.             'categories' => $categories,
  148.             'form' => $form->createView(),
  149.             //TO COPY TO EVERY ROUTE THAT DISPLAY CART
  150.             'totalQuantity' => $totalQuantity,
  151.             'maxQuantity' => $maxQuantity,
  152.             'cartProducts' => $cartProducts,
  153.             'totalPrice' => $totalPrice
  154.         ]);
  155.     }
  156.     #[Route('/change-user-password'name:('change_user_password'))]
  157.     public function changeUserPassword(Request $requestUserPasswordHasherInterface $passwordHasherEntityManagerInterface $em): JsonResponse
  158.     {
  159.         //Ecrire les intructions du mot de passe coté client (min 8, max 64)
  160.         $data json_decode($request->getContent(), true);
  161.         try
  162.         {
  163.             if (!$data || !isset($data['newPass'])) {
  164.                 throw new Exception('Données manquantes : le mot de passe est requis.');
  165.             }
  166.             $newPassword $data['newPass'];
  167.             $user $this->getUser();
  168.             $passwordLength strlen($newPassword);
  169.             if ($passwordLength || $passwordLength 64) {
  170.                 throw new Exception('Le mot de passe doit contenir entre 8 et 64 caractères.');
  171.             }
  172.             if (preg_match('/[<>&\'"\/]/'$newPassword)) {
  173.                 throw new Exception('Le mot de passe contient des caractères non autorisés.');
  174.             }
  175.             $encodedPassword $passwordHasher->hashPassword($user$newPassword);
  176.             $user->setPassword($encodedPassword);
  177.             $em->persist($user);
  178.             $em->flush();
  179.             $this->addFlash('success'"Nouveau mot de passe enregistré !");
  180.             return new JsonResponse([
  181.                 "status" => "ok",
  182.                 "message" => "Pass bien reçus",
  183.                 "password" => $newPassword
  184.             ], 200); 
  185.         }
  186.         catch(Exception $e)
  187.         {
  188.             return new JsonResponse([
  189.                 'status' => 'error',
  190.                 'message' => $e->getMessage()
  191.             ], 400);
  192.         }
  193.         return new JsonResponse([
  194.             "status custom" => "ok",
  195.             "message" => "Pass bien reçus",
  196.             "password" => $newPassword
  197.         ], 200); 
  198.     }
  199.     #[Route('/all-products-category/{page}'name'all_products_category')]
  200.     public function allProductsCategory(ProductRepository $productRepoCategoryRepository $catRepoRequest $request$page 1): Response
  201.     {
  202.         $products $productRepo->findAll();
  203.         $categories $catRepo->findAll();
  204.         //TO COPY TO EVERY ROUTE THAT DISPLAY CART
  205.         $session $request->getSession();
  206.         $cart = new Cart($session);
  207.         $totalQuantity $cart->getCartTotalQuantity();           
  208.         //PAGINATION
  209.         //Change this value to set ne numbers of products per pages
  210.         $productsPerPage 3;
  211.         $pageToDisplay $page 1;
  212.         $currentPage $page;
  213.         $totalProducts count($products);
  214.         $totalPages $totalProducts 3;
  215.         for ($i 0$i <= $totalPages 1$i++)
  216.         {
  217.             $pageContent[] = array_slice($products$i $productsPerPage$productsPerPage);
  218.         }
  219.         return $this->render('main/all_products_category.html.twig', [
  220.             'products' => $pageContent[$pageToDisplay],
  221.             'categories' => $categories,
  222.             'currentPage' => $currentPage,
  223.             'maxPage' => count($pageContent),
  224.             //TO COPY TO EVERY ROUTE THAT DISPLAY CART
  225.             'totalQuantity' => $totalQuantity
  226.             
  227.         ]);
  228.     }
  229.     #[Route('/products-category/{id}'name'products_category')]
  230.     public function productsCategory($idCategoryRepository $catRepoProductRepository $productRepoRequest $request): Response
  231.     {
  232.         $selectedCategory $catRepo->find($id);
  233.         $categories $catRepo->findAll();
  234.         //TO COPY TO EVERY ROUTE THAT DISPLAY CART
  235.         $session $request->getSession();
  236.         $cart = new Cart($session);
  237.         $totalQuantity $cart->getCartTotalQuantity();
  238.         $cartProducts $cart->getCartProducts($productRepo);
  239.         $totalPrice $cart->getTotalPrice($productRepo);       
  240.         return $this->render('main/products_category.html.twig', [
  241.             'category' => $selectedCategory,
  242.             'categories' => $categories,
  243.             //TO COPY TO EVERY ROUTE THAT DISPLAY CART
  244.             'totalQuantity' => $totalQuantity,
  245.             'cartProducts' => $cartProducts,
  246.             'totalPrice' => $totalPrice
  247.         ]);
  248.     }
  249.     #[Route('filtre-produit'name:'products_filter')]
  250.     public function productsFilter(Request $requestProductRepository $productRepoCategoryRepository $catRepo): Response
  251.     {
  252.         $categories $catRepo->findAll();
  253.         //TO COPY TO EVERY ROUTE THAT DISPLAY CART
  254.         $session $request->getSession();
  255.         $cart = new Cart($session);
  256.         $cartProducts $cart->getCartProducts($productRepo);
  257.         $totalPrice $cart->getTotalPrice($productRepo);
  258.         $totalQuantity $cart->getCartTotalQuantity();   
  259.         $maxQuantity $cart->getMaxQuantityAllowed();
  260.         $products = [];
  261.         $pageAsked 0;
  262.         $productsByCategoryRequested $request->query->all();
  263.         if ($request->query->has('category'))
  264.         {
  265.             if (count($productsByCategoryRequested) == 0)
  266.             {
  267.                 //dd('Array empty');
  268.                 $products $productRepo->findAll();
  269.             }
  270.             else
  271.             {
  272.                 //dd('There is a request');
  273.                 if (!is_array($productsByCategoryRequested['category']))
  274.                 {
  275.                     //dd('Single request');
  276.                     $products $productRepo->findBy(['category' => $productsByCategoryRequested['category']]);
  277.     
  278.                 }
  279.     
  280.                 if (is_array($productsByCategoryRequested['category']))
  281.                 {
  282.                     //dd('Multiple request');
  283.                     $productsByCategories = [];
  284.                     $products = [];
  285.     
  286.                     foreach ($productsByCategoryRequested['category'] as $id)
  287.                     {
  288.                         $productsByCategories[] = $productRepo->findBy(['category' => $id]);
  289.                     }
  290.                     foreach ($productsByCategories as $categoriesOfProducts)
  291.                     {
  292.                         
  293.                         $products array_merge($categoriesOfProducts$products); 
  294.                     }
  295.                     
  296.                 }
  297.     
  298.             }
  299.         }
  300.         else
  301.         {
  302.             $products $productRepo->findAll();
  303.         }
  304.         if($request->query->has('price-range'))
  305.         {
  306.             //Obtenir le price range
  307.             $priceRange $request->query->all('price-range')[0];
  308.             list($range1$range2) = explode('-'$priceRange);
  309.             $range1 = (int)$range1;
  310.             $range2 = (int)$range2;
  311.             $sortedByPriceProducts = [];
  312.             //dd($range2);
  313.             foreach($products as $product)
  314.             {
  315.                 $productPrice $product->getPrice();
  316.                 if ($productPrice >= $range1 && $productPrice $range2)
  317.                 {
  318.                    $sortedByPriceProducts[] = $product;
  319.                 }
  320.             }
  321.             $products $sortedByPriceProducts;
  322.             
  323.         }
  324.         
  325.         if($request->query->has('page'))
  326.         {
  327.             $pageAsked $request->query->get('page');
  328.         }
  329.         //Change this value to automaticaly change the numbers of pages according to products to display wished
  330.         $numberOfProductsToDisplayPerPages 10;
  331.         $pagination = new Pagination($products$numberOfProductsToDisplayPerPages);
  332.         $paginatedProducts $pagination->makePagination($pageAsked);
  333.         //dd($pagination->getStatus());
  334.         return $this->render('main/products_filter.html.twig', [
  335.             'products' => $products,
  336.             'numberOfProductsToDisplayPerPages' => $numberOfProductsToDisplayPerPages,
  337.             'paginatedProducts' => $paginatedProducts,
  338.             'categories' => $categories,
  339.             'currentPage' => $pagination->getCurrentPage(),
  340.             'maxPage' => $pagination->getMaxPage(),
  341.             //TO COPY TO EVERY ROUTE THAT DISPLAY CART
  342.             'cartProducts' => $cartProducts,
  343.             'totalPrice' => $totalPrice,
  344.             'totalQuantity' => $totalQuantity,
  345.             'maxQuantity' => $maxQuantity,
  346.         ]);
  347.     }
  348.     #[Route('/contact'name:'contact')]
  349.     public function contacts(CategoryRepository $catRepo): Response
  350.     {
  351.         $categories $catRepo->findAll();
  352.         return $this->render('main/contact.html.twig', [
  353.             'categories' => $categories
  354.         ]);
  355.     }
  356.     #[Route('/recherche-produits/{pageAsked}'name'search_products'methods: ['GET''POST'])]
  357.     public function searchProducts(Request $requestProductRepository $productRepoCategoryRepository $catRepoint $pageAsked 0)
  358.     {
  359.         
  360.         $categories $catRepo->findAll();
  361.         $filters $request->query->all();
  362.         
  363.         if (!$filters)
  364.         {   
  365.             //Pas de reqête GET donc je dois récupérer la requête POST
  366.             // LE PROBLEME EST ICI !!!
  367.             $terms $request->request->get('terms_to_search');
  368.             //Je pense que c'est résolut avec la conditionnel suivante:
  369.             if ($request->headers->get('Content-Type') === 'application/json')
  370.             {
  371.                 $data json_decode($request->getContent(), true);
  372.                 $terms $data['terms_to_search'] ?? '';
  373.             }
  374.         }
  375.         else
  376.         {
  377.             $data json_decode($request->getContent(), true);
  378.             $terms $data['terms_to_search'] ?? '';
  379.             //$terms = "trevor";
  380.         }
  381.         
  382.         //TO COPY TO EVERY ROUTE THAT DISPLAY CART
  383.         $session $request->getSession();
  384.         $cart = new Cart($session);
  385.         $totalQuantity $cart->getCartTotalQuantity();
  386.         $maxQuantity $cart->getMaxQuantityAllowed();
  387.         $cartProducts $cart->getCartProducts($productRepo);
  388.         $totalPrice $cart->getTotalPrice($productRepo);   
  389.         $results $productRepo->fulltextSearch($terms);
  390.     
  391.         //FILTERS
  392.         if($filters)
  393.         {
  394.             if (isset($filters["category"]) && $filters["category"] !== '')
  395.             {
  396.                 $selectedFilters = [...$filters["category"]];
  397.     
  398.                 
  399.                 //PHASE I vérification des categories
  400.                 $filteredProducts = [];
  401.     
  402.     
  403.                 //Boucle sur les produits du $result initial de la recherche fullText
  404.                 foreach ($results as $result)
  405.                 {
  406.                     if (in_array($result->getCategory()->getName(), $selectedFilters))
  407.                     {
  408.                         array_push($filteredProducts$result);
  409.                     }
  410.                 }
  411.     
  412.     
  413.                 $results $filteredProducts;
  414.             }
  415.             
  416.         }
  417.         if (isset($filters["price-range"]) && $filters["price-range"] !== '')
  418.         {
  419.             $filteredProdcutsWithPriceRange = [];
  420.             
  421.             foreach($results as $result)
  422.             {
  423.                 $price $result->getPrice();
  424.                 $priceRange $filters["price-range"][0];
  425.                 list($min$max) = explode('-'$priceRange);
  426.                 $min = (float) $min;
  427.                 $max = (float) $max;
  428.                 if ($price >= $min && $price <= $max)
  429.                 {
  430.                     array_push($filteredProdcutsWithPriceRange$result);
  431.                 }
  432.                 $results $filteredProdcutsWithPriceRange;
  433.             }
  434.         }
  435.         
  436.         if (!$results)
  437.         {
  438.             $result = [];
  439.         }
  440.         
  441.         //PAGINATION
  442.         $SearchProductsPagination = new SearchProductsPagination($results2$pageAsked4);
  443.         return $this->render('main/search_results.html.twig', [
  444.             //Fulltext search
  445.             'terms' => $terms,
  446.             'results' => $SearchProductsPagination->paginatedProducts(),
  447.             //Pagination
  448.             'pageAsked' => $pageAsked,
  449.             'numberOfPages' => $SearchProductsPagination->getNumberOfPages(),
  450.             'selectorOffset' => $SearchProductsPagination->getNumberOfSelectorPageToDisplay(),
  451.             'categories' => $categories,        
  452.             'totalQuantity' => $totalQuantity,
  453.             'maxQuantity' => $maxQuantity,
  454.             'cartProducts' => $cartProducts,        
  455.             'totalPrice' => $totalPrice,
  456.         ]);
  457.         
  458.     }
  459.     
  460.     #[Route('/add-to-cart/{id}/{quantity}/{customerCustomMessage?}/{customerCustomPolice?}/{customerCustomImage?}'name'add_to_cart')]
  461.     public function addToCart(int $idint $quantity 1, ?string $customerCustomMessage null, ?string $customerCustomPolice null, ?string $customerCustomImage nullRequest $requestProductRepository $productRepo): JsonResponse
  462.     {
  463.         $cart = new Cart($request->getSession());
  464.         $productToAdd $productRepo->find($id);
  465.     
  466.         if (!$productToAdd) {
  467.             return $this->json(['success' => false'error' => 'Produit introuvable.'], 404);
  468.         }
  469.     
  470.         $productStock $productToAdd->getStock();
  471.     
  472.         // Validation quantité
  473.         if ($quantity 1) {
  474.             return $this->json(['success' => false'error' => 'La quantité doit être au moins 1.'], 400);
  475.         }
  476.     
  477.         if ($quantity $productStock) {
  478.             return $this->json(['success' => false'error' => 'Quantité demandée supérieure au stock disponible.'], 400);
  479.         }
  480.     
  481.         // Customizable data protections
  482.         $messageMaxLength 200;
  483.         $policeMinNumber 1;
  484.         $policeMaxNumber 10;
  485.         $imageMinNumber 1;
  486.         $imageMaxNumber 5;
  487.         if ($customerCustomMessage !== null || $customerCustomPolice !== null || $customerCustomImage !== null)
  488.         {
  489.             // Validation message (si présent)
  490.             if ($customerCustomMessage !== null) {
  491.                 if ($customerCustomMessage === 'undefined' || trim($customerCustomMessage) === '') {
  492.                     return $this->json(['success' => false'error' => 'Message personnalisé invalide.'], 400);
  493.                 }
  494.             
  495.                 $messagePattern '/^[\p{L}0-9 _\-?!\']{1,' $messageMaxLength '}$/u';
  496.                 if (!preg_match($messagePattern$customerCustomMessage)) {
  497.                     return $this->json(['success' => false'error' => 'Message personnalisé invalide.'], 400);
  498.                 }
  499.             }
  500.             
  501.             // Validation police (si présente)
  502.             if ($customerCustomPolice !== null) {
  503.                 if (!ctype_digit($customerCustomPolice)) {
  504.                     return $this->json(['success' => false'error' => 'Style du texte doit être un entier.'], 400);
  505.                 }
  506.         
  507.                 $policeValue = (int) $customerCustomPolice;
  508.                 if ($policeValue $policeMinNumber || $policeValue $policeMaxNumber) {
  509.                     return $this->json(['success' => false'error' => "Style du texte doit être entre $policeMinNumber et $policeMaxNumber."], 400);
  510.                 }
  511.             }
  512.         
  513.             // Validation image (si présente)
  514.             if ($customerCustomImage !== null) {
  515.                 if (!ctype_digit($customerCustomImage)) {
  516.                     return $this->json(['success' => false'error' => 'Motif doit être un entier.'], 400);
  517.                 }
  518.         
  519.                 $imageValue = (int) $customerCustomImage;
  520.                 if ($imageValue $imageMinNumber || $imageValue $imageMaxNumber) {
  521.                     return $this->json(['success' => false'error' => "Motif doit être entre $imageMinNumber et $imageMaxNumber."], 400);
  522.                 }
  523.             }
  524.         }
  525.         
  526.     
  527.         // Ajout au panier
  528.         $cart->addToCart($id$quantity$customerCustomMessage$customerCustomPolice$customerCustomImage);
  529.     
  530.         return $this->json([
  531.             'success' => true,
  532.             'cart' => $cart->getCart()
  533.         ]);
  534.     }
  535.     #[Route('/get-product-stock/{id}'name:'get_product_stock')]
  536.     public function getProductStock($idProductRepository $productRepo): JsonResponse
  537.     {
  538.         $product $productRepo->find($id);
  539.         $productStock $product->getStock();
  540.         return $this->json($productStock);
  541.     }
  542.     /**
  543.      * Cart edition. Use requested id to compare with present product id
  544.      * inside cart session if exist.
  545.      */
  546.     #[Route('/edit-cart/{id}/{quantity}'name'edit_cart')]
  547.     public function editCart($id$quantity 1Request $request): JsonResponse
  548.     {
  549.         $quantity intval($quantity);
  550.         $cart = new Cart($request->getSession());
  551.         $maxQuantity $cart->getMaxQuantityAllowed();
  552.         if ($cart->cartSessionExists())
  553.         {
  554.             $cartContent $cart->getCart();
  555.             foreach($cartContent as $contentId => $content)
  556.             {
  557.                 if ($id == $contentId)
  558.                 {
  559.                     if ($quantity === 0)
  560.                     {
  561.                         unset($cartContent[$contentId]);
  562.                         $cart->setCartContent($cartContent);
  563.                     }
  564.                     elseif ($quantity != $content['quantity'] && $quantity >= && $quantity <= $maxQuantity)
  565.                     {
  566.                         $cartContent[$id]['quantity'] = $quantity;
  567.                         $cart->setCartContent($cartContent);
  568.                     }
  569.                 }
  570.             }
  571.         }
  572.         return $this->json($cart->getCart());
  573.     }
  574.     #[Route('/check-cart-content'name'check_cart_content')]
  575.     public function checkCartContent(Request $requestProductRepository $productRepo): JsonResponse
  576.     {
  577.         $session $request->getSession();
  578.         $cart = new Cart($session);
  579.         $cartContent $cart->getCartProducts($productRepo);
  580.         dd($cartContent);
  581.         return $this->json($cartContent);
  582.     }
  583.     
  584.     #[Route('/check-cart-quantity'name'check_cart_quantity')]
  585.     public function checkCart(Request $request): Response
  586.     {
  587.         $session $request->getSession();
  588.         $cart = new Cart($session);
  589.         $totalQuantity $cart->getCartTotalQuantity();
  590.         return new Response($totalQuantityResponse::HTTP_OK, [
  591.             'Content-Type' => 'text/plain',
  592.         ]);
  593.     }
  594.     #[Route('/clear-cart'name'clear_cart')]
  595.     public function clearCart(Request $request): Response
  596.     {
  597.         $session $request->getSession();
  598.         $session->remove('cart');
  599.         return new Response('Session cleared !'Response::HTTP_OK, [
  600.             'Content-Type' => 'text/plain'
  601.         ]);
  602.     }
  603.     #[Route('/test-mail'name'test_mail')]
  604.     public function testMail(MailerInterface $mailer)
  605.     {
  606.         $email = (new Email())
  607.             ->from('no-reply@example.com')
  608.             ->to('user@example.com')
  609.             ->subject('Test Mail')
  610.             ->text('This is a test email sent to MailHog.')
  611.             ->html('<p>This is a test email sent to MailHog.</p>');
  612.         $mailer->send($email);
  613.         return new Response('Mail sent to MailHog!');
  614.     }
  615.     #[Route('/politique-confidentialite'name'politique_confidentialite')]
  616.     public function informationPage(Request $requestProductRepository $productRepoCategoryRepository $catRepo)
  617.     {
  618.         $categories $catRepo->findAll();
  619.         $session $request->getSession();
  620.         $cart = new Cart($session);
  621.         $totalQuantity $cart->getCartTotalQuantity();
  622.         $maxQuantity $cart->getMaxQuantityAllowed();
  623.         $cartProducts $cart->getCartProducts($productRepo);
  624.         $totalPrice $cart->getTotalPrice($productRepo);
  625.         return $this->render('main/politique-confidentialite.html.twig', [
  626.             'categories' => $categories,
  627.             'totalQuantity' => $totalQuantity,
  628.             'maxQuantity' => $maxQuantity,
  629.             'cartProducts' => $cartProducts,
  630.             'totalPrice' => $totalPrice,
  631.             'title' => 'politique de confidentialité'                      
  632.         ]);
  633.     }
  634.     #[Route('/cgv'name'cgv')]
  635.     public function cgv(Request $requestProductRepository $productRepoCategoryRepository $catRepo)
  636.     {
  637.         $categories $catRepo->findAll();
  638.         $session $request->getSession();
  639.         $cart = new Cart($session);
  640.         $totalQuantity $cart->getCartTotalQuantity();
  641.         $maxQuantity $cart->getMaxQuantityAllowed();
  642.         $cartProducts $cart->getCartProducts($productRepo);
  643.         $totalPrice $cart->getTotalPrice($productRepo);
  644.         return $this->render('main/cgv.html.twig', [
  645.             'categories' => $categories,
  646.             'totalQuantity' => $totalQuantity,
  647.             'maxQuantity' => $maxQuantity,
  648.             'cartProducts' => $cartProducts,
  649.             'totalPrice' => $totalPrice,
  650.             'title' => 'Conditions générales de vente'                    
  651.         ]);
  652.     }
  653.     #[Route('/test'name:'test')]
  654.     public function test(Request $requestProductRepository $productRepoCategoryRepository $catRepo): Response
  655.     {
  656.         //dd($user);
  657.         $session $request->getSession();
  658.         $cart = new Cart($session);
  659.         $cartProducts $cart->getCartProducts($productRepo);
  660.         $cartProductsLength count($cartProducts);
  661.         //$productsStocks = [];
  662.         for ($i 0$i $cartProductsLength $i++)
  663.         {
  664.             $productId $cartProducts[$i]["product"]->getId();
  665.             $productName $cartProducts[$i]["product"]->getName();
  666.             $productQuantityAsked $cartProducts[$i]["quantity"];
  667.             $productStockData $this->forward('App\Controller\MainController::getProductStock', [
  668.                 'id' => $productId,
  669.             ]);
  670.             $productStock intvaljson_decode($productStockData->getContent(), true));
  671.             if ($productQuantityAsked $productStock)
  672.             {
  673.                 throw new Exception('Le produit '.$productName.'n\'est plus disponible');
  674.             }
  675.             
  676.         }
  677.         dd($productStockData);
  678.     }
  679. }