Paillasse/portail/app/Services/Quiz/LecteurGift.php

73 lines
2.2 KiB
PHP
Raw Normal View History

<?php
namespace App\Services\Quiz;
use App\Models\QuestionQuiz;
use Illuminate\Support\Facades\File;
/**
* Lit un fichier quiz.gift (format GIFT, voir paillasse-contenus/README.md).
* Seuls les types QCM et vrai/faux sont supportés par la banque (schéma de
* questions_quiz) : un type numérique ({#N}, utilisable dans Moodle) est
* ignoré avec un avertissement plutôt que d'inventer une réponse.
*/
class LecteurGift
{
/**
* @return array{questions: array<int, array{enonce: string, type: string, reponse_vrai_faux: ?bool, choix: array<int, array{texte: string, est_correct: bool}>}>, avertissements: array<int, string>}
*/
public static function lire(string $chemin): array
{
$texte = preg_replace('/^[ \t]*\/\/.*$/m', '', File::get($chemin));
$questions = [];
$avertissements = [];
preg_match_all('/::(.*?)::(.*?)\{(.*?)\}/s', $texte, $blocs, PREG_SET_ORDER);
foreach ($blocs as $bloc) {
$enonce = trim($bloc[2]);
$contenu = trim($bloc[3]);
if ($contenu === 'T' || $contenu === 'F') {
$questions[] = [
'enonce' => $enonce,
'type' => QuestionQuiz::VRAI_FAUX,
'reponse_vrai_faux' => $contenu === 'T',
'choix' => [],
];
continue;
}
if (str_starts_with($contenu, '#')) {
$avertissements[] = "question numérique ignorée (type non supporté par la banque) : {$enonce}";
continue;
}
$choix = [];
foreach (preg_split('/\r?\n/', $contenu) as $ligne) {
$ligne = trim($ligne);
if ($ligne === '') {
continue;
}
$choix[] = [
'texte' => trim(substr($ligne, 1)),
'est_correct' => $ligne[0] === '=',
];
}
$questions[] = [
'enonce' => $enonce,
'type' => QuestionQuiz::QCM,
'reponse_vrai_faux' => null,
'choix' => $choix,
];
}
return ['questions' => $questions, 'avertissements' => $avertissements];
}
}