ogcore/src/EventSubscriber/JournalPullSubscriber.php

103 lines
3.1 KiB
PHP

<?php
namespace App\EventSubscriber;
use App\Entity\BootServer;
use App\Entity\DhcpServer;
use App\Entity\ImageRepository;
use App\Service\JournalPullService;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Event\PostPersistEventArgs;
use Doctrine\ORM\Event\PostRemoveEventArgs;
use Doctrine\ORM\Event\PostUpdateEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Doctrine\ORM\Events;
#[AsDoctrineListener(event: Events::postPersist)]
#[AsDoctrineListener(event: Events::postRemove)]
#[AsDoctrineListener(event: Events::preUpdate)]
#[AsDoctrineListener(event: Events::postUpdate)]
class JournalPullSubscriber
{
/** @var array<int, array{old: string, new: string}> */
private array $pendingIpChanges = [];
public function __construct(
private readonly JournalPullService $journalPullService,
private readonly EntityManagerInterface $entityManager,
) {}
private function supports(object $entity): bool
{
return $entity instanceof BootServer
|| $entity instanceof DhcpServer
|| $entity instanceof ImageRepository;
}
public function postPersist(PostPersistEventArgs $args): void
{
$entity = $args->getObject();
if (!$this->supports($entity)) {
return;
}
$this->journalPullService->add($entity->getIp());
}
public function postRemove(PostRemoveEventArgs $args): void
{
$entity = $args->getObject();
if (!$this->supports($entity)) {
return;
}
if (!$this->isIpStillInUse($entity->getIp(), $entity)) {
$this->journalPullService->remove($entity->getIp());
}
}
private function isIpStillInUse(string $ip, object $excludedEntity): bool
{
$types = [BootServer::class, DhcpServer::class, ImageRepository::class];
foreach ($types as $class) {
$results = $this->entityManager->getRepository($class)->findBy(['ip' => $ip]);
foreach ($results as $entity) {
if ($entity !== $excludedEntity) {
return true;
}
}
}
return false;
}
public function preUpdate(PreUpdateEventArgs $args): void
{
$entity = $args->getObject();
if (!$this->supports($entity) || !$args->hasChangedField('ip')) {
return;
}
$this->pendingIpChanges[spl_object_id($entity)] = [
'old' => $args->getOldValue('ip'),
'new' => $args->getNewValue('ip'),
];
}
public function postUpdate(PostUpdateEventArgs $args): void
{
$entity = $args->getObject();
if (!$this->supports($entity)) {
return;
}
$oid = spl_object_id($entity);
if (!isset($this->pendingIpChanges[$oid])) {
return;
}
['old' => $oldIp, 'new' => $newIp] = $this->pendingIpChanges[$oid];
unset($this->pendingIpChanges[$oid]);
if (!$this->isIpStillInUse($oldIp, $entity)) {
$this->journalPullService->remove($oldIp);
}
$this->journalPullService->add($newIp);
}
}