<?php
namespace Tonur\Packstation\Subscriber;
use Shopware\Core\Framework\Validation\BuildValidationEvent;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Validator\Constraints\Length;
use Tonur\Packstation\Component\Validator\Constraints\PostNumber;
use Tonur\Packstation\Util\PluginConfigUtil;
class AddressValidationSubscriber implements EventSubscriberInterface
{
private PluginConfigUtil $pluginConfig;
private RequestStack $requestStack;
public function __construct(PluginConfigUtil $pluginConfig, RequestStack $requestStack)
{
$this->pluginConfig = $pluginConfig;
$this->requestStack = $requestStack;
}
public static function getSubscribedEvents()
{
return [
'framework.validation.address.update' => 'onBuildValidation',
'framework.validation.address.create' => 'onBuildValidation'
];
}
public function onBuildValidation(BuildValidationEvent $event)
{
if (!$this->isPluginActive()) {
return;
}
$this->addPostNumberBuildValidation($event);
}
private function isPluginActive(?SalesChannelContext $salesChannelContext = null)
{
return $this->pluginConfig->isPluginActive($salesChannelContext);
}
private function addPostNumberBuildValidation(BuildValidationEvent $event)
{
if (!$this->pluginConfig->validatePostNumber()) {
return;
}
$postNumberKey = 'repertusPackstationPostNumber';
$data = $event->getData();
$definition = $event->getDefinition();
if (!$data->has($postNumberKey)) {
$currentRequest = $this->requestStack->getCurrentRequest();
if ($currentRequest && $postNumberValue = $currentRequest->get($postNumberKey)) {
$data->set($postNumberKey, $postNumberValue);
}
}
if ($data->has($postNumberKey)) {
$shippingAddress = $data->get('shippingAddress');
if ($shippingAddress && !$shippingAddress->has($postNumberKey)) {
$shippingAddress->set($postNumberKey, $data->get($postNumberKey));
}
$definition->add($postNumberKey, new PostNumber('/^[\d]*$/'), new Length(null, 6, 12));
}
}
}