<?php declare(strict_types=1);
namespace Proc\ProcWegReg\Subscriber;
use Proc\ProcWegReg\Migration\Migration1718877324CustomFieldApproval;
use Shopware\Core\Checkout\Customer\Event\CustomerGroupRegistrationAccepted;
use Shopware\Core\Checkout\Customer\Event\CustomerGroupRegistrationDeclined;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\System\User\UserEntity;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
class CustomerGroupApprovalSubscriber implements EventSubscriberInterface
{
public function __construct(
private readonly EntityRepository $customerRepository,
private readonly EntityRepository $userRepository,
private readonly RequestStack $requestStack
) {
}
public static function getSubscribedEvents(): array
{
return [
CustomerGroupRegistrationAccepted::class => ["onRegistrationAccepted", 1000],
CustomerGroupRegistrationDeclined::class => ["onRegistrationDeclined", 1000]
];
}
public function onRegistrationAccepted(CustomerGroupRegistrationAccepted $event): void
{
$this->updateCustomerField($event->getCustomer()->getId(), true, $event->getContext());
}
public function onRegistrationDeclined(CustomerGroupRegistrationDeclined $event): void
{
$this->updateCustomerField($event->getCustomer()->getId(), false, $event->getContext());
}
private function updateCustomerField(string $id, bool $accepted, Context $context): void
{
$user_id = $this->requestStack->getCurrentRequest()?->get("oauth_user_id", "");
$status = $accepted ? "Accepted" : "Declined";
if ($username = $this->getUsername($user_id, $context)) {
$this->customerRepository->upsert([
[
"id" => $id,
"customFields" => [Migration1718877324CustomFieldApproval::CUSTOM_FIELD_NAME => "$username - $status"]
]
], $context);
}
}
private function getUsername(string $id, Context $context): string|null
{
/** @var UserEntity $user */
$user = $this->userRepository->search(new Criteria([$id]), $context)->first();
return $user?->getUsername();
}
}