Files
esun3d/app/code/Esun/CustomerCoupon/Observer/GrantRegistrationSubscriptionCoupon.php
2026-09-15 10:35:56 +08:00

54 lines
1.8 KiB
PHP

<?php
declare(strict_types=1);
namespace Esun\CustomerCoupon\Observer;
use Esun\CustomerCoupon\Model\RegistrationSubscriptionCouponService;
use Esun\CustomerCoupon\Model\RegistrationCouponGrantContext;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Psr\Log\LoggerInterface;
class GrantRegistrationSubscriptionCoupon implements ObserverInterface
{
public function __construct(
private readonly RegistrationSubscriptionCouponService $couponService,
private readonly RegistrationCouponGrantContext $grantContext,
private readonly LoggerInterface $logger
) {
}
public function execute(Observer $observer): void
{
$controller = $observer->getEvent()->getAccountController();
$subscriptionRequested = $controller?->getRequest()->getParam('is_subscribed', false);
if (!in_array(strtolower((string)$subscriptionRequested), ['1', 'true', 'yes', 'on'], true)) {
return;
}
$customer = $observer->getEvent()->getCustomer();
$customerId = (int)($customer?->getId() ?? 0);
if ($customerId <= 0) {
return;
}
try {
$granted = $this->couponService->grant(
$customerId,
(int)$customer->getWebsiteId(),
(int)$customer->getGroupId(),
(int)$customer->getStoreId()
);
if ($granted) {
$this->grantContext->markGranted($customerId);
}
} catch (\Throwable $exception) {
// Coupon delivery must never roll back an otherwise successful customer registration.
$this->logger->error('Unable to grant registration subscription coupon.', [
'customer_id' => $customerId,
'exception' => $exception,
]);
}
}
}