<?php

declare(strict_types=1);

class CsvExporter
{
    /**
     * @var resource
     */
    protected $csvFile;

    /**
     * @var string
     */
    protected $fileName;

    /**
     * @var string
     */
    protected $delimiter;

    /**
     * @param array<string>|null $header
     *
     * @throws Exception
     */
    public function __construct(string $fileName, string $delimiter = ';', ?array $header = null)
    {
        $csvFile = fopen('php://temp', 'w');

        if (!$csvFile) {
            throw new Exception('Création de fichier impossible');
        }
        $this->csvFile = $csvFile;
        $this->fileName = $fileName;
        $this->delimiter = $delimiter;

        if ($header) {
            fputcsv($this->csvFile, $header, $delimiter);
        }
    }

    /**
     * @param array<array<string>> $collection
     */
    public function write(array $collection): void
    {
        foreach ($collection as $object) {
            fputcsv($this->csvFile, $object, $this->delimiter);
        }
    }

    public function getContent(): ?string
    {
        rewind($this->csvFile);
        $file_contents = stream_get_contents($this->csvFile);
        fclose($this->csvFile);

        return false === $file_contents ? null : $file_contents;
    }
}
