94 lines
2.9 KiB
PHP
94 lines
2.9 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
declare(strict_types=1);
|
||
|
|
|
||
|
|
namespace App\Services;
|
||
|
|
|
||
|
|
use App\Models\Employee;
|
||
|
|
use Illuminate\Support\Collection;
|
||
|
|
use Illuminate\Support\Enumerable;
|
||
|
|
use Maatwebsite\Excel\Concerns\FromCollection;
|
||
|
|
use Maatwebsite\Excel\Concerns\WithCustomCsvSettings;
|
||
|
|
use Maatwebsite\Excel\Concerns\WithHeadings;
|
||
|
|
use Maatwebsite\Excel\Concerns\WithMapping;
|
||
|
|
use Maatwebsite\Excel\Facades\Excel;
|
||
|
|
|
||
|
|
class EmployeeExportService
|
||
|
|
{
|
||
|
|
/** @param \App\Models\Employee[] $employeesToExport */
|
||
|
|
public function export(string $diskName, string $filename, array $employeesToExport): bool
|
||
|
|
{
|
||
|
|
foreach ($employeesToExport as $employee) {
|
||
|
|
throw_unless(
|
||
|
|
$employee instanceof Employee,
|
||
|
|
\InvalidArgumentException::class,
|
||
|
|
'employeeToExport as to be an array of ' . Employee::class
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
$exportClass = $this->getExportClass($employeesToExport);
|
||
|
|
|
||
|
|
return Excel::store($exportClass, $filename, $diskName);
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* @param \App\Models\Employee[] $employeesToExport
|
||
|
|
* @return FromCollection<array-key,\App\Models\Employee>&WithCustomCsvSettings&WithHeadings&WithMapping<\App\Models\Employee>
|
||
|
|
*/
|
||
|
|
private function getExportClass(array $employeesToExport): FromCollection & WithCustomCsvSettings & WithHeadings & WithMapping
|
||
|
|
{
|
||
|
|
return new readonly class ($employeesToExport) implements
|
||
|
|
FromCollection,
|
||
|
|
WithCustomCsvSettings,
|
||
|
|
WithHeadings,
|
||
|
|
WithMapping
|
||
|
|
{
|
||
|
|
/** @param \App\Models\Employee[] $employeesToExport */
|
||
|
|
public function __construct(
|
||
|
|
private array $employeesToExport
|
||
|
|
) {
|
||
|
|
}
|
||
|
|
|
||
|
|
/** @return string[] */
|
||
|
|
public function headings(): array
|
||
|
|
{
|
||
|
|
return [
|
||
|
|
'Matricule',
|
||
|
|
'Nom',
|
||
|
|
'Prenom',
|
||
|
|
'Site',
|
||
|
|
'Code',
|
||
|
|
];
|
||
|
|
}
|
||
|
|
|
||
|
|
/** @param \App\Models\Employee $employee */
|
||
|
|
public function map($employee): array
|
||
|
|
{
|
||
|
|
/** @var \App\Models\Employee $employee */
|
||
|
|
return [
|
||
|
|
$employee->matricule->value,
|
||
|
|
$employee->nom,
|
||
|
|
$employee->prenom,
|
||
|
|
$employee->site,
|
||
|
|
$employee->code,
|
||
|
|
];
|
||
|
|
}
|
||
|
|
|
||
|
|
/** @return array<string,string> */
|
||
|
|
public function getCsvSettings(): array
|
||
|
|
{
|
||
|
|
return [
|
||
|
|
'delimiter' => ';',
|
||
|
|
'output_encoding' => 'UTF-8',
|
||
|
|
];
|
||
|
|
}
|
||
|
|
|
||
|
|
/** @return \Illuminate\Support\Enumerable<array-key,\App\Models\Employee> */
|
||
|
|
public function collection(): Enumerable
|
||
|
|
{
|
||
|
|
return Collection::make($this->employeesToExport);
|
||
|
|
}
|
||
|
|
};
|
||
|
|
}
|
||
|
|
}
|