<?php
namespace App\V4\Action\Export;
use App\Security\User;
use App\V4\Messenger\Handler\EntityExportRequestHandler;
use DateTimeImmutable;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
/**
* @Route("/api/v4/export/list", name="export_list", methods={"GET"})
*/
class EntityExportListAction extends AbstractController
{
public function __invoke(Security $security, KernelInterface $kernel): JsonResponse
{
$user = $security->getUser();
if (!$user instanceof User) {
return new JsonResponse(['message' => 'need_authenticated'], Response::HTTP_UNAUTHORIZED);
}
$finder = new Finder();
$userExportPath = sprintf(
'%s/%s/%s/',
$kernel->getProjectDir().EntityExportRequestHandler::EXPORT_PATH_COMPLETED,
$user->getCustomerId(),
$user->getUserId()
);
$fileSystem = new Filesystem();
if (!$fileSystem->exists($userExportPath)) {
return new JsonResponse(['files' => []]);
}
$finder->files()->in($userExportPath)->name('*.csv');
$files = [];
foreach ($finder as $file) {
if (!isset($files[$file->getRelativePath()])) {
$files[$file->getRelativePath()] = [];
}
$files[$file->getRelativePath()][] = [
'id' => $file->getFilenameWithoutExtension(),
'requestedAt' => (new DateTimeImmutable())->setTimestamp($file->getCTime())->format(DateTimeImmutable::ISO8601),
];
}
return new JsonResponse(['files' => $files]);
}
}