<?php
namespace CioBudget\Subscriber;
use CioBudget\Service\BudgetLoaderService;
use CioBudget\Service\SessionService;
use CioCustomerPermissionGroups\Event\CustomerGroupsLoadedEvent;
use Shopware\Core\Checkout\Customer\Event\CustomerLoginEvent;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CustomerGroupsLoadedSubscriber implements EventSubscriberInterface
{
private SessionService $sessionService;
private EntityRepositoryInterface $customerRepository;
private BudgetLoaderService $budgetLoaderService;
public function __construct(EntityRepositoryInterface $customerRepository,
SessionService $sessionService,
BudgetLoaderService $budgetLoaderService)
{
$this->budgetLoaderService = $budgetLoaderService;
$this->sessionService = $sessionService;
$this->customerRepository = $customerRepository;
}
public static function getSubscribedEvents(): array
{
return [
CustomerGroupsLoadedEvent::class => 'onCustomerGroupsLoadedEvent'
];
}
public function onCustomerGroupsLoadedEvent(CustomerGroupsLoadedEvent $event)
{
$groups = $event->getGroups();
$currentBudgetId = $this->sessionService->getCurrentBudgetId();
if (is_array($event->getCustomer()->getCustomFields()) && key_exists('cio_stores', $event->getCustomer()->getCustomFields()) && is_array($event->getCustomer()->getCustomFields()['cio_stores'])) {
$currentBudget = null;
// find current budget in all budgets of the customer
foreach ($event->getCustomer()->getCustomFields()['cio_stores'] as $customerStore) {
if (is_array($customerStore) && key_exists('id', $customerStore)) {
$storeBudgetId = $this->budgetLoaderService->getBudgetIdByStoreId($customerStore['id']);
if ($storeBudgetId == $currentBudgetId) {
// store data with ACL becomes budget data
$currentBudget = $customerStore;
$currentBudget['id'] = $storeBudgetId;
break;
}
}
}
// iterate over all aclgroups of the current selected budget of the customer
if ($currentBudget && $currentBudget['aclgroup']) {
if (is_array($currentBudget['aclgroup'])) {
foreach ($currentBudget['aclgroup'] as $aclgroup) {
$groups[] = $aclgroup;
}
}
}
}
$event->setGroups($groups);
}
}