61 lines
1.8 KiB
PHP
61 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\Classe;
|
|
use App\Models\Eleve;
|
|
use App\Support\CodeLisible;
|
|
use Illuminate\Support\Facades\Hash;
|
|
use Illuminate\Support\Str;
|
|
|
|
/**
|
|
* Génère les identifiants (prénom.initiale, avec un numéro pour les
|
|
* homonymes) et les codes secrets des élèves (étape 8 du déploiement).
|
|
*/
|
|
class GenerateurCompteEleve
|
|
{
|
|
public function genererIdentifiant(string $prenom, ?string $nom): string
|
|
{
|
|
$base = Str::slug($prenom, '');
|
|
if ($nom !== null && $nom !== '') {
|
|
$base .= '.'.Str::slug(mb_substr($nom, 0, 1));
|
|
}
|
|
|
|
$identifiant = $base;
|
|
$suffixe = 2;
|
|
while (Eleve::where('identifiant', $identifiant)->exists()) {
|
|
$identifiant = $base.$suffixe;
|
|
$suffixe++;
|
|
}
|
|
|
|
return $identifiant;
|
|
}
|
|
|
|
public function genererCodeSecret(): string
|
|
{
|
|
return CodeLisible::genere(6);
|
|
}
|
|
|
|
/**
|
|
* Crée le compte d'un élève et renvoie sa fiche (le code secret en clair
|
|
* n'existe que dans cette fiche : il est stocké haché).
|
|
*
|
|
* @return array{eleve: Eleve, identifiant: string, prenom: string, nom: ?string, code_secret: string, jeton_qr: string}
|
|
*/
|
|
public function creerDans(Classe $classe, string $prenom, ?string $nom): array
|
|
{
|
|
$identifiant = $this->genererIdentifiant($prenom, $nom);
|
|
$codeSecret = $this->genererCodeSecret();
|
|
$jetonQr = Str::random(32);
|
|
|
|
$eleve = $classe->eleves()->create([
|
|
'prenom' => $prenom,
|
|
'nom' => $nom,
|
|
'identifiant' => $identifiant,
|
|
'code_secret' => Hash::make($codeSecret),
|
|
'jeton_qr' => $jetonQr,
|
|
]);
|
|
|
|
return ['eleve' => $eleve, 'identifiant' => $identifiant, 'prenom' => $prenom, 'nom' => $nom, 'code_secret' => $codeSecret, 'jeton_qr' => $jetonQr];
|
|
}
|
|
}
|