<?php
namespace Okeonline\KejeDeliveryAddress\Core\Checkout\Customer\Aggregate\CustomerAddress\Subscriber;
use Shopware\Core\Checkout\Customer\Aggregate\CustomerAddress\CustomerAddressEntity;
use Shopware\Core\Checkout\Customer\CustomerEvents;
use Shopware\Core\Framework\Api\Context\SalesChannelApiSource;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\EntityWriteResult;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CustomerAddressWrittenSubscriber implements EventSubscriberInterface {
private $customerAddressRepository;
private $customerRepository;
public function __construct(
EntityRepository $customerAddressRepository,
EntityRepository $customerRepository
)
{
$this->customerAddressRepository = $customerAddressRepository;
$this->customerRepository = $customerRepository;
}
public static function getSubscribedEvents(): array
{
return [
CustomerEvents::CUSTOMER_ADDRESS_WRITTEN_EVENT => 'setCustomerAddressSource',
];
}
public function setCustomerAddressSource(EntityWrittenEvent $event): void
{
foreach($event->getWriteResults() as $entityWriteResult)
{
if($entityWriteResult->getOperation() === EntityWriteResult::OPERATION_INSERT)
{
// newley created address (api/storefront/backoffice)
// determine where the source is:
switch (get_class($event->getContext()->getSource()))
{
case SalesChannelApiSource::class;
$source = 'storefront';
break;
default:
$source = 'default';
break;
}
$customerAddressId = $entityWriteResult->getPrimaryKey();
/** @var CustomerAddressEntity $currentCustomerAddress */
$criteria = new Criteria([$customerAddressId]);
$currentCustomerAddress = $this->customerAddressRepository->search($criteria, $event->getContext())->first();
// If there is not an extensuon with customerAddressSource, we should create it, and set correct source
if (!$currentCustomerAddress->hasExtension('customerAddressSource')) {
// add extension and set value
$this->customerAddressRepository->update([
[
'id' => $customerAddressId,
'customerAddressSource' => ['source' => $source]
]
], $event->getContext());
}
// // Then, if it is storefront, set it als new default ShippingAddress.
// // This setting wil be undone when:
// // Order is created
// // User is logout/logged in
// if($source === 'storefront' && $currentCustomerAddress->getCustomerId())
// {
// // set new addres as default shipping address
// $this->customerRepository->update([
// [
// 'id' => $currentCustomerAddress->getCustomerId(),
// 'defaultShippingAddressId' => $customerAddressId
// ]
// ], $event->getContext());
//
// }
}
}
}
}