<?php declare(strict_types=1);
namespace Shopware\B2B\EasyMode\BridgePlatform;
use Shopware\B2B\Acl\Framework\AclRepository;
use Shopware\B2B\Common\IdValue;
use Shopware\B2B\Common\Repository\NotFoundException;
use Shopware\B2B\Debtor\Framework\DebtorService;
use Shopware\B2B\Role\Framework\RoleRepository;
use Shopware\B2B\Shop\BridgePlatform\B2bCustomerDataDefinition;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use function array_key_exists;
class B2bCustomerDataSubscriber implements EventSubscriberInterface
{
private RoleRepository $roleRepository;
private EasyModeService $easyModeService;
private AclRepository $aclRoleRepository;
private DebtorService $debtorService;
public function __construct(
RoleRepository $roleRepository,
EasyModeService $easyModeService,
AclRepository $aclRoleRepository,
DebtorService $debtorService
) {
$this->roleRepository = $roleRepository;
$this->easyModeService = $easyModeService;
$this->aclRoleRepository = $aclRoleRepository;
$this->debtorService = $debtorService;
}
public static function getSubscribedEvents(): array
{
return [
B2bCustomerDataDefinition::ENTITY_NAME . '.written' => 'updateEasyModeAcl',
];
}
public function updateEasyModeAcl(EntityWrittenEvent $event): void
{
$writtenResults = $event->getPayloads();
$identities = [];
foreach ($writtenResults as $customerData) {
$customerId = IdValue::create($customerData['customerId']);
$isInEasyMode = array_key_exists('isInEasyMode', $customerData) && $customerData['isInEasyMode'] === true;
if ($isInEasyMode === false) {
continue;
}
try {
$identity = $this->debtorService->loadIdentityByAuthentication($customerId);
} catch (NotFoundException $exception) {
continue;
}
$identities[] = $identity;
}
if (!$identities) {
return;
}
foreach ($identities as $identity) {
$easyModeRole = $this->easyModeService->getEasyModeRole($identity->getOwnershipContext(), $this->roleRepository);
$this->aclRoleRepository->allow($easyModeRole, $easyModeRole->id);
}
}
}