<?php
namespace EnetPickupDate\Subscriber;
use EnetPickupDate\Exception\NoDatePresentError;
use EnetPickupDate\Validator\OpeningTimes;
use EnetPickupDate\Validator\PickupDate;
use EnetPickupDate\Validator\PublicHoliday;
use EnetPickupDate\Validator\PublicHolidayValidator;
use Shopware\Core\Checkout\Cart\SalesChannel\CartService;
use Shopware\Core\Checkout\Payment\Exception\InvalidOrderException;
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 \Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Checkout\Cart\Error\Error;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Validator\Constraints\NotBlank;
class ValidationSubscriber implements EventSubscriberInterface
{
/** @var DataValidator $validator */
private $validator;
/** @var RequestStack $requestStack */
private $requestStack;
/** @var CartService $cartService */
private $cartService;
public function __construct(DataValidator $validator, RequestStack $requestStack, CartService $cartService)
{
$this->validator = $validator;
$this->requestStack = $requestStack;
$this->cartService = $cartService;
}
public static function getSubscribedEvents()
{
return [
'framework.validation.order.create' => 'cartValidation'
];
}
/**
* Set the PickupDate Validator
* if LineItems are less then one or if there NOT is only an UserCredit item in cart
*
* @param BuildValidationEvent $event
*/
public function cartValidation(BuildValidationEvent $event)
{
$salesChannelContext = $this->requestStack->getCurrentRequest()->get('sw-sales-channel-context');
$cart = $this->cartService->getCart($salesChannelContext->getToken(), $salesChannelContext);
$hasUserCreditProduct = false;
foreach($cart->getLineItems() as $lineItem) {
$customFields = $lineItem->getPayloadValue('customFields');
if(isset($customFields['enet_credit_product']) && $customFields['enet_credit_product'] === true) {
$hasUserCreditProduct = true;
}
}
// dump(
// count($cart->getLineItems()) > 1,
// $hasUserCreditProduct === false
// );
// die();
if(count($cart->getLineItems()) > 1 || $hasUserCreditProduct === false) {
$data = $this->requestStack->getCurrentRequest()->request;
$definition = new DataValidationDefinition('order.pickupdate');
$definition->add('enet_pickup',
new PickupDate()
);
$violations = $this->validator->getViolations($data->all(), $definition);
if (!$violations->count()) {
return;
}
throw new ConstraintViolationException($violations, $data->all());
}
}
}