<?php
namespace EnetCredit\Subscriber;
use EnetCredit\Service\UserCreditPayment;
use EnetCredit\Validator\UserCredit;
use Shopware\Core\Framework\Validation\BuildValidationEvent;
use Shopware\Core\Framework\Validation\DataValidationDefinition;
use Shopware\Core\Framework\Validation\Exception\ConstraintViolationException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ValidationSubscriber implements EventSubscriberInterface
{
/** @var \Shopware\Core\Framework\Validation\DataValidator $validator */
private $validator;
/** @var \Symfony\Component\HttpFoundation\RequestStack $requestStack */
private $requestStack;
/** @var \Shopware\Core\Checkout\Cart\SalesChannel\CartService $cartService */
private $cartService;
public function __construct($validator, $requestStack, $cartService)
{
$this->validator = $validator;
$this->requestStack = $requestStack;
$this->cartService = $cartService;
}
public static function getSubscribedEvents()
{
return [
'framework.validation.order.create' => 'userCreditValidation'
];
}
public function userCreditValidation(BuildValidationEvent $event)
{
$data = $this->requestStack->getCurrentRequest()->request;
/** @var \Shopware\Core\System\SalesChannel\SalesChannelContext $salesChannelContext */
$salesChannelContext = $this->requestStack->getCurrentRequest()->get('sw-sales-channel-context');
$customer = $salesChannelContext->getCustomer();
$paymentMethod = $salesChannelContext->getPaymentMethod();
if($paymentMethod->getHandlerIdentifier() === UserCreditPayment::class) {
$customerCustomFields = $customer->getCustomFields();
$definition = new DataValidationDefinition('order.enet_user_credit');
$definition->add('enet_user_credit', new UserCredit());
if(isset($customerCustomFields['enet_credit_value']) && $customerCustomFields['enet_credit_value']) {
$userCreditValue = floatval($customerCustomFields['enet_credit_value']);
$cart = $this->cartService->getCart($salesChannelContext->getToken(), $salesChannelContext);
$cartTotalPrice = $cart->getPrice()->getTotalPrice();
if($userCreditValue < $cartTotalPrice) {
UserCredit::$errors[] = 'to-low-user-credit';
}
}
else {
UserCredit::$errors[] = 'no-user-credit';
}
$violations = $this->validator->getViolations($data->all(), $definition);
if (!$violations->count()) {
return;
}
throw new ConstraintViolationException($violations, $data->all());
}
}
}