pedi2/app/Helpers/CsvHelper.php

101 lines
2.9 KiB
PHP

<?php
namespace App\Helpers;
use App\Http\Controllers\ComisionesController;
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 {
try {
$csv = self::getReader($filePath);
return $csv->getRecords();
} catch (InvalidArgument|Exception $e) {
Log::error($e->getMessage());
throw new Exception($message, $e);
}
}
/**
* @throws Exception
*/
public static function cambiarParametro(string $id, string $valor): void
{
try {
$updated = false;
$filePath = resource_path(ComisionesController::PARAMETROS_PATH);
$csv = self::getReader($filePath);
$headers = $csv->getHeader();
$records = array_map(fn($r) => (array) $r, iterator_to_array($csv->getRecords()));
foreach ($records as &$record) {
if ($record['id'] === $id) {
$record['valor'] = $valor;
$updated = true;
break;
}
}
unset($record);
if (!$updated)
throw new Exception("Parametro '{$id}' no encontrado.");
self::generarCsv($filePath, $records, $headers, "|", "'", false);
} catch (CannotInsertRecord | InvalidArgument $e) {
Log::error("Error al actualizar csv: " . $e->getMessage());
throw new Exception("Error al actualizar csv", $e);
}
}
/**
* @throws InvalidArgument
* @throws CannotInsertRecord
*/
public static function generarCsv($filePath, $contenido, $headers = null, $delimiter = null, $enclosure = null, $export = true): void
{
$path = $filePath;
if ($export) {
if (!File::exists(storage_path('csv/exports')))
File::makeDirectory(storage_path('csv/exports'), 0755, true);
$path = storage_path($filePath);
}
$writer = Writer::createFromPath($path, 'w');
if ($delimiter)
$writer->setDelimiter($delimiter);
if ($enclosure)
$writer->setEnclosure($enclosure);
if ($headers)
$writer->insertOne($headers);
$writer->insertAll($contenido);
}
/**
* @param string $filePath
* @return Reader
* @throws InvalidArgument
* @throws Exception
*/
private static function getReader(string $filePath): Reader
{
$csv = Reader::createFromPath($filePath);
$csv->setDelimiter("|");
$csv->setEnclosure("'");
$csv->setHeaderOffset(0);
return $csv;
}
}