Paillasse/portail/app/Services/GenerateurCompteEleve.php

69 lines
2.1 KiB
PHP
Raw Normal View History

<?php
namespace App\Services;
use App\Models\Classe;
use App\Models\Eleve;
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
{
// Sans 0/O ni 1/I/L, pour qu'un élève ne confonde pas à la lecture.
private const ALPHABET_CODE = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
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
{
$code = '';
for ($i = 0; $i < 6; $i++) {
$code .= self::ALPHABET_CODE[random_int(0, strlen(self::ALPHABET_CODE) - 1)];
}
return $code;
}
/**
* 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];
}
}