Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
88.89% |
8 / 9 |
|
75.00% |
3 / 4 |
CRAP | |
0.00% |
0 / 1 |
| GenericExport | |
88.89% |
8 / 9 |
|
75.00% |
3 / 4 |
8.09 | |
0.00% |
0 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| headings | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| collection | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
1 | |||
| cell | |
75.00% |
3 / 4 |
|
0.00% |
0 / 1 |
5.39 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace App\Reports; |
| 4 | |
| 5 | use Illuminate\Support\Collection; |
| 6 | use Maatwebsite\Excel\Concerns\FromCollection; |
| 7 | use Maatwebsite\Excel\Concerns\WithHeadings; |
| 8 | |
| 9 | /** |
| 10 | * Turns any Report's columns()+rows() into an .xlsx download — one export |
| 11 | * class for every report, instead of one per report. |
| 12 | */ |
| 13 | class GenericExport implements FromCollection, WithHeadings |
| 14 | { |
| 15 | public function __construct(private readonly Collection $rows, private readonly array $columns) {} |
| 16 | |
| 17 | public function headings(): array |
| 18 | { |
| 19 | return collect($this->columns)->pluck('label')->all(); |
| 20 | } |
| 21 | |
| 22 | public function collection() |
| 23 | { |
| 24 | return $this->rows->map( |
| 25 | fn ($row) => collect($this->columns)->map(fn ($c) => $this->cell($row, $c))->all() |
| 26 | ); |
| 27 | } |
| 28 | |
| 29 | private function cell($row, array $column) |
| 30 | { |
| 31 | if (isset($column['export'])) { |
| 32 | return $column['export']($row); |
| 33 | } |
| 34 | |
| 35 | $value = is_array($row) ? ($row[$column['key']] ?? null) : data_get($row, $column['key']); |
| 36 | |
| 37 | return is_scalar($value) || $value === null ? $value : (string) $value; |
| 38 | } |
| 39 | } |