Skip to content

Instantly share code, notes, and snippets.

@samijnih
Last active October 25, 2022 23:19
Show Gist options
  • Save samijnih/d4e8a050c344ab26313d569550c97570 to your computer and use it in GitHub Desktop.
Save samijnih/d4e8a050c344ab26313d569550c97570 to your computer and use it in GitHub Desktop.
BDD contrainte - Legacy - CartController
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Entity\Cart;
use App\Entity\Product;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
class CartController
{
#[Route('/carts/{id}/products', 'methods': ['POST'])]
public function addProductToCart(
Cart $cart,
Request $request,
ManagerRegistry $doctrine
): JsonResponse {
$quantity = $request->request->get('quantity', 1);
if ($quantity < 1) {
$quantity = 1;
}
$productId = $request->request->get('product_id', null);
$product = $doctrine->getRepository(Product::class)->find($productId);
if ($quantity > $product->getQuantity()) {
return new JsonResponse(null, 400);
}
$product->setQuantity($quantity);
$cart->addProduct($product);
$entityManager = $doctrine->getManager();
$entityManager->flush();
return new JsonResponse([], 201);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment