File: D:/HostingSpaces/SBogers10/shop.komma.nl/app/Cart/ShoppingCartController.php
<?php
namespace App\Cart;
use App\Base\Controller;
use App\Pages\PageService;
use App\Cart\Requests\AddProductableRequest;
use App\Cart\Requests\RemoveProductRequest;
use App\Cart\Requests\UpdateProductableQuantityRequest;
use App\Discounts\DiscountServiceInterface;
use App\Products\ProductableEnum;
use Illuminate\Contracts\View\View;
use Symfony\Component\HttpFoundation\JsonResponse;
/**
* Represents a shopping cart
*
* Class ShoppingCart
* @package App\Cart
*/
class ShoppingCartController extends Controller
{
/**
* @var DiscountServiceInterface $discountService
*/
private $discountService;
public function __construct(PageService $pageService)
{
// $this->shoppingCart = app(ShoppingCart::class); //Don't do this. The shopping cart service restores itself using session. But the session is not yet initialized in constructors.
parent::__construct();
}
/**
* @return View
* @throws \Illuminate\Contracts\Container\BindingResolutionException
*/
public function index() : View
{
return view('templates.cart', [
'links' => $this->links,
]);
}
/**
* Add a product to the cart
*
* @param AddProductableRequest $request
*
* @return JsonResponse
*/
public function addProductToShoppingCart(AddProductableRequest $request) : JsonResponse
{
/** @var ShoppingCartInterface $shoppingCart */
$shoppingCart = app(ShoppingCartInterface::class);
$productableEnum = $request->get('productableEnum');
$productableId = $request->get('productableId');
$quantity = $request->get('quantity');
$productable = ProductableEnum::getClassFromEnumValue($productableEnum)::where('id', $productableId)->with('translation', 'translations')->first();
$shoppingCart->addProductable($productable, $quantity);
return response()->json(null, 202);
}
/**
* Add a product to the cart
*
* @param RemoveProductRequest $request
* @return JsonResponse
*/
public function removeItemFromShoppingCart(RemoveProductRequest $request) : JsonResponse
{
$shoppingCart = app(ShoppingCartInterface::class);
$id = $request->get('itemId');
if($id === null) abort(400, 'No id specified');
if($id !== null) {
/** @var ShoppingCartInterface $shoppingCart */
$shoppingCart->deleteItem($id);
}
return response()->json(null, 202);
}
/**
* Add a product to the cart
*
* @param UpdateProductableQuantityRequest $request
* @return JsonResponse
*/
public function setItemQuantityInShoppingcart(UpdateProductableQuantityRequest $request) : JsonResponse
{
$shoppingCart = app(ShoppingCartInterface::class);
if($request->has('itemId')) {
/** @var ShoppingCartInterface $shoppingCart */
$shoppingCart->setItemQuantity($request->get('itemId'), $request->get('quantity'));
}
return response()->json(null, 202);
}
}