<?php
namespace Customize\Controller;
use Eccube\Controller\AbstractController;
use Eccube\Entity\BaseInfo;
use Eccube\Entity\ProductClass;
use Eccube\Event\EccubeEvents;
use Eccube\Event\EventArgs;
use Eccube\Repository\BaseInfoRepository;
use Eccube\Repository\ProductClassRepository;
use Eccube\Service\CartService;
use Eccube\Service\OrderHelper;
use Eccube\Service\PurchaseFlow\PurchaseContext;
use Eccube\Service\PurchaseFlow\PurchaseFlow;
use Eccube\Service\PurchaseFlow\PurchaseFlowResult;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Customize\Common\Constants;
use Eccube\Common\EccubeConfig;
class CartController extends AbstractController
{
/**
* @var ProductClassRepository
*/
protected $productClassRepository;
/**
* @var CartService
*/
protected $cartService;
/**
* @var PurchaseFlow
*/
protected $purchaseFlow;
/**
* @var BaseInfo
*/
protected $baseInfo;
private $setting;
/**
* CartController constructor.
*
* @param ProductClassRepository $productClassRepository
* @param CartService $cartService
* @param PurchaseFlow $cartPurchaseFlow
* @param BaseInfoRepository $baseInfoRepository
*/
public function __construct(
ProductClassRepository $productClassRepository,
CartService $cartService,
PurchaseFlow $cartPurchaseFlow,
BaseInfoRepository $baseInfoRepository,
EccubeConfig $eccubeConfig,
) {
$this->productClassRepository = $productClassRepository;
$this->cartService = $cartService;
$this->purchaseFlow = $cartPurchaseFlow;
$this->baseInfo = $baseInfoRepository->get();
$this->eccubeConfig = $eccubeConfig;
}
/**
* カート画面.
*
* @Route("/cart", name="cart", methods={"GET"})
* @Template("Cart/index.twig")
*/
public function index(Request $request)
{
$result = $this->cartService->validateLocale($request, $this->cartService->getCart());
if($result['isPass'] == false){
return $this->redirectToRoute('cart_locale', [
'_locale' => $result['locale']
]);
}
// カートを取得して明細の正規化を実行
$Carts = $this->cartService->getCarts();
$this->execPurchaseFlow($Carts);
// TODO itemHolderから取得できるように
$least = [];
$quantity = [];
$isDeliveryFree = [];
$totalPrice = 0;
$totalQuantity = 0;
foreach ($Carts as $Cart) {
$quantity[$Cart->getCartKey()] = 0;
$isDeliveryFree[$Cart->getCartKey()] = false;
if ($this->baseInfo->getDeliveryFreeQuantity()) {
if ($this->baseInfo->getDeliveryFreeQuantity() > $Cart->getQuantity()) {
$quantity[$Cart->getCartKey()] = $this->baseInfo->getDeliveryFreeQuantity() - $Cart->getQuantity();
} else {
$isDeliveryFree[$Cart->getCartKey()] = true;
}
}
if ($this->baseInfo->getDeliveryFreeAmount()) {
if (!$isDeliveryFree[$Cart->getCartKey()] && $this->baseInfo->getDeliveryFreeAmount() <= $Cart->getTotalPrice()) {
$isDeliveryFree[$Cart->getCartKey()] = true;
} else {
$least[$Cart->getCartKey()] = $this->baseInfo->getDeliveryFreeAmount() - $Cart->getTotalPrice();
}
}
$totalPrice += $Cart->getTotalPrice();
$totalQuantity += $Cart->getQuantity();
}
// カートが分割された時のセッション情報を削除
$request->getSession()->remove(OrderHelper::SESSION_CART_DIVIDE_FLAG);
return [
'totalPrice' => $totalPrice,
'totalQuantity' => $totalQuantity,
// 空のカートを削除し取得し直す
'Carts' => $this->cartService->getCarts(true),
'Cart' => $this->cartService->getCart(),
'least' => $least,
'quantity' => $quantity,
'is_delivery_free' => $isDeliveryFree,
];
}
/**
* カート画面.
*
* @Route("/{_locale}/cart", name="cart_locale", methods={"GET"})
* @Template("Cart/index.twig")
*/
public function indexLocale(Request $request)
{
if($this->eccubeConfig['salon_domain'] == $_SERVER['SERVER_NAME']){
$this->redirectToRoute('homepage');
}
$result = $this->cartService->validateLocale($request, $this->cartService->getCart());
if($result['isPass'] == false){
return $this->redirectToRoute('cart_locale', [
'_locale' => $result['locale']
]);
}
if($request->getLocale() == Constants::LOCALE_JAPAN){
return $this->redirectToRoute('cart');
}
return $this->index($request);
}
/**
* カート明細の加算/減算/削除を行う.
*
* - 加算
* - 明細の個数を1増やす
* - 減算
* - 明細の個数を1減らす
* - 個数が0になる場合は、明細を削除する
* - 削除
* - 明細を削除する
*
* @Route(
* path="/cart/{operation}/{productClassId}",
* name="cart_handle_item",
* methods={"PUT"},
* requirements={
* "operation": "up|down|remove",
* "productClassId": "\d+"
* }
* )
*/
public function handleCartItem($operation, $productClassId)
{
log_info('カート明細操作開始', ['operation' => $operation, 'product_class_id' => $productClassId]);
$this->isTokenValid();
/** @var ProductClass $ProductClass */
$ProductClass = $this->productClassRepository->find($productClassId);
if (is_null($ProductClass)) {
log_info('商品が存在しないため、カート画面へredirect', ['operation' => $operation, 'product_class_id' => $productClassId]);
if (isset($_SERVER['REQUEST_URI'])) {
if (!strpos($_SERVER['REQUEST_URI'], Constants::LOCALE_JAPAN)) {
return $this->redirectToRoute('cart_locale');
};
}
return $this->redirectToRoute('cart');
}
// 明細の増減・削除
switch ($operation) {
case 'up':
$this->cartService->addProduct($ProductClass, 1);
break;
case 'down':
$this->cartService->addProduct($ProductClass, -1);
break;
case 'remove':
$this->cartService->removeProduct($ProductClass);
break;
}
// カートを取得して明細の正規化を実行
$Carts = $this->cartService->getCarts();
$this->execPurchaseFlow($Carts);
switch ($operation) {
case 'up':
break;
case 'down':
$event = new EventArgs(
[
'productClass' => $ProductClass
],
);
$this->eventDispatcher->dispatch($event, EccubeEvents::FRONT_CART_DOWN_COMPLETE);
break;
case 'remove':
break;
}
log_info('カート演算処理終了', ['operation' => $operation, 'product_class_id' => $productClassId]);
if (isset($_SERVER['REQUEST_URI'])) {
if (!strpos($_SERVER['REQUEST_URI'], Constants::LOCALE_JAPAN)) {
return $this->redirectToRoute('cart_locale');
};
}
return $this->redirectToRoute('cart');
}
/**
* カート明細の加算/減算/削除を行う.
*
* - 加算
* - 明細の個数を1増やす
* - 減算
* - 明細の個数を1減らす
* - 個数が0になる場合は、明細を削除する
* - 削除
* - 明細を削除する
*
* @Route(
* path="/{_locale}/cart/{operation}/{productClassId}",
* name="cart_handle_item_locale",
* methods={"PUT"},
* requirements={
* "operation": "up|down|remove",
* "productClassId": "\d+"
* }
* )
*/
public function handleCartItemLocale($operation, $productClassId)
{
return $this->handleCartItem($operation, $productClassId);
}
/**
* @param $Carts
*
* @return \Symfony\Component\HttpFoundation\RedirectResponse|null
*/
protected function execPurchaseFlow($Carts)
{
/** @var PurchaseFlowResult[] $flowResults */
$flowResults = array_map(function ($Cart) {
$purchaseContext = new PurchaseContext($Cart, $this->getUser());
return $this->purchaseFlow->validate($Cart, $purchaseContext);
}, $Carts);
// 復旧不可のエラーが発生した場合はカートをクリアして再描画
$hasError = false;
foreach ($flowResults as $result) {
if ($result->hasError()) {
$hasError = true;
foreach ($result->getErrors() as $error) {
$this->addRequestError($error->getMessage());
}
}
}
if ($hasError) {
$this->cartService->clear();
if (isset($_SERVER['REQUEST_URI'])) {
if (!strpos($_SERVER['REQUEST_URI'], Constants::LOCALE_JAPAN)) {
return $this->redirectToRoute('cart_locale');
};
}
return $this->redirectToRoute('cart');
}
$this->cartService->save();
foreach ($flowResults as $index => $result) {
foreach ($result->getWarning() as $warning) {
if ($Carts[$index]->getItems()->count() > 0) {
$cart_key = $Carts[$index]->getCartKey();
$this->addRequestError($warning->getMessage(), "front.cart.${cart_key}");
} else {
// キーが存在しない場合はグローバルにエラーを表示する
$this->addRequestError($warning->getMessage());
}
}
}
return null;
}
/**
* カートをロック状態に設定し、購入確認画面へ遷移する.
*
* @Route("/cart/buystep/{cart_key}", name="cart_buystep", requirements={"cart_key" = "[a-zA-Z0-9]+[_][\x20-\x7E]+"}, methods={"GET"})
*/
public function buystep(Request $request, $cart_key)
{
$Carts = $this->cartService->getCart();
if (!is_object($Carts)) {
if (!$request->get('_locale') == Constants::LOCALE_JAPAN) {
return $this->redirectToRoute('cart_locale');
}
return $this->redirectToRoute('cart');
}
// FRONT_CART_BUYSTEP_INITIALIZE
$event = new EventArgs(
[],
$request
);
$this->eventDispatcher->dispatch($event, EccubeEvents::FRONT_CART_BUYSTEP_INITIALIZE);
$this->cartService->setPrimary($cart_key);
$this->cartService->save();
// FRONT_CART_BUYSTEP_COMPLETE
$event = new EventArgs(
[],
$request
);
$this->eventDispatcher->dispatch($event, EccubeEvents::FRONT_CART_BUYSTEP_COMPLETE);
if ($event->hasResponse()) {
return $event->getResponse();
}
return $request->get('_locale') != Constants::LOCALE_JAPAN && $request->get('_locale') != null
? $this->redirectToRoute('shopping_locale')
: $this->redirectToRoute('shopping');
}
/**
* カートをロック状態に設定し、購入確認画面へ遷移する.
*
* @Route("/{_locale}/cart/buystep/{cart_key}", name="cart_buystep_locale", requirements={"cart_key" = "[a-zA-Z0-9]+[_][\x20-\x7E]+"}, methods={"GET"})
*/
public function buystepLocale(Request $request, $cart_key)
{
return $this->buystep($request, $cart_key);
}
}