<?php
declare(strict_types=1);
namespace BitBag\OpenMarketplace\Component\Core\Shop\Listener;
use BitBag\OpenMarketplace\Component\Brevo\Emails;
use BitBag\OpenMarketplace\Component\Customer\Model\CustomerInterface;
use BitBag\OpenMarketplace\Component\Organization\Entity\OrganizationInterface;
use BitBag\OpenMarketplace\Component\Vendor\Entity\ShopUserInterface;
use BitBag\OpenMarketplace\Component\Vendor\Entity\VendorInterface;
use Sylius\Component\Mailer\Sender\SenderInterface;
use Symfony\Component\EventDispatcher\GenericEvent;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RouterInterface;
final class MailerListener
{
public function __construct(
private SenderInterface $emailSender,
private RouterInterface $router,
) {
}
public function sendResetPasswordTokenEmail(GenericEvent $event): void
{
$user = $event->getSubject();
if (!$user instanceof ShopUserInterface) {
return;
}
$url = $this->router->generate(
'sylius_shop_password_reset',
['token' => $user->getPasswordResetToken()],
UrlGeneratorInterface::ABSOLUTE_PATH,
);
$this->emailSender->send(
Emails::PASSWORD_RESET,
[$user->getEmail()],
[
'user' => $user,
'url' => $url,
],
);
}
public function sendVerificationTokenEmail(GenericEvent $event): void
{
$user = $event->getSubject();
if (!$user instanceof ShopUserInterface) {
return;
}
$url = $this->router->generate(
'sylius_shop_user_verification',
['token' => $user->getEmailVerificationToken()],
UrlGeneratorInterface::ABSOLUTE_PATH,
);
$this->emailSender->send(
$this->resolveEmailCode($user),
[$user->getEmail()],
[
'user' => $user,
'url' => $url,
],
);
}
public function sendAccountUnderVerificationEmail(GenericEvent $event): void
{
$user = $event->getSubject();
if (!$user instanceof ShopUserInterface) {
return;
}
if (false === $this->isVendorAccount($user)) {
return;
}
$this->emailSender->send(
Emails::ACCOUNT_UNDER_VERIFICATION,
[$user->getEmail()],
);
}
private function resolveEmailCode(ShopUserInterface $user): string
{
return true === $this->isVendorAccount($user) ?
Emails::SELLER_REGISTRATION :
Emails::BUYER_REGISTRATION;
}
private function isVendorAccount(ShopUserInterface $user): bool
{
$organization = $this->getOrganization($user);
if (!$organization instanceof OrganizationInterface) {
return false;
}
return $organization->getVendor() instanceof VendorInterface;
}
private function getOrganization(ShopUserInterface $user): ?OrganizationInterface
{
$customer = $user->getCustomer();
if (!$customer instanceof CustomerInterface) {
return null;
}
$organization = $customer->getOrganization();
if (!$organization instanceof OrganizationInterface) {
return null;
}
return $organization;
}
}