Spaces:
No application file
No application file
File size: 7,110 Bytes
d2897cd |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 |
<?php
declare(strict_types=1);
namespace Mautic\CoreBundle\Helper;
use Mautic\CoreBundle\Exception\FilePathException;
use Mautic\CoreBundle\Model\IteratorExportDataModel;
use Mautic\LeadBundle\Entity\Lead;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Csv;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* Provides several functions for export-related tasks,
* like exporting to CSV or Excel.
*/
class ExportHelper
{
public const EXPORT_TYPE_EXCEL = 'xlsx';
public const EXPORT_TYPE_CSV = 'csv';
public function __construct(
private TranslatorInterface $translator,
private CoreParametersHelper $coreParametersHelper,
private FilePathResolver $filePathResolver
) {
}
/**
* Returns supported export types as an array.
*/
public function getSupportedExportTypes(): array
{
return [
self::EXPORT_TYPE_CSV,
self::EXPORT_TYPE_EXCEL,
];
}
/**
* Exports data as the given export type. You can get available export types with getSupportedExportTypes().
*
* @param array|\Iterator $data
*/
public function exportDataAs($data, string $type, string $filename): StreamedResponse
{
if (is_array($data)) {
$data = new \ArrayIterator($data);
}
if (!$data->valid()) {
throw new \Exception('No or invalid data given');
}
if (self::EXPORT_TYPE_EXCEL === $type) {
return $this->exportAsExcel($data, $filename);
}
if (self::EXPORT_TYPE_CSV === $type) {
return $this->exportAsCsv($data, $filename);
}
throw new \InvalidArgumentException($this->translator->trans('mautic.error.invalid.specific.export.type', ['%type%' => $type, '%expected_type%' => self::EXPORT_TYPE_EXCEL]));
}
public function exportDataIntoFile(IteratorExportDataModel $data, string $type, string $fileName): string
{
if (!$data->valid()) {
throw new \Exception('No or invalid data given');
}
if (self::EXPORT_TYPE_CSV === $type) {
return $this->exportAsCsvIntoFile($data, $fileName);
}
throw new \InvalidArgumentException($this->translator->trans('mautic.error.invalid.specific.export.type', ['%type%' => $type, '%expected_type%' => self::EXPORT_TYPE_CSV]));
}
public function zipFile(string $filePath, string $fileName): string
{
$zipFilePath = str_replace('.csv', '.zip', $filePath);
$zipArchive = new \ZipArchive();
if (true === $zipArchive->open($zipFilePath, \ZipArchive::OVERWRITE | \ZipArchive::CREATE)) {
$zipArchive->addFile($filePath, $fileName);
$zipArchive->close();
$this->filePathResolver->delete($filePath);
return $zipFilePath;
}
throw new FilePathException("Could not create zip archive at $zipFilePath.");
}
private function exportAsExcel(\Iterator $data, string $filename): StreamedResponse
{
$spreadsheet = $this->getSpreadsheetGeneric($data, $filename);
$objWriter = IOFactory::createWriter($spreadsheet, 'Xlsx');
$objWriter->setPreCalculateFormulas(false);
$response = new StreamedResponse(
function () use ($objWriter): void {
$objWriter->save('php://output');
}
);
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Content-Disposition', 'attachment; filename="'.$filename.'"');
$response->headers->set('Expires', '0');
$response->headers->set('Cache-Control', 'must-revalidate');
$response->headers->set('Pragma', 'public');
return $response;
}
private function getSpreadsheetGeneric(\Iterator $data, string $filename): Spreadsheet
{
$spreadsheet = new Spreadsheet();
$spreadsheet->getProperties()->setTitle($filename);
$spreadsheet->createSheet();
$rowCount = 2;
foreach ($data as $key => $row) {
if (0 === $key) {
// Build the header row from keys in the current row.
$spreadsheet->getActiveSheet()->fromArray(array_keys($row), null, 'A1');
}
$spreadsheet->getActiveSheet()->fromArray($row, null, "A{$rowCount}");
// Increment row
++$rowCount;
}
return $spreadsheet;
}
private function exportAsCsv(\Iterator $data, string $filename): StreamedResponse
{
$spreadsheet = $this->getSpreadsheetGeneric($data, $filename);
$objWriter = new Csv($spreadsheet);
$objWriter->setPreCalculateFormulas(false);
// For UTF-8 support
$objWriter->setUseBOM(true);
$response = new StreamedResponse(
function () use ($objWriter): void {
$objWriter->save('php://output');
}
);
$response->headers->set('Content-Type', 'text/csv');
$response->headers->set('Content-Disposition', 'attachment; filename="'.$filename.'"');
$response->headers->set('Expires', '0');
$response->headers->set('Cache-Control', 'must-revalidate');
$response->headers->set('Pragma', 'public');
return $response;
}
/**
* @param \Iterator<mixed> $data
*/
private function exportAsCsvIntoFile(\Iterator $data, string $fileName): string
{
$filePath = $this->getValidContactExportFileName($fileName);
$handler = @fopen($filePath, 'ab+');
$headerSet = false;
foreach ($data as $row) {
if (!$headerSet) {
fputcsv($handler, array_keys($row));
$headerSet = true;
}
fputcsv($handler, $row);
}
fclose($handler);
return $filePath;
}
private function getValidContactExportFileName(string $fileName): string
{
$contactExportDir = $this->coreParametersHelper->get('contact_export_dir');
$this->filePathResolver->createDirectory($contactExportDir);
$filePath = $contactExportDir.'/'.$fileName;
$fileName = (string) pathinfo($filePath, PATHINFO_FILENAME);
$extension = (string) pathinfo($filePath, PATHINFO_EXTENSION);
$originalName = $fileName;
$i = 1;
while (file_exists($filePath)) {
$fileName = $originalName.'_'.$i;
$filePath = $contactExportDir.'/'.$fileName.'.'.$extension;
++$i;
}
return $filePath;
}
/**
* @return array<string, string>
*/
public function parseLeadToExport(Lead $lead): array
{
$leadExport = $lead->getProfileFields();
$stage = $lead->getStage();
$leadExport['stage'] = $stage ? $stage->getName() : null;
return $leadExport;
}
}
|