<?php
namespace Harmonizely\Service\EventSubscriber;
use Harmonizely\Background\Data\DirectoryDeleteCompanyEventData;
use Harmonizely\Background\Data\DirectorySaveCompanyEventData;
use Harmonizely\Core\BackgroundWork\Contract\IClient;
use Harmonizely\Core\Security\Contract\ISecurityHelper;
use Harmonizely\Model\EventTypeInterface;
use Harmonizely\Service\Event\CreateEventTypeEvent;
use Harmonizely\Service\Event\DeleteEventTypeEvent;
use Harmonizely\Service\Event\UpdateEventTypeEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class DirectorySubscriber implements EventSubscriberInterface
{
/**
* @var IClient
*/
private IClient $backgroundClient;
/**
* @var ISecurityHelper
*/
private ISecurityHelper $securityHelper;
/**
* @param IClient $backgroundClient
* @param ISecurityHelper $securityHelper
*/
public function __construct(
IClient $backgroundClient,
ISecurityHelper $securityHelper
)
{
$this->backgroundClient = $backgroundClient;
$this->securityHelper = $securityHelper;
}
/**
* @return string[]
*/
public static function getSubscribedEvents(): array
{
return [
CreateEventTypeEvent::NAME => 'createEventType',
UpdateEventTypeEvent::NAME => 'updateEventType',
DeleteEventTypeEvent::NAME => 'deleteEventType',
];
}
/**
* @param CreateEventTypeEvent $event
* @return void
*/
public function createEventType(CreateEventTypeEvent $event): void
{
$this->saveOrDeleteEventType($event->getEventType());
}
/**
* @param UpdateEventTypeEvent $event
* @return void
*/
public function updateEventType(UpdateEventTypeEvent $event): void
{
$this->saveOrDeleteEventType($event->getEventType());
}
/**
* @param DeleteEventTypeEvent $event
* @return void
*/
public function deleteEventType(DeleteEventTypeEvent $event): void
{
$user = $this->securityHelper->getUser();
$this->backgroundClient->add(new DirectoryDeleteCompanyEventData($user->getId(), $event->getEventTypeId()));
$this->backgroundClient->runJobs();
}
/**
* @param EventTypeInterface $eventType
* @return void
*/
private function saveOrDeleteEventType(EventTypeInterface $eventType): void
{
$user = $this->securityHelper->getUser();
if ($eventType->isEnabled() && !$eventType->isSecret()) {
$this->backgroundClient->add(new DirectorySaveCompanyEventData($user->getId(), $eventType->getId()));
} else {
$this->backgroundClient->add(new DirectoryDeleteCompanyEventData($user->getId(), $eventType->getId()));
}
$this->backgroundClient->runJobs();
}
}