<?php

namespace onespace\tools\helpers\traits;

trait CSVLoader {

    /**
     * @param   string  $fileName   The full or relative file path and name.
     * 
     * @param   string  $memoryLimit    Set the defined PHP memory limit. Increase when dealing with larger CSV files.
     * 
     * @param   int|null    $getRows Limit the number of rows returned.
     * Defaults as null (no limit).
     * 
     * @param int|null $length
     * 
     * @param string $separator
     * [optional] Set the field delimiter (one character only).
     * 
     * @param string $enclosure
     * [optional] Set the field enclosure character (one character only).
     * 
     * @param string $escape
     * [optional] Set the escape character (one character only). Defaults as a backslash.
     * 
     * @return  array
     * 
     * @access  public
     */

    public function getCSVDataFromFile(
        string $filename,
        string $memoryLimit = '128M',
        ?int $getRows = null,
        ?int $length = null,
        string $separator = ',',
        string $enclosure = '"',
        string $escape = '\\'
    ): array {
        ini_set('memory_limit', $memoryLimit);
        $data = [];

        $file = fopen($filename, 'r');
        if (!$file) {
            echo "Unable to open file: {$filename}\n";
            exit(1);
        }

        $headings = [];
        $rowIndex = 0;
        $maxLen = 0;
        while (($csvData = fgetcsv($file, $length,  $separator, $enclosure, $escape)) !== false) {
            if ($rowIndex == 0) {
                $maxLen = count($csvData);
                $headings = $csvData;
                $rowIndex++;
                continue;
            }
            if (count($csvData) !== $maxLen) {
                echo "Line {$rowIndex} doesn't have complete data\n";
                exit(1);
            }
            $data[] = array_combine($headings, $csvData);
            if (!is_null($getRows) && $rowIndex == $getRows) {
                break;
            }
            $rowIndex++;
        }

        // clear some memory
        $csvData = $headings = null;
        fclose($file);
        return $data;
    }
}
