← Back
Editing: ReportExporter.php
<?php namespace App\Report; use App\Entity\User; use App\Enum\ReportType; use App\Repository\ReportRepository; use App\Service\OrganizationService; use App\Service\Utils; use Doctrine\ORM\QueryBuilder; use Symfony\Component\Security\Core\Security; use Symfony\Component\Serializer\Context\Normalizer\ObjectNormalizerContextBuilder; use Symfony\Component\Serializer\SerializerInterface; use Symfony\Contracts\Translation\TranslatorInterface; class ReportExporter { public function __construct( private readonly ReportRepository $reportRepository, private readonly Security $security, private readonly SerializerInterface $serializer, private readonly Utils $utils, private readonly TranslatorInterface $translator, private readonly OrganizationService $organizationService ) { } public function __invoke(ReportType $reportType): string { $reports = $this->getQuery($reportType)->getQuery()->getResult(); $context = (new ObjectNormalizerContextBuilder()) ->withGroups('export_report') ->toArray(); $csv = $this->serializer->serialize($reports, 'csv', $context); $this->translateFields($csv); $xlsx = $this->utils->csvToSpreadsheet($csv); $fileName = 'report.xlsx'; $tmpFile = tempnam(sys_get_temp_dir(), $fileName); $xlsx->save($tmpFile); return $tmpFile; } private function getQuery(ReportType $reportType): QueryBuilder { /** @var User $user */ $user = $this->security->getUser(); $agencyIds = []; $manager = null; if (in_array('ROLE_ORGANIZATION', $user->getRoles())) { $agencyIds = $this->organizationService->getAgenciesId(); } if (in_array('ROLE_SUPERVISOR', $user->getRoles())) { $agencyIds[] = $user->getAgency()->getId(); } if (in_array('ROLE_MANAGER', $user->getRoles())) { $manager = $user; } return $this->reportRepository->getReportsQueryBuilder( manager: $manager, type: $reportType, agenciesId: $agencyIds ); } private function translateFields(string &$csv): void { $lines = explode("\n", $csv); $headers = explode(',', $lines[0]); foreach ($headers as &$header) { $header = $this->translator->trans($header); } $lines[0] = implode(',', $headers); $csv = implode("\n", $lines); } }
Save File
Cancel