<?php
namespace App\EventSubscriber;
use App\Event\CustomerEvent;
use App\Repository\UserRepository;
use App\Security\Voters\InvoiceVoter;
use App\Service\Constants\LogEvents;
use App\Service\Invoice\Outgoing\OutgoingInvoiceService;
use App\Service\Subscription\SubscriptionService;
use App\Service\UserLog;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Security;
class CustomerSubscriber implements EventSubscriberInterface
{
protected Security $security;
protected UserRepository $userRepo;
protected SubscriptionService $subscriptionService;
private UserLog $userLog;
private OutgoingInvoiceService $outgoingInvoiceService;
public function __construct(
SubscriptionService $subscriptionService,
OutgoingInvoiceService $outgoingInvoiceService,
Security $security,
UserLog $userLog
)
{
$this->security = $security;
$this->subscriptionService = $subscriptionService;
$this->userLog = $userLog;
$this->outgoingInvoiceService = $outgoingInvoiceService;
}
public static function getSubscribedEvents(): array
{
return [
CustomerEvent::INVOICE_DEFAULTS_UPDATED => [
['logInvoiceDefaultsChange'],
['updateCustomerJsonData']
],
CustomerEvent::ADDRESS_DEFAULTS_UPDATED => [
['logAddressDefaultsChange'],
['updateCustomerJsonData']
],
CustomerEvent::CUSTOMER_BASICS_UPDATED => [
['logCustomerBasicsChange'],
['updateCustomerJsonData']
],
CustomerEvent::CUSTOMER_CREATED => [
['createSubscriptions']
],
];
}
public function updateCustomerJsonData(CustomerEvent $event)
{
$customer = $event->getCustomer();
foreach ($customer->getInvoices() as $invoice) {
if (!$this->security->isGranted(InvoiceVoter::CAN_BE_UPDATED, $invoice))
{
continue;
}
$this->outgoingInvoiceService->updateCustomerJsonData($invoice);
}
}
public function logInvoiceDefaultsChange(CustomerEvent $event)
{
$this->userLog->log('customer',LogEvents::CUSTOMER_UPDATED_INVOICE_DEFAULTS_APP,
$event->getCustomer()->getId(),
$event->getCustomer()->getName()
);
}
public function logAddressDefaultsChange(CustomerEvent $event)
{
$this->userLog->log('customer',LogEvents::CUSTOMER_UPDATED_ADDRESS_DEFAULTS_APP,
$event->getCustomer()->getId(),
$event->getCustomer()->getName()
);
}
public function logCustomerBasicsChange(CustomerEvent $event)
{
$this->userLog->log('customer',LogEvents::CUSTOMER_UPDATED_BASICS_APP,
$event->getCustomer()->getId(),
$event->getCustomer()->getName()
);
}
public function createSubscriptions(CustomerEvent $event) {
if ($customer = $event->getCustomer()) {
$this->subscriptionService->generateSubscriptions($customer);
}
}
}