Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Cart] implement add-to-cart as Symfony Form #812

Merged
merged 6 commits into from
Feb 23, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion CHANGELOG-2.1.x.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,9 @@
- deprecated [CoreShop\Bundle\StoreBundle\Theme\ThemeHelper](https://github.com/coreshop/CoreShop/blob/master/src/CoreShop/Bundle/StoreBundle/Theme/ThemeHelper.php) in favor of [CoreShop\Bundle\ThemeBundle\Service\ThemeHelper](https://github.com/coreshop/CoreShop/blob/master/src/CoreShop/Bundle/ThemeBundle/Service/ThemeHelper.php)
- deprecated [CoreShop\Bundle\StoreBundle\Theme\ThemeHelperInterface](https://github.com/coreshop/CoreShop/blob/master/src/CoreShop/Bundle/StoreBundle/Theme/ThemeHelperInterface.php) in favor of [CoreShop\Bundle\ThemeBundle\Service\ThemeHelperInterface](https://github.com/coreshop/CoreShop/blob/master/src/CoreShop/Bundle/ThemeBundle/Service/ThemeHelperInterface.php)
- deprecated [CoreShop\Bundle\StoreBundle\Theme\ThemeResolver](https://github.com/coreshop/CoreShop/blob/master/src/CoreShop/Bundle/StoreBundle/Theme/ThemeResolver.php) in favor of [CoreShop\Bundle\ThemeBundle\Service\ThemeResolver](https://github.com/coreshop/CoreShop/blob/master/src/CoreShop/Bundle/ThemeBundle/Service/ThemeResolver.php)
- deprecated [CoreShop\Bundle\StoreBundle\Theme\ThemeResolverInterface](https://github.com/coreshop/CoreShop/blob/master/src/CoreShop/Bundle/StoreBundle/Theme/ThemeResolverInterface.php) in favor of [CoreShop\Bundle\ThemeBundle\Service\ThemeResolverInterface](https://github.com/coreshop/CoreShop/blob/master/src/CoreShop/Bundle/ThemeBundle/Service/ThemeResolverInterface.php)
- deprecated [CoreShop\Bundle\StoreBundle\Theme\ThemeResolverInterface](https://github.com/coreshop/CoreShop/blob/master/src/CoreShop/Bundle/StoreBundle/Theme/ThemeResolverInterface.php) in favor of [CoreShop\Bundle\ThemeBundle\Service\ThemeResolverInterface](https://github.com/coreshop/CoreShop/blob/master/src/CoreShop/Bundle/ThemeBundle/Service/ThemeResolverInterface.php)

- Introduce AddToCartFormType. This allows to use validators to check if its allowed to add a product to the cart. If you update from CoreShop 2.0.* change the add-to-cart form in your templates to the following: (https://github.com/coreshop/CoreShop/pull/812/files#diff-3e06a5f0e813be230a0cd232e916738eL29)
```
{{ render(url('coreshop_cart_add', {'product': product.id})) }}
```
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ core_shop_product_quantity_price_rules:
model: CoreShop\Component\Core\Model\QuantityRange
action_constraints:
-
class: 'CoreShop\Bundle\CoreBundle\Validation\Constraints\QuantityRangePriceCurrencyAware'
class: 'CoreShop\Bundle\CoreBundle\Validator\Constraints\QuantityRangePriceCurrencyAware'
groups:
- 'coreshop_product_quantity_price_rules_range_validation_behaviour_fixed'
- 'coreshop_product_quantity_price_rules_range_validation_behaviour_amount_decrease'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ imports:
- { resource: "services/grid_config.yml" }
- { resource: "services/routing.yml" }
- { resource: "services/product-quantity-price-rules.yml" }
- { resource: "services/validators.yml" }

services:
_defaults:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
services:
coreshop.validator.add_to_cart_availability:
class: CoreShop\Bundle\CoreBundle\Validator\Constraints\AddToCartAvailabilityValidator
arguments:
- '@coreshop.inventory.availability_checker'
tags:
- { name: validator.constraint_validator, alias: 'coreshop_add_to_cart_availability' }
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
CoreShop\Bundle\OrderBundle\DTO\AddToCart:
constraints:
- \CoreShop\Bundle\CoreBundle\Validator\Constraints\AddToCartAvailability: { message: 'coreshop.cart_item.not_sufficient_stock', groups: ['coreshop'] }
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php
/**
* CoreShop.
*
* This source file is subject to the GNU General Public License version 3 (GPLv3)
* For the full copyright and license information, please view the LICENSE.md and gpl-3.0.txt
* files that are distributed with this source code.
*
* @copyright Copyright (c) 2015-2019 Dominik Pfaffenbauer (https://www.pfaffenbauer.at)
* @license https://www.coreshop.org/license GNU General Public License version 3 (GPLv3)
*/

namespace CoreShop\Bundle\CoreBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

final class AddToCartAvailability extends Constraint
{
/**
* @var string
*/
public $message;

/**
* {@inheritdoc}
*/
public function validatedBy(): string
{
return 'coreshop_add_to_cart_availability';
}

/**
* {@inheritdoc}
*/
public function getTargets(): string
{
return self::CLASS_CONSTRAINT;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?php
/**
* CoreShop.
*
* This source file is subject to the GNU General Public License version 3 (GPLv3)
* For the full copyright and license information, please view the LICENSE.md and gpl-3.0.txt
* files that are distributed with this source code.
*
* @copyright Copyright (c) 2015-2019 Dominik Pfaffenbauer (https://www.pfaffenbauer.at)
* @license https://www.coreshop.org/license GNU General Public License version 3 (GPLv3)
*/

namespace CoreShop\Bundle\CoreBundle\Validator\Constraints;

use CoreShop\Bundle\OrderBundle\DTO\AddToCartInterface;
use CoreShop\Component\Core\Model\CartItemInterface;
use CoreShop\Component\Inventory\Checker\AvailabilityCheckerInterface;
use CoreShop\Component\Inventory\Model\StockableInterface;
use CoreShop\Component\Order\Model\CartInterface;
use CoreShop\Component\Order\Model\PurchasableInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Webmozart\Assert\Assert;

final class AddToCartAvailabilityValidator extends ConstraintValidator
{
/**
* @var AvailabilityCheckerInterface
*/
private $availabilityChecker;

/**
* @param AvailabilityCheckerInterface $availabilityChecker
*/
public function __construct(AvailabilityCheckerInterface $availabilityChecker)
{
$this->availabilityChecker = $availabilityChecker;
}

/**
* @param AddToCartInterface $addCartItemCommand
*
* {@inheritdoc}
*/
public function validate($addCartItemCommand, Constraint $constraint): void
{
Assert::isInstanceOf($addCartItemCommand, AddToCartInterface::class);
Assert::isInstanceOf($constraint, AddToCartAvailability::class);

/**
* @var StockableInterface $purchasable
*/
$purchasable = $addCartItemCommand->getPurchasable();

$isStockSufficient = $this->availabilityChecker->isStockSufficient(
$purchasable,
$addCartItemCommand->getQuantity() + $this->getExistingCartItemQuantityFromCart($addCartItemCommand->getCart(), $purchasable)
);

if (!$isStockSufficient) {
$this->context->addViolation(
$constraint->message,
['%stockable%' => $purchasable->getInventoryName()]
);
}
}

/**
* @param CartInterface $cart
* @param PurchasableInterface $purchasable
* @return int
*/
private function getExistingCartItemQuantityFromCart(CartInterface $cart, PurchasableInterface $purchasable)
{
$cartItem = $cart->getItemForProduct($purchasable);

if ($cartItem instanceof CartItemInterface) {
return $cartItem->getQuantity();
}

return 0;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
* @license https://www.coreshop.org/license GNU General Public License version 3 (GPLv3)
*/

namespace CoreShop\Bundle\CoreBundle\Validation\Constraints;
namespace CoreShop\Bundle\CoreBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
* @license https://www.coreshop.org/license GNU General Public License version 3 (GPLv3)
*/

namespace CoreShop\Bundle\CoreBundle\Validation\Constraints;
namespace CoreShop\Bundle\CoreBundle\Validator\Constraints;

use CoreShop\Component\Core\Model\CurrencyInterface;
use CoreShop\Component\Core\Model\QuantityRangeInterface;
Expand Down
104 changes: 82 additions & 22 deletions src/CoreShop/Bundle/FrontendBundle/Controller/CartController.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,26 @@

namespace CoreShop\Bundle\FrontendBundle\Controller;

use CoreShop\Bundle\OrderBundle\DTO\AddToCartInterface;
use CoreShop\Bundle\OrderBundle\Form\Type\AddToCartType;
use CoreShop\Bundle\OrderBundle\Form\Type\CartType;
use CoreShop\Bundle\OrderBundle\Form\Type\ShippingCalculatorType;
use CoreShop\Component\Address\Model\AddressInterface;
use CoreShop\Component\Inventory\Model\StockableInterface;
use CoreShop\Component\Order\Cart\Rule\CartPriceRuleProcessorInterface;
use CoreShop\Component\Order\Cart\Rule\CartPriceRuleUnProcessorInterface;
use CoreShop\Component\Order\Context\CartContextInterface;
use CoreShop\Component\Order\Manager\CartManagerInterface;
use CoreShop\Component\Order\Model\CartInterface;
use CoreShop\Component\Order\Model\CartItemInterface;
use CoreShop\Component\Order\Model\CartPriceRuleVoucherCodeInterface;
use CoreShop\Component\Order\Model\PurchasableInterface;
use CoreShop\Component\Order\Repository\CartPriceRuleVoucherRepositoryInterface;
use CoreShop\Component\StorageList\StorageListModifierInterface;
use Symfony\Component\EventDispatcher\GenericEvent;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\ConstraintViolationListInterface;

class CartController extends FrontendController
{
Expand Down Expand Up @@ -148,51 +153,82 @@ public function shipmentCalculationAction(Request $request)
/**
* @param Request $request
*
* @return \Symfony\Component\HttpFoundation\RedirectResponse
* @return \Symfony\Component\HttpFoundation\Response
*/
public function addItemAction(Request $request)
{
$product = $this->get('coreshop.repository.stack.purchasable')->find($request->get('product'));

if (!$product instanceof PurchasableInterface) {
if ($request->isXmlHttpRequest()) {
return new JsonResponse([
'success' => false,
]);
}

$redirect = $request->get('_redirect', $this->generateCoreShopUrl(null, 'coreshop_index'));

return $this->redirect($redirect);
}

$quantity = (int) $request->get('quantity', 1);
$addToCart = $this->createAddToCart($this->getCart(), $product, (int) $request->get('quantity', 1));

if (!is_int($quantity)) {
$quantity = 1;
}
$form = $this->createForm(AddToCartType::class, $addToCart);

$redirect = $request->get('_redirect', $this->generateCoreShopUrl($this->getCart(), 'coreshop_cart_summary'));
if ($request->isMethod('POST')) {
$redirect = $request->get('_redirect', $this->generateCoreShopUrl($this->getCart(), 'coreshop_cart_summary'));

if ($product instanceof StockableInterface) {
$item = $this->getCart()->getItemForProduct($product);
$quantityToCheckStock = $quantity;
if ($form->handleRequest($request)->isValid()) {
/**
* @var AddToCartInterface $addToCart
*/
$addToCart = $form->getData();

if ($item instanceof CartItemInterface) {
$quantityToCheckStock += $item->getQuantity();
}
$this->getCartModifier()->addItem($addToCart->getCart(), $addToCart->getPurchasable(), $addToCart->getQuantity());
$this->getCartManager()->persistCart($this->getCart());

$hasStock = $this->get('coreshop.inventory.availability_checker.default')->isStockSufficient($product, $quantityToCheckStock);
$this->get('coreshop.tracking.manager')->trackCartAdd($addToCart->getCart(), $addToCart->getPurchasable(), $addToCart->getQuantity());

if (!$hasStock) {
$this->addFlash('error', $this->get('translator')->trans('coreshop.cart_item.not_sufficient_stock', ['%stockable%' => $product->getName()], 'validators'));
$this->addFlash('success', $this->get('translator')->trans('coreshop.ui.item_added'));

if ($request->isXmlHttpRequest()) {
return new JsonResponse([
'success' => true
]);
}

return $this->redirect($redirect);
}
}

$this->getCartModifier()->addItem($this->getCart(), $product, $quantity);
$this->getCartManager()->persistCart($this->getCart());
foreach ($form->getErrors(true, true) as $error) {
$this->addFlash('error', $error->getMessage());
}

$this->get('coreshop.tracking.manager')->trackCartAdd($this->getCart(), $product, $quantity);
if ($request->isXmlHttpRequest()) {
return new JsonResponse([
'success' => false,
'errors' => array_map(function(FormError $error) {
return $error->getMessage();
}, iterator_to_array($form->getErrors(true)))
]);
}

$this->addFlash('success', $this->get('translator')->trans('coreshop.ui.item_added'));
return $this->redirect($redirect);
}

return $this->redirect($redirect);
if ($request->isXmlHttpRequest()) {
return new JsonResponse([
'success' => false,
]);
}

return $this->renderTemplate(
$request->get('template', $this->templateConfigurator->findTemplate('Product/_addToCart.html')),
[
'form' => $form->createView(),
'product' => $product
]
);
}

/**
Expand Down Expand Up @@ -259,6 +295,17 @@ public function createQuoteAction(Request $request)
return $this->redirectToRoute('coreshop_quote_detail', ['quote' => $quote->getId()]);
}

/**
* @param CartInterface $cart
* @param PurchasableInterface $purchasable
* @param int $quantity
* @return AddToCartInterface
*/
protected function createAddToCart(CartInterface $cart, PurchasableInterface $purchasable, int $quantity)
{
return $this->get('coreshop.factory.add_to_cart')->createWithCartAndPurchasableAndQuantity($cart, $purchasable, $quantity);
}

/**
* @return \CoreShop\Component\Resource\Factory\PimcoreFactory
*/
Expand Down Expand Up @@ -327,4 +374,17 @@ protected function getCartManager()
{
return $this->get('coreshop.cart.manager');
}

/**
* @param CartItemInterface $cartItem
*
* @return ConstraintViolationListInterface
*/
private function getCartItemErrors(CartItemInterface $cartItem)
{
return $this
->get('validator')
->validate($cartItem, null, $this->getParameter('coreshop.form.type.cart_item.validation_groups'))
;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,9 @@
<i class="fa fa-heart"></i>
</a>
{% if coreshop_inventory_is_available(product) %}
<form action="{{ coreshop_path(coreshop.cart, 'coreshop_cart_add', {product: product.id}) }}" method="post">
<button type="submit" class="btn btn-cart"
rel="nofollow">
{{ 'coreshop.ui.add_to_cart'|trans }}
<i class="fa fa-shopping-cart"></i>
</button>
</form>
{% if coreshop_inventory_is_available(product) %}
{{ render(url('coreshop_cart_add', {'product': product.id})) }}
{% endif %}
{% endif %}
</div>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,8 @@
<a href="{{ coreshop_path('coreshop_wishlist_add', {product: product.id}) }}" title="" class="btn btn-wishlist">
<i class="fa fa-heart"></i>
</a>

{% if coreshop_inventory_is_available(product) %}
<form action="{{ coreshop_path(coreshop.cart, 'coreshop_cart_add', {product: product.id}) }}" method="post">
<button type="submit" class="btn btn-cart"
rel="nofollow">
{{ 'coreshop.ui.add_to_cart'|trans }}
<i class="fa fa-shopping-cart"></i>
</button>
</form>
{{ render(url('coreshop_cart_add', {'product': product.id})) }}
{% endif %}
</div>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@
{{ messages.error(error.message, false) }}
{%- endfor -%}
{%- endif -%}
{%- endblock form_errors -%}
{%- endblock form_errors -%}
Loading