ldc-gen-game-web/app/Jobs/ProcessUniqueCode.php

91 lines
2.4 KiB
PHP
Raw Normal View History

<?php
namespace App\Jobs;
use App\Mail\CodeGenerationEnd;
use App\Mail\JobFailed;
use App\Models\Codes;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;
class ProcessUniqueCode implements ShouldQueue
{
2021-08-18 17:08:02 +02:00
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
private $quantity;
2021-08-18 17:08:02 +02:00
private $length;
2021-08-18 17:08:02 +02:00
private $settings;
/**
* Create a new job instance.
*
* @return void
*/
2021-08-18 17:08:02 +02:00
public function __construct($quantity, $length, $settings)
{
$this->quantity = $quantity;
2021-08-18 17:08:02 +02:00
$this->length = $length;
$this->settings = $settings;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
set_time_limit(0);
for ($ib = 1; $ib <= $this->quantity;) {
try {
2021-08-18 17:08:02 +02:00
$code = new Codes();
$code->code_unique = $this->getCode($this->length);
$code->date_creation = now();
$code->save();
2021-08-18 17:08:02 +02:00
if ($code) {
$ib++;
}
} catch (\PDOException $e) {
2021-08-18 17:08:02 +02:00
if (!strpos($e->getMessage(), 'Duplicate entry')) {
Mail::to(config('mail.MAIL_ADMIN'))->send(new JobFailed("ProcessUniqueCode", ['message' => $e->getMessage(), 'trace' => $e->getTraceAsString()]));
die();
}
}
}
// ---- Fin de la génération
Mail::to(config('mail.MAIL_ADMIN'))->send(new CodeGenerationEnd($this->quantity, $this->settings));
}
2021-08-18 17:08:02 +02:00
private function getCode($car)
{
$chaine = "ABCDEFGHJKMNPQRSTUWXYZ123456789"; // Caractères autorisés
$valprec = "";
2021-08-18 17:08:02 +02:00
$string = "";
srand();
for ($i = 0; $i < $car;) {
$val = $chaine[rand() % strlen($chaine)];
2021-08-18 17:08:02 +02:00
if ($val != $valprec) {
$string .= $val;
$valprec = $val;
$i++;
}
}
return $string;
}
2021-08-18 17:08:02 +02:00
public function failed(Exception $exception)
{
Mail::to(config('mail.MAIL_ADMIN'))->send(new JobFailed("ProcessUniqueCode", ['message' => $exception->getMessage(), 'trace' => $exception->getTraceAsString()]));
}
}