65 lines
1.6 KiB
PHP
65 lines
1.6 KiB
PHP
<?php
|
|
|
|
class TestSummary
|
|
{
|
|
public int $maxMark; // Maximum mark
|
|
public int $mark; // Collected mark
|
|
private float $percentage; // Ratio of correct answers
|
|
|
|
// Calculate percentage.
|
|
private function calculatePercentage(): void
|
|
{
|
|
if ($this->maxMark > 0) {
|
|
$this->percentage = $this->mark / (double)$this->maxMark * 100.0;
|
|
} else { // avoid division by zero
|
|
$this->percentage = 0.0;
|
|
}
|
|
}
|
|
|
|
function __construct(int $taskN, int $correctAnswerN)
|
|
{
|
|
$this->maxMark = $taskN;
|
|
$this->mark = $correctAnswerN;
|
|
$this->calculatePercentage();
|
|
}
|
|
|
|
// Get max mark.
|
|
function getMaxMark(): int
|
|
{
|
|
return $this->maxMark;
|
|
}
|
|
|
|
// Get mark.
|
|
function getMark(): int
|
|
{
|
|
return $this->mark;
|
|
}
|
|
|
|
function setMark(int $mark): void
|
|
{
|
|
$this->mark = $mark;
|
|
$this->calculatePercentage();
|
|
}
|
|
|
|
// Get ratio of correct results.
|
|
function getPercentage(): float
|
|
{
|
|
return ($this->mark * 100.0) / $this->maxMark;
|
|
}
|
|
|
|
// Build from array.
|
|
static function fromArray(array $a): TestSummary
|
|
{
|
|
if (!isset($a["max_mark"]) || !isset($a["mark"])) { // backward compatibility
|
|
return new TestSummary($a["challenge_n"], $a["correct_answer_n"]);
|
|
} else {
|
|
return new TestSummary($a["max_mark"], $a["mark"]);
|
|
}
|
|
}
|
|
|
|
// Convert to array.
|
|
function toArray(): array
|
|
{
|
|
return ["challenge_n" => $this->maxMark, "correct_answer_n" => $this->mark, "percentage" => $this->percentage];
|
|
}
|
|
} |