<?php declare(strict_types=1);
namespace Compra\InvoiceDispatchSW6\Storefront\Subscriber;
use Compra\InvoiceDispatchSW6\Core\System\InvoiceDispatchService;
use Shopware\Core\Checkout\Customer\Event\CustomerRegisterEvent;
use Shopware\Core\Framework\Validation\BuildValidationEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Validator\Constraints\NotBlank;
class FrontendSubscriber implements EventSubscriberInterface
{
/** @var InvoiceDispatchService */
protected $invoiceDispatchService;
/** @var Request */
protected $request;
public function __construct(
InvoiceDispatchService $invoiceDispatchService,
RequestStack $requestStack
)
{
$this->invoiceDispatchService = $invoiceDispatchService;
$this->request = $requestStack->getCurrentRequest();
}
/**
* @return string[]
*/
public static function getSubscribedEvents(): array
{
return [
CustomerRegisterEvent::class => 'onCustomerRegister',
'framework.validation.customer.create' => 'onBuildValidation'
];
}
/**
* @param BuildValidationEvent $event
*/
public function onBuildValidation(BuildValidationEvent $event): void
{
if ($event->getDefinition()->getName() !== 'customer.create') {
return;
}
// add constraint notBlank on invoice mail address if 'mail' is selected
if ($this->request->get('invoice_dispatch') === InvoiceDispatchService::INVOICE_DISPATCH_MAIL) {
$event->getDefinition()->add('invoice_mail_address', new NotBlank());
}
}
/**
* @param CustomerRegisterEvent $event
*/
public function onCustomerRegister(CustomerRegisterEvent $event): void
{
$invoiceDispatchMode = $this->request->get('invoice_dispatch');
$invoiceMailAddress = $this->request->get('invoice_mail_address');
$this->invoiceDispatchService->saveInvoiceDispatch($invoiceDispatchMode, $invoiceMailAddress, $event->getCustomer(), $event->getSalesChannelContext()->getContext());
}
}