<?php declare(strict_types=1);
namespace EsmComputer\Storefront\Subscriber;
use Shopware\Core\Checkout\Customer\CustomerEvents;
use Shopware\Core\Framework\Event\DataMappingEvent;
use Shopware\Core\Framework\Validation\DataValidationDefinition;
use Shopware\Core\Framework\Validation\DataValidator;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Type;
class AddressSubscriber implements EventSubscriberInterface
{
/**
* @var DataValidator
*/
private $dataValidator;
public function __construct(
DataValidator $dataValidator
) {
$this->dataValidator = $dataValidator;
}
public static function getSubscribedEvents()
{
return [
CustomerEvents::MAPPING_REGISTER_ADDRESS_BILLING => 'onDataMappingEvent',
CustomerEvents::MAPPING_REGISTER_ADDRESS_SHIPPING => 'onDataMappingEvent',
CustomerEvents::MAPPING_ADDRESS_CREATE => 'onDataMappingEvent'
];
}
/**
* @param DataMappingEvent $event
*/
public function onDataMappingEvent(DataMappingEvent $event): void
{
$this->setAddressOutput($event);
}
/**
* @param DataMappingEvent $event
*/
private function setAddressOutput(DataMappingEvent $event): void
{
// Ignore this subscriber on PayPal express checkout
if($event->getContext()->getExtension('payPalExpressCheckoutActive')) {
return;
}
$output = $event->getOutput();
$houseNumber = $event->getInput()->get('houseNumber');
$definition = new DataValidationDefinition();
$definition->add('houseNumber', new NotBlank(), new Type('string'));
$this->dataValidator->validate($event->getInput()->all(), $definition);
if (!$houseNumber) {
return;
}
$output['street'] = trim($output['street'])." ".trim($houseNumber);
if (!array_key_exists('customFields', $output)) {
$output['customFields'] = [
'custom_address_separate_street' => trim($event->getInput()->get('street')),
'custom_address_separate_house_number' => trim($event->getInput()->get('houseNumber'))
];
} else {
$output['customFields']['custom_address_separate_street'] = trim($event->getInput()->get('street'));
$output['customFields']['custom_address_separate_house_number'] = trim($event->getInput()->get('houseNumber'));
}
$event->setOutput($output);
}
}