92 lines
2.1 KiB
PHP
92 lines
2.1 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Collection;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
|
|
class UserTest extends Model
|
|
{
|
|
use HasFactory;
|
|
|
|
protected $fillable = [
|
|
'category_id',
|
|
'test_id',
|
|
'closed_at',
|
|
'is_completed',
|
|
'score',
|
|
];
|
|
|
|
protected $casts = [
|
|
'closed_at' => 'datetime',
|
|
'is_completed' => 'boolean',
|
|
];
|
|
|
|
/**
|
|
* Generating empty answers to fill later
|
|
* @param Collection<Question>|array<Question> $questions
|
|
* @return void
|
|
*/
|
|
public function generateEmptyAnswers(Collection|array $questions)
|
|
{
|
|
$answers = [];
|
|
foreach ($questions as $question) {
|
|
$questionId = is_array($question) ? $question['id'] : $question->id;
|
|
|
|
$answers[] = [
|
|
'question_id' => $questionId,
|
|
'user_test_id' => $this->id,
|
|
'user_id' => $this->user_id,
|
|
'created_at' => now(),
|
|
'updated_at' => now(),
|
|
];
|
|
}
|
|
|
|
UserTestAnswer::insert($answers);
|
|
}
|
|
|
|
public function completeTest()
|
|
{
|
|
$correctAnswers = 0;
|
|
$allAnswers = $this->answers->count();
|
|
|
|
foreach ($this->answers as $answer) {
|
|
if($answer->isCorrect())
|
|
$correctAnswers++;
|
|
}
|
|
|
|
$this->score = intval($correctAnswers * 100 / $allAnswers);
|
|
$this->is_completed = true;
|
|
$this->save();
|
|
}
|
|
|
|
/**
|
|
* Check cooldown for current test
|
|
* @return bool
|
|
*/
|
|
public function isAvailable()
|
|
{
|
|
return (!$this->is_completed) &&
|
|
($this->closed_at === null || now()->lt($this->closed_at));
|
|
}
|
|
|
|
public function category()
|
|
{
|
|
return $this->belongsTo(Category::class);
|
|
}
|
|
|
|
public function test()
|
|
{
|
|
return $this->belongsTo(Test::class);
|
|
}
|
|
|
|
public function user()
|
|
{
|
|
return $this->belongsTo(User::class);
|
|
}
|
|
public function answers()
|
|
{
|
|
return $this->hasMany(UserTestAnswer::class);
|
|
}
|
|
} |