← Back
Editing: AgencyController.php
<?php namespace App\Controller; use App\DTO\AgencyImport as AgencyImportDTO; use App\Entity\Agency; use App\Form\Admin\AgencyImportCommitType; use App\Form\Admin\AgencyImportPreviewType; use App\Form\AgencyType; use App\Form\Filter\UserFilterType; use App\Import\AgencyExport; use App\Import\AgencyImporter; use App\Repository\AgencyRepository; use App\Repository\ItemRepository; use App\Service\SolutionService; use Doctrine\Common\Collections\Criteria; use Doctrine\DBAL\Exception\UniqueConstraintViolationException; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\OptimisticLockException; use Doctrine\ORM\ORMException; use Dompdf\Dompdf; use Dompdf\Options; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\BinaryFileResponse; use Symfony\Component\HttpFoundation\File\Exception\FileException; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\ResponseHeaderBag; use Symfony\Component\HttpKernel\KernelInterface; use Symfony\Component\Routing\Annotation\Route; #[Route(path: '/agency')] class AgencyController extends AbstractController { /** * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception */ #[Route(path: '/export/index', name: 'agency_export_index', methods: ['GET'])] public function exportIndex(AgencyRepository $agencyRepository): Response { $agencyList = $agencyRepository->findAll(); $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $sheet->setTitle('Adresse'); $sheet->setCellValue('A1', 'Nom'); $sheet->setCellValue('B1', 'Email'); $sheet->setCellValue('C1', 'Téléphone fixe'); $sheet->setCellValue('D1', 'Date début contrat'); $sheet->setCellValue('E1', 'Date fin contrat'); $sheet->setCellValue('F1', 'Nombre licence'); $sheet->setCellValue('G1', 'Nom contact'); $sheet->setCellValue('H1', 'Prénom contact'); $sheet->setCellValue('I1', 'Mail contact'); $sheet->setCellValue('J1', 'Téléphone contact'); for ($i = 0; $i < count($agencyList); ++$i) { $sheet->setCellValue('A'.($i + 2), $agencyList[$i]->getNom()); $sheet->setCellValue('B'.($i + 2), $agencyList[$i]->getEmail()); $sheet->setCellValue('C'.($i + 2), $agencyList[$i]->getTelephoneFixe()); $sheet->setCellValue('D'.($i + 2), $agencyList[$i]->getDateDebutContrat()); $sheet->setCellValue('E'.($i + 2), $agencyList[$i]->getDateFinContrat()); $sheet->setCellValue('F'.($i + 2), $agencyList[$i]->getNombreLicence()); $sheet->setCellValue('G'.($i + 2), $agencyList[$i]->getNomContact()); $sheet->setCellValue('H'.($i + 2), $agencyList[$i]->getPrenomContact()); $sheet->setCellValue('I'.($i + 2), $agencyList[$i]->getMailContact()); $sheet->setCellValue('J'.($i + 2), $agencyList[$i]->getTelephoneContact()); } $writer = new Xlsx($spreadsheet); $fileName = 'agencys.xlsx'; $tmpFile = tempnam(sys_get_temp_dir(), $fileName); // Create the excel file in the tmp directory of the system $writer->save($tmpFile); // Return the excel file as an attachment return $this->file($tmpFile, $fileName, ResponseHeaderBag::DISPOSITION_INLINE); } #[Route(path: '/export/pdf', name: 'agency_export_pdf_index', methods: ['GET'])] public function exportPdfIndex(AgencyRepository $agencyRepository): Response { $agencyList = $agencyRepository->findAll(); // Configure Dompdf according to your needs $pdfOptions = new Options(); $pdfOptions->set('defaultFont', 'Arial'); // Instantiate Dompdf with our options $dompdf = new Dompdf($pdfOptions); $dompdf->set_option('isHtml5ParserEnabled', true); $title = 'Welcome to our PDF Test'; // Retrieve the HTML generated in our twig file $html = $this->renderView( 'export/pdf_agency.html.twig', [ 'agencyList' => $agencyList, 'user' => $this->getUser(), ] ); // Load HTML to Dompdf $dompdf->loadHtml($html); // (Optional) Setup the paper size and orientation 'portrait' or 'landscape' $dompdf->setPaper('A4', 'landscape'); // Render the HTML as PDF $dompdf->render(); // Output the generated PDF to Browser (force download) $dompdf->stream( 'entreprises.pdf', [ 'Attachment' => true, ] ); return new Response(); } #[Route(path: '/', name: 'agency_index', methods: ['GET'])] public function index(Request $request, AgencyRepository $agencyRepository): Response { $agencies = $agencyRepository->getAgencysWithSearch($request->get('s')); return $this->render( 'client/index.html.twig', [ 'agencies' => $agencies, ] ); } #[Route(path: '/{id}/utilisateurs', name: 'agency_user_index', methods: ['GET', 'POST'])] public function agencyUsers(Agency $agency, Request $request): Response { $criteria = Criteria::create(); $userFilterType = $this->createForm(UserFilterType::class); $userFilterType->handleRequest($request); if ($userFilterType->isSubmitted()) { $data = $userFilterType->getData(); if ($data['role']) { $criteria->andWhere(Criteria::expr()->contains('roles', $data['role'])); } } $agencyUsers = $agency->getUsers()->matching($criteria); return $this->render( 'client/user.html.twig', [ 'userFilterForm' => $userFilterType->createView(), 'agency' => $agency, 'agencyUsers' => $agencyUsers, ] ); } /** * @throws ORMException * @throws OptimisticLockException * @throws \PhpOffice\PhpSpreadsheet\Exception * @throws \ReflectionException * @throws \App\Import\AgencyImportException */ #[Route(path: '/import/{agency}', name: 'agency_import')] public function import( Agency $agency, ItemRepository $itemRepository, SolutionService $solutionService ): Response { $defaultItems = $itemRepository->findDefaultByAgency($agency, $solutionService->getCurrent()); $import = new AgencyImportDTO($defaultItems); $previewForm = $this->createForm(AgencyImportPreviewType::class, $import); return $this->render('client/import.html.twig', ['agency' => $agency, 'form' => $previewForm->createView()]); } #[Route(path: '/import/{agency}/preview', name: 'agency_import_preview', methods: ['POST'])] public function importPreview( Agency $agency, Request $request, AgencyImporter $agencyImport, KernelInterface $kernel, ): Response { $import = new AgencyImportDTO(); $previewForm = $this->createForm(AgencyImportPreviewType::class, $import); $previewForm->handleRequest($request); if (!$previewForm->isValid()) { $this->addFlash('danger', 'Formulaire invalide'); return $this->redirectToRoute('agency_import', ['agency' => $agency->getId()]); } $import->filePath = $this->getTmpFile($import->importFile, $kernel); $commitForm = $this->createForm(AgencyImportCommitType::class, $import); try { $agencyImport->importFile($import->filePath, $agency); } catch (\Throwable $e) { $this->addFlash('danger', "Le fichier n'a pas pu être lu. Vérifiez qu'il s'agit bien du modèle d'import (.xlsx) et qu'il n'est pas corrompu."); return $this->redirectToRoute('agency_import', ['agency' => $agency->getId()]); } try { $agencyImport->run(false, $import->defaultItems); } catch (\Exception $e) { $this->addFlash('danger', $e->getMessage()); return $this->redirectToRoute('agency_import', ['agency' => $agency->getId()]); } return $this->render( 'client/import.summary.html.twig', ['form' => $commitForm->createView(), 'agency' => $agency, 'summary' => $agencyImport->getSummary()] ); } #[Route(path: '/import/{agency}/commit', name: 'agency_import_commit', methods: ['POST'])] public function importCommit( Request $request, Agency $agency, AgencyImporter $agencyImport ): Response { $import = new AgencyImportDTO(); $commitForm = $this->createForm(AgencyImportCommitType::class, $import); $commitForm->handleRequest($request); if (!$commitForm->isValid()) { $this->addFlash('danger', 'Formulaire invalide'); return $this->redirectToRoute('agency_import', ['agency' => $agency->getId()]); } try { $agencyImport->importFile($import->filePath, $agency); } catch (\Throwable $e) { $this->addFlash('danger', "Le fichier n'a pas pu être lu. Vérifiez qu'il s'agit bien du modèle d'import (.xlsx) et qu'il n'est pas corrompu."); return $this->redirectToRoute('agency_import', ['agency' => $agency->getId()]); } try { $agencyImport->run(true, $import->defaultItems); } catch (UniqueConstraintViolationException $e) { $this->addFlash('danger', "L'import a échoué : une adresse email est utilisée en double (présente plusieurs fois dans le fichier ou déjà enregistrée dans l'application). Vérifiez que chaque email n'apparaît qu'une seule fois."); return $this->redirectToRoute('agency_import', ['agency' => $agency->getId()]); } catch (\Exception $e) { $this->addFlash('danger', $e->getMessage()); return $this->redirectToRoute('agency_import', ['agency' => $agency->getId()]); } $this->addFlash('success', 'Vos informations ont bien été importées'); return $this->redirectToRoute('agency_index', ['agency' => $agency->getId()]); } /** * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception */ #[Route(path: '/agency/export/{id}', name: 'agency_export')] public function export(Agency $agency, AgencyExport $agencyExport): BinaryFileResponse { $agencyExport->setAgency($agency); $agencyExport->run(); $file = $agencyExport->export(); return $this->file($file); } #[Route(path: '/new', name: 'agency_new', methods: ['GET', 'POST'])] public function new(Request $request, EntityManagerInterface $em, string $logosDirectory): Response { $form = $this->createForm(AgencyType::class); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $agency = $form->getData(); if ($agency->getLogo()) { $file = $form->get('logo')->getData(); $fileName = $this->uploadLogo($file, $logosDirectory); $agency->setLogo($fileName); } $em->persist($agency); $em->flush(); return $this->redirectToRoute('agency_index'); } return $this->render( 'client/new.html.twig', [ 'agency' => $form->getData(), 'form' => $form->createView(), ] ); } #[Route(path: '/agencyAjax', name: 'agency_show', methods: ['GET'])] public function show(Request $request, AgencyRepository $agencyRepository): Response { $agency = $agencyRepository->find(intval($request->get('id'))); return $this->render( 'client/show.html.twig', [ 'agency' => $agency, ] ); } #[Route(path: '/{id}/edit', name: 'agency_edit', methods: ['GET', 'POST'])] public function edit(Request $request, Agency $agency, EntityManagerInterface $em, string $logosDirectory): Response { $lastLogo = $agency->getLogo(); $form = $this->createForm(AgencyType::class, $agency); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { if ($agency->getLogo()) { $file = $form->get('logo')->getData(); $fileName = $this->uploadLogo($file, $logosDirectory); $agency->setLogo($fileName); } else { $agency->setLogo($lastLogo); } $em->flush(); return $this->redirectToRoute( 'agency_index', [ 'id' => $agency->getId(), ] ); } return $this->render( 'client/edit.html.twig', [ 'agency' => $agency, 'form' => $form->createView(), ] ); } #[Route(path: '/{id}', name: 'agency_delete', methods: ['DELETE'])] public function delete(Request $request, Agency $agency, EntityManagerInterface $em): Response { if ($this->isCsrfTokenValid('delete'.$agency->getId(), $request->request->get('_token'))) { $em->remove($agency); $em->flush(); } return $this->redirectToRoute('agency_index'); } public function uploadLogo($file, string $logosDirectory): string { $fileName = uniqid().'.'.$file->guessExtension(); // Move the file to the directory where brochures are stored try { $file->move( $logosDirectory, $fileName ); } catch (FileException $e) { // ... handle exception if something happens during file upload } return $fileName; // ... persist the $product variable or any other work } private function getTmpFile( UploadedFile $uploadedFile, KernelInterface $kernel ): string { $tmpFileName = $uploadedFile->move($kernel->getCacheDir()); return $tmpFileName->getPathname(); } }
Save File
Cancel