<?php
declare(strict_types=1);
namespace WbfkExtensions\Subscriber;
use Shopware\Core\Framework\Validation\BuildValidationEvent;
use Shopware\Core\Framework\Validation\DataBag\RequestDataBag;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
use Symfony\Component\Validator\Constraints\File;
class AddTradeLicenseValidationForCustomer implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
'kernel.controller_arguments' => 'addTradeLicenseToRequestDataBag',
'framework.validation.customer.create' => 'addTradeLicenseValidation',
'framework.validation.customer.update' => 'addTradeLicenseValidation',
'framework.validation.customer.profile.update' => 'addTradeLicenseValidation',
];
}
public function addTradeLicenseToRequestDataBag(ControllerArgumentsEvent $event): void
{
// if current route is frontend.account.register.save
if (
!in_array(
$event->getRequest()->get('_route'),
[
'frontend.account.register.save',
'frontend.account.profile.save',
]
)) {
return;
}
$requestDataBag = $this->findRequestDataBag($event);
if (!$requestDataBag) {
return;
}
// Add tradeLicense to request data bag
$requestDataBag->add(['tradeLicense' => $event->getRequest()->files->get('tradeLicense')]);
}
public function addTradeLicenseValidation(BuildValidationEvent $event): void
{
$definition = $event->getDefinition();
$definition->add(
'tradeLicense',
new File([
'maxSize' => '5M',
'mimeTypes' => [
'application/pdf',
'image/png',
'image/jpg',
'image/jpeg',
],
'mimeTypesMessage' => 'Please upload a valid PDF, PNG, JPG AND JPEG',
])
);
}
private function findRequestDataBag(ControllerArgumentsEvent $event): ?RequestDataBag
{
$controllerArguments = $event->getArguments();
foreach ($controllerArguments as $controllerArgument) {
if ($controllerArgument instanceof RequestDataBag) {
return $controllerArgument;
}
}
return null;
}
}