ldc-boutique-cnc/app/Jobs/CsvSalariesReader.php
2022-09-03 16:56:16 +02:00

127 lines
3.5 KiB
PHP

<?php
namespace App\Jobs;
use App\Enums\LogType;
use App\Models\Salarie;
use ErrorException;
use TypeError;
use Illuminate\Database\QueryException;
use App\Exceptions\AbortCsvImportException;
use Illuminate\Support\Str;
class CsvSalariesReader extends CsvJobs
{
/**
* This is for Laravel Console usage
* @var \Illuminate\Console\Command|null
*/
public $console = null;
/**
* The Laravel disk name
*
* @var string
*/
protected $disk = 'salaries';
/**
* Create a new job instance.
*
* @return void
*/
public function __construct()
{
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
/** @var Filesystem */
$disk = $this->getDisk();
$this->log('Démarrage du traitement');
$files = $disk->files();
$progress = 1;
$total = count(array_filter($files, function ($filename) {
if ($this->fileHasToBeIgnored($filename)) {
return false;
}
return true;
}));
foreach ($files as $filename) {
if ($this->fileHasToBeIgnored($filename)) {
continue;
}
$this->log(sprintf(' traitement %d sur %s ', $progress++, $total));
/** @var string $filepath */
$filepath = $disk->path($filename);
try {
$data = $this->parseCsv($filepath);
// First line is header (mandatory).
$header = array_flip(array_shift($data));
foreach ($data as $line) {
$matricule = $line[$header['matricule']];
$prenom = $line[$header['prenom']];
$nom = $line[$header['nom']];
$salarie = Salarie::firstOrNew(['matricule' => $matricule ]);
$salarie->matricule = $matricule;
$salarie->nom = $nom;
$salarie->prenom = $prenom;
$salarie->code = $salarie->code ?? $this->generateCode();
$salarie->save();
}
} catch (ErrorException | TypeError | QueryException $e) {
$message = $e->getMessage();
if (get_class($e) === QueryException::class) {
$message = implode(' ', $e->errorInfo);
}
$this->log(
sprintf(
'File %s could not be parsed => %s on line %d',
$filename,
$message,
$e->getLine()
),
LogType::critical()
);
continue;
// Ignore the file.
} catch (AbortCsvImportException $e) {
$this->log(
sprintf(
'File %s could not be parsed => %s on line %d',
$filename,
$e->getMessage(),
$e->getLine()
),
LogType::error()
);
continue;
// Ignore the file.
}//end try
$this->moveToArchives($filename);
}//end foreach
// Clear old archives.
$this->clearOldArchives();
}
/**
* Génère un code d'inscription
*
* @return string
*/
protected function generateCode()
{
return Str::random(5);
}
}