<?php

namespace idoit\Component\Csv;

use isys_tenantsettings;
use League\Csv\EncloseField;
use League\Csv\Writer as CsvWriter;
use SplFileObject;

/**
 * i-doit CSV reader.
 *
 * @package     i-doit
 * @subpackage  Component
 * @author      Leonard Fischer <lfischer@i-doit.com>
 * @copyright   synetics GmbH
 * @license     http://www.i-doit.com/license
 * @since       1.13
 */
class Writer extends CsvWriter
{
    /**
     * @param string        $path
     * @param string|null   $openMode
     * @param resource|null $context the resource context
     *
     * @return Writer
     * @throws \League\Csv\Exception
     */
    public static function createFromPath(string $path, ?string $openMode = null, $context = null)
    {
        $writer = parent::createFromPath($path, $openMode ?: 'r+', $context)->configure();
        EncloseField::addTo($writer, "\t\x1f");

        return $writer;
    }

    /**
     * @param string $string
     *
     * @return Writer
     * @throws \League\Csv\Exception
     */
    public static function createFromString(string $string = '')
    {
        $writer = parent::createFromString($string)->configure();
        EncloseField::addTo($writer, "\t\x1f");
        return $writer;
    }

    /**
     * Forced enclosure does not work with SplFileObject
     *
     * @param  SplFileObject $file
     *
     * @return self
     */
    public static function createFromFileObject(SplFileObject $file)
    {
        return parent::createFromFileObject($file)->configure();
    }

    /**
     * @return Writer
     */
    private function configure()
    {
        return $this
            ->setOutputBOM(self::BOM_UTF8)
            ->setDelimiter(isys_tenantsettings::get('system.csv-export-delimiter', ';'));
    }
}
