table-document/src/TableDocumentData.php

66 lines
1.8 KiB
PHP

<?php
namespace Zoomyboy\TableDocument;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Spatie\LaravelData\Data;
use Spatie\LaravelData\DataCollection;
use Spatie\LaravelData\Attributes\DataCollectionOf;
class TableDocumentData extends Data
{
public Spreadsheet $spreadsheet;
public function __construct(
#[DataCollectionOf(SheetData::class)]
public DataCollection $sheets,
public string $title,
) {
}
public function compile(string $path): string
{
$this->spreadsheet = new Spreadsheet();
$this->spreadsheet->getProperties()
->setTitle($this->title)
->setSubject($this->title)
->setDescription($this->title);
$this->spreadsheet->getDefaultStyle()->getFont()->setSize(12);
$this->spreadsheet->getActiveSheet()->setTitle('unfilled');
foreach ($this->sheets as $sheet) {
$this->compileSheet($sheet);
}
$this->spreadsheet->setActiveSheetIndex(0);
$writer = new Xlsx($this->spreadsheet);
$writer->save($path);
$this->spreadsheet->disconnectWorksheets();
return $path;
}
public function addSheet(SheetData $sheet): self
{
$this->sheets[] = $sheet;
return $this;
}
private function compileSheet(SheetData $sheet): void
{
if ('unfilled' !== $this->spreadsheet->getActiveSheet()->getTitle()) {
$this->spreadsheet->addSheet(new Worksheet($this->spreadsheet, $sheet->name));
$this->spreadsheet->setActiveSheetIndexByName($sheet->name);
}
$this->spreadsheet->getActiveSheet()->setTitle($sheet->name);
$sheet->fill($this->spreadsheet);
}
}