<?php
namespace CioSubaccounts\Subscriber;
use CioBudget\Event\CustomerStoresLoadedEvent;
use CioMasterdata\Event\MasterdataLoadedEvent;
use CioMasterdata\Service\MasterdataService;
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 SubaccountsMasterdataInheritance implements EventSubscriberInterface
{
private ContainerInterface $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public static function getSubscribedEvents(): array
{
return [
MasterdataLoadedEvent::class => 'onMasterdataLoaded'
];
}
public function onMasterdataLoaded(MasterdataLoadedEvent $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) {
/** @var MasterdataService $masterdataService */
$masterdataService = $this->container->get('CioMasterdata\Service\MasterdataService');
$event->setMasterdataIds(
array_merge(
$event->getMasterdataIds(), // stores from user
$masterdataService->getMasterdataIdsForCustomer($parentCustomer, false) // masterdataIds from parent
)
);
}
}
}