<?php
namespace CioSubaccounts\Subscriber;
use CioBudget\Event\CustomerStoresLoadedEvent;
use Shopware\Core\Checkout\Customer\CustomerEntity;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class SubaccountsStoresInheritance implements EventSubscriberInterface
{
private ContainerInterface $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public static function getSubscribedEvents(): array
{
return [
CustomerStoresLoadedEvent::class => 'onCustomerStoreIdsLoadedEvent'
];
}
public function onCustomerStoreIdsLoadedEvent(CustomerStoresLoadedEvent $event)
{
$customer = $event->getCustomer();
$parentCustomer = $customer->getExtension('customerParent');
// ignore customers without parent
if (is_null($parentCustomer)) {
return;
}
/** @var EntityRepositoryInterface $customerRepository */
$customerRepository = $this->container->get('customer.repository');
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('id', $parentCustomer->getParent()));
$parentCustomer = $customerRepository->search($criteria, Context::createDefaultContext())->first();
// customer has a parent for inheritance
if ($parentCustomer instanceof CustomerEntity) {
$storeLoaderService = $this->container->get('customer.store_loader_service');
$event->setStores(
array_merge(
$event->getStores(), // stores from user
$storeLoaderService->getCustomerStores($parentCustomer) // stores from parent
)
);
}
}
}