<?php
namespace App\EventSubscriber;
use App\Entity\Import;
use App\Entity\Upload;
use App\Service\EsSocket;
use App\Service\EsUpload;
use App\Handler\UserHandler;
use App\Service\EsSpreadsheet;
use App\Event\ImportPreUpdateEvent;
use App\Event\ImportPrePersistEvent;
use App\Event\ImportPostPersistEvent;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
class ImportSubscriber implements EventSubscriberInterface
{
public function __construct(
private UserHandler $handler,
private EntityManagerInterface $_em,
private EsUpload $esUpload,
private EsSpreadsheet $esSpreadsheet,
private EsSocket $esSocket,
private $localStorageFullPath
) {}
public static function getSubscribedEvents(): array
{
return [
ImportPrePersistEvent::NAME => 'onPreCreate',
ImportPostPersistEvent::NAME => 'onPostCreate',
//ImportPreUpdateEvent::NAME => 'onPreUpdate',
];
}
public function onPreCreate(ImportPrePersistEvent $event)
{
$object = $event->getObject();
$filename = $object->getFileName();
if (empty($filename)) {
throw new BadRequestHttpException('validation.user.import:filenameNotFound');
}
$file = $this->esUpload->resolvePath($filename, Upload::FILETYPE_IMPORT_FILE);
$file = $this->esSpreadsheet->convertToCsv($file);
$content = file_get_contents($file);
if (file_exists($file)) {
unlink($file);
}
if (empty($content)) {
throw new BadRequestHttpException('validation.user.import:emptyFileContent');
}
$object->setPayload($content);
}
public function onPostCreate(ImportPostPersistEvent $event)
{
$object = $event->getObject();
$this->handler->import($object);
}
public function onPreUpdate(ImportPreUpdateEvent $event)
{
$object = $event->getObject();
$originalEvent = $event->getEvent();
$changeSet = $originalEvent->getEntityChangeSet();
if (isset($changeSet['status'])) {
if ($changeSet['status'][0] !== $changeSet['status'][1]) {
$this->esSocket->emit(
'backend-command',
[
'type' => 'import_user_status',
'payload' => [
'containerId' => $object->getContainer->getId(),
'importId' => $object->getId(),
'status' => $changeSet['status'][1]
]
]
);
}
}
}
}