<?php
namespace EnetMinOrderValue\Subscriber;
use EnetMinOrderValue\Validator\MinOrderValue;
use Shopware\Core\Checkout\Cart\SalesChannel\CartService;
use Shopware\Core\Framework\Validation\BuildValidationEvent;
use Shopware\Core\Framework\Validation\DataValidationDefinition;
use Shopware\Core\Framework\Validation\DataValidator;
use Shopware\Core\Framework\Validation\Exception\ConstraintViolationException;
use Shopware\Core\Framework\Context;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
class ValidationSubscriber implements EventSubscriberInterface
{
/** @var DataValidator $validator */
protected $validator;
/** @var RequestStack $requestStack */
protected $requestStack;
/** @var SystemConfigService $systemConfigService */
protected $systemConfigService;
/** @var CartService $cartService */
protected $cartService;
public function __construct(DataValidator $validator, RequestStack $requestStack, CartService $cartService, SystemConfigService $systemConfigService)
{
$this->validator = $validator;
$this->requestStack = $requestStack;
$this->cartService = $cartService;
$this->systemConfigService = $systemConfigService;
}
public static function getSubscribedEvents()
{
return [
'framework.validation.order.create' => 'cartValidation'
];
}
public function cartValidation(BuildValidationEvent $event)
{
$minOrderValue = floatval($this->systemConfigService->get('EnetMinOrderValue.config.minOrderValue'));
/** @var \Shopware\Core\System\SalesChannel\SalesChannelContext $salesChannelContext */
$salesChannelContext = $this->requestStack->getCurrentRequest()->get('sw-sales-channel-context');
// only validate if orderValue is larger then 0 (default for off)
// or if paymentMethod is not UserCreditPayment
// dump($salesChannelContext->getPaymentMethod()->getFormattedHandlerIdentifier());
// die();
if($minOrderValue > 0 && $salesChannelContext->getPaymentMethod()->getFormattedHandlerIdentifier() !== "handler_enetcredit_usercreditpayment") {
$data = $this->requestStack->getCurrentRequest()->request;
$definition = new DataValidationDefinition('order.minOrderValue');
$cart = $this->cartService->getCart($salesChannelContext->getToken(), $salesChannelContext);
$definition->add('enet_minOrderValue',
new MinOrderValue($minOrderValue, $cart->getPrice())
);
$violations = $this->validator->getViolations($data->all(), $definition);
if(!$violations->count()) {
return;
}
throw new ConstraintViolationException($violations, $data->all());
}
}
}