<?php

namespace idoit\Component\Csv;

use isys_tenantsettings;
use League\Csv\Reader as CsvReader;
use SplFileObject;

/**
 * i-doit CSV reader.
 *
 * @package     i-doit
 * @subpackage  Component
 * @copyright   synetics GmbH
 * @license     http://www.i-doit.com/license
 * @since       1.13
 */
class Reader extends CsvReader
{
    /**
     * @param string        $path
     * @param string|null   $openMode
     * @param resource|null $context
     *
     * @return Reader
     */
    public static function createFromPath(string $path, ?string $openMode = null, $context = null)
    {
        return parent::createFromPath($path, $openMode ?: 'r+', $context)
            ->configure();
    }

    /**
     * @param string $string
     *
     * @return Reader
     * @throws \League\Csv\InvalidArgument
     */
    public static function createFromString(string $string = '')
    {
        return parent::createFromString($string)->configure();
    }

    /**
     * @param SplFileObject $file
     *
     * @return Reader
     * @throws \League\Csv\InvalidArgument
     */
    public static function createFromFileObject(SplFileObject $file)
    {
        return parent::createFromFileObject($file)->configure();
    }

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