php-test/classes/quiz.class.php

127 lines
2.7 KiB
PHP

<?php
namespace TestProject;
/*
* Quiz class
*/
class Quiz extends Item {
private const tb_str = 'quiz';
private const resultTb_str = 'quiz_result';
private $name_str;
private $maxScore_int;
private $questionID_arr;
/**
* Load quiz
*
* @param int $id_int ID of quiz to load
*/
public function __construct( int $id_int ){
$db = DB::getDB();
$rows_arr = $db->select( self::tb_str, array(), array( 'id' => $id_int ) );
if ( empty( $rows_arr ) ){
throw new \RuntimeException( 'Invalid quiz ID' );
}
$this->id_int = $rows_arr[0]['id'];
$this->name_str = $rows_arr[0]['name'];
$this->maxScore_int = $rows_arr[0]['max_score'];
$this->questionID_arr = Question::getList( $this->id_int );
}
/**
* Get a list of quiz IDs and names
*
* @return string[] Array of quiz names keyed by id
*/
public static function getList(){
$db = DB::getDB();
$quiz_arr = $db->select( self::tb_str, array( 'id', 'name' ) );
return $quiz_arr;
}
/**
* Get name of Quiz
*
* @return string Name
*/
public function getName(){
return $this->name_str;
}
/**
* Get Maximum possible Score of quiz
*
* @return int Max score
*/
public function getMaxScore(){
return $this->maxScore_int;
}
/**
* Calculate and save the total score of a user
*
* @param int $userID_int $userID_int ID of user
*
* @return string Access key for results page
*/
public function saveResult( int $userID_int ){
$db = DB::getDB();
$total_int = 0;
foreach( $this->questionID_arr as $questionID_int ){
$question = new Question( $questionID_int );
$total_int += $question->getScore( $userID_int );
}
$accessKey_str = hash( 'sha256', $this->id_int . $userID_int . microtime() );
$db->insert(
self::resultTb_str,
array(
'quiz' => $this->id_int,
'user' => $userID_int,
'score' => $total_int,
'access_key' => $accessKey_str
)
);
return $accessKey_str;
}
/**
* Get result for user and calculate average score
*
* @param string $acessKey_str Access key for result
*
* @return mixed[] Array of result data
*/
public static function getResult( string $accessKey_str ){
$db = DB::getDB();
$rows_arr = $db->select( self::resultTb_str, array(), array( 'access_key' => $accessKey_str ) );
if ( empty( $rows_arr ) ){
throw new \RuntimeException( 'Invalid access key' );
}
$result_arr = $rows_arr[0];
$rows_arr = $db->select( self::resultTb_str, array( 'score' ), array( 'quiz' => $result_arr['quiz'] ) );
$total_int = 0;
foreach ( $rows_arr as $row_arr ){
$total_int += $row_arr['score'];
}
$result_arr['average'] = $total_int / count( $rows_arr );
return $result_arr;
}
}