48 lines
		
	
	
	
		
			1.3 KiB
		
	
	
	
		
			PHP
		
	
	
	
	
	
			
		
		
	
	
			48 lines
		
	
	
	
		
			1.3 KiB
		
	
	
	
		
			PHP
		
	
	
	
	
	
<?php
 | 
						|
 | 
						|
namespace App\Helpers;
 | 
						|
 | 
						|
use Illuminate\Support\Facades\File;
 | 
						|
use Illuminate\Support\Facades\Log;
 | 
						|
use Iterator;
 | 
						|
use League\Csv\CannotInsertRecord;
 | 
						|
use League\Csv\Exception;
 | 
						|
use League\Csv\InvalidArgument;
 | 
						|
use League\Csv\Reader;
 | 
						|
use League\Csv\Writer;
 | 
						|
 | 
						|
class CsvHelper
 | 
						|
{
 | 
						|
    /**
 | 
						|
     * @throws Exception
 | 
						|
     */
 | 
						|
    public static function getRecords($filePath, $message): Iterator {
 | 
						|
        $csv = Reader::createFromPath($filePath);
 | 
						|
        try {
 | 
						|
            $csv->setDelimiter("|");
 | 
						|
            $csv->setEnclosure("'");
 | 
						|
            $csv->setHeaderOffset(0);
 | 
						|
            return $csv->getRecords();
 | 
						|
        } catch (InvalidArgument|Exception $e) {
 | 
						|
            Log::error($e->getMessage());
 | 
						|
            throw new Exception($message, $e);
 | 
						|
        }
 | 
						|
    }
 | 
						|
 | 
						|
    public static function generarCsv($filePath, $contenido, $headers = null): void
 | 
						|
    {
 | 
						|
        if (!File::exists(storage_path('csv/exports'))) {
 | 
						|
            File::makeDirectory(storage_path('csv/exports'), 0755, true);
 | 
						|
        }
 | 
						|
 | 
						|
        try {
 | 
						|
            $writer = Writer::createFromPath(storage_path($filePath), 'w');
 | 
						|
            if ($headers) {
 | 
						|
                $writer->insertOne($headers);
 | 
						|
            }
 | 
						|
            $writer->insertAll($contenido);
 | 
						|
        } catch (CannotInsertRecord $e) {
 | 
						|
            Log::error($e->getMessage(), $e->getTrace());
 | 
						|
        }
 | 
						|
    }
 | 
						|
}
 |