SpreadQuiz/class/Tasks/OpenEndedTask.php
2025-09-30 22:44:06 +02:00

63 lines
1.5 KiB
PHP

<?php
require_once "PicturedTask.php";
class OpenEndedTask extends PicturedTask
{
public function __construct(array $a = null)
{
parent::__construct("openended", $a);
$this->correct_answer = $a["correct_answer"] ?? null;
$this->setMaxMark(1.0);
}
public function addCorrectAnswer(string $ca): void {
$this->correct_answer[] = $ca;
}
public function saveAnswer(mixed $ans): bool
{
// collect transformations
$transform_fns = [];
foreach ($this->flags as $flag) {
switch ($flag) {
case "makeuppercase":
$transform_fns[] = "strtoupper";
break;
case "makelowercase":
$transform_fns[] = "strtolower";
break;
case "removespaces":
$transform_fns[] = fn($str) => str_replace(" ", "", $str);
break;
}
}
// run the transformations
foreach ($transform_fns as $tfn) {
$ans = $tfn($ans);
}
// save the answer
$this->player_answer = $ans;
return true;
}
public function clearAnswer(): void
{
$this->player_answer = "";
}
public function getMark(): float
{
return in_array($this->player_answer, $this->correct_answer) ? 1.0 : 0.0;
}
function toArray(): array {
$a = parent::toArray();
$a["correct_answer"] = $this->correct_answer;
return $a;
}
}