src/Controller/ProductController.php line 19

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\OrderItem;
  4. use App\Entity\Product;
  5. use App\Form\AddToCartType;
  6. use App\Manager\CartManager;
  7. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use Symfony\Component\HttpFoundation\Response;
  10. use Symfony\Component\Routing\Annotation\Route;
  11. class ProductController extends AbstractController
  12. {
  13. /**
  14. * @Route("/product/{slug}", name="product")
  15. */
  16. public function index(Product $product, Request $request, CartManager $cartManager): Response
  17. {
  18. $order_item = new OrderItem();
  19. $form = $this->createForm(AddToCartType::class, $order_item->setProducts($product));
  20. $form->handleRequest($request);
  21. if ($form->isSubmitted() && $form->isValid()) {
  22. /** @var OrderItem $item */
  23. $item = $form->getData();
  24. $payment_option = $form->get('paymentOption')->getData();
  25. $installments_arr = $product->getInstallments()->toArray();
  26. $this->setInstallmentOption($item, $payment_option, $installments_arr);
  27. $item->setQuantity(1)
  28. ->setProducts($product);
  29. $cart = $cartManager->getCurrentCart();
  30. $cart
  31. ->addOrderItem($item);
  32. $cartManager->save($cart);
  33. return $this->redirectToRoute('cart');
  34. }
  35. return $this->render('product/index.html.twig', [
  36. 'controller_name' => 'ProductController',
  37. 'product' => $product,
  38. 'form' => $form->createView(),
  39. ]);
  40. }
  41. public function setInstallmentOption(OrderItem $item, $payment_option, $installments_arr)
  42. {
  43. foreach ($installments_arr as $installment) {
  44. if ($installment->getDuration() == $payment_option) {
  45. $item->setPaymentOption($installment);
  46. }
  47. }
  48. if (empty($item->getPaymentOption())) {
  49. foreach ($installments_arr as $installment) {
  50. if ($installment->getDuration() == '1 months') {
  51. $item->setPaymentOption($installment);
  52. }
  53. }
  54. }
  55. }
  56. }