<?php
namespace MLDev\OrderBundle\Controller;
use App\Service\Promocode\Promocode;
use MLDev\BaseBundle\Controller\FrontController;
use MLDev\BaseBundle\Service\PageManager;
use MLDev\OrderBundle\Service\Cart\ProviderInterface;
use MLDev\OrderBundle\Service\CartService;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* Class CartController
* @package MLDev\OrderBundle\Controller
*/
class CartController extends FrontController
{
/**
* @var Request
*/
private $request;
/**
* @var CartService
*/
private $cartService;
/**
* BasketController constructor.
*/
public function __construct(CartService $cartService, RequestStack $requestStack)
{
$this->cartService = $cartService;
$this->request = $requestStack->getCurrentRequest();
}
/**
* @Route("/cart", methods={"GET", "POST"}, name="mldev-front-cart-index")
*/
public function indexAction(ProviderInterface $provider, PageManager $pageManager): Response
{
$entity = $pageManager->createVirtualEntity('Корзина', '/cart');
return $this->renderCustomTemplate($entity, '@MLDevOrder/cart/index.html.twig', [
'cartItems' => $this->cartService->getCartItems(),
'cost' => $provider->getCost(),
'count' => $provider->getCount(),
'items' => $provider->getItems(),
]);
}
/**
* @Route("/cart/details", methods={"GET", "POST"}, name="mldev-front-cart-details", defaults={"_format": "json"})
*/
public function detailsAction(ProviderInterface $provider, Promocode $promocode): JsonResponse
{
$code = $promocode->get();
return $this->json(
[
'promocode' => $code ? $code->getCode() : null,
'promocode_discount' => $code ? $code->getDiscount() : null,
'cost' => $provider->getCost(),
'count' => $provider->getCount(),
'items' => $provider->getItems(),
'cart_url' => $this->generateUrl('mldev-front-cart-index'),
'order_url' => $this->generateUrl('mldev-front-order-index')
]
);
}
/**
* @Route("/cart/set", methods={"POST"}, name="mldev-front-cart-set", defaults={"_format": "json"})
*/
public function setAction(): JsonResponse
{
$data = json_decode($this->request->getContent(), true);
$id = (isset($data['id']) ? (integer)$data['id'] : 0);
$count = (isset($data['count']) ? (integer)$data['count'] : 0);
return $this->json(
$this->cartService->getStorage()->set($id, $count)
);
}
/**
* @Route("/cart/remove", methods={"POST"}, name="mldev-front-cart-remove", defaults={"_format": "json"})
*/
public function removeAction(): JsonResponse
{
$data = json_decode($this->request->getContent(), true);
$id = (isset($data['id']) ? (integer)$data['id'] : 0);
return $this->json(
$this->cartService->getStorage()->remove($id)
);
}
/**
* @Route("/cart/clear", methods={"POST"}, name="mldev-front-cart-clear", defaults={"_format": "json"})
*/
public function clearAction(): JsonResponse
{
$this->cartService->clearCart();
return $this->json([]);
}
}