<?php
namespace Helpers\ExportTo;

class CsvRes
{
    /** @var resource */
    private $file_p;
    
    /**
     * @param resource $file_p
     */
    public function __construct($file_p)
    {
        $this->file_p = $file_p;
    }

    public static function touch(string $filepath) :self
    {
        $p = fopen($filepath, 'w');
        if ($p === false) {
            throw new \Exception('fputcsv failed on "'.$filepath.'"');
        }
        fprintf($p, chr(0xEF).chr(0xBB).chr(0xBF));// TODO : only do if new file
        return new CsvRes($p);
    }

    /**
     * @param array<string> $row
     */
    public function addRow(array $row, string $delimiter = ';') :self
    {
        $b = fputcsv($this->file_p, $row, ';');
        if ($b === false) {
            throw new \Exception('fputcsv failed on '.var_export($row, true));
        }
        return $this;
    }

    public function __destruct()
    {
        fclose($this->file_p);
    }
}
