1 | <?php |
||
2 | |||
3 | namespace App\Models; |
||
4 | |||
5 | use Illuminate\Database\Eloquent\Factories\HasFactory; |
||
6 | use Illuminate\Database\Eloquent\Model; |
||
7 | |||
8 | class Attempt extends Model |
||
9 | { |
||
10 | use HasFactory; |
||
11 | |||
12 | const CREATED_AT = 'started_at'; |
||
13 | |||
14 | protected $guarded = ['id']; |
||
15 | |||
16 | protected $dates = [ |
||
17 | 'submitted_at', |
||
18 | 'examined_at', |
||
19 | ]; |
||
20 | |||
21 | protected $casts = [ |
||
22 | 'answers' => 'object', |
||
23 | ]; |
||
24 | |||
25 | // Custom Attributes |
||
26 | |||
27 | public function getTimeRemainingAttribute() |
||
28 | { |
||
29 | return $this->quiz->time_limit - now()->diffInSeconds($this->started_at); |
||
30 | } |
||
31 | |||
32 | public function getQuestionsAttribute() |
||
33 | { |
||
34 | return Question::where('quiz_id', $this->quiz_id)->whereIn('id', array_keys(get_object_vars($this->answers)))->get(); |
||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
35 | } |
||
36 | |||
37 | // Relations |
||
38 | |||
39 | public function user() |
||
40 | { |
||
41 | return $this->belongsTo(User::class); |
||
42 | } |
||
43 | |||
44 | public function quiz() |
||
45 | { |
||
46 | return $this->belongsTo(Quiz::class); |
||
47 | } |
||
48 | |||
49 | // Helper Functions |
||
50 | |||
51 | public function examine() |
||
52 | { |
||
53 | if (! $this->questions) { |
||
54 | return false; |
||
55 | } |
||
56 | |||
57 | $questions = $this->questions->mapWithKeys(function ($item) { |
||
58 | return [$item->id => $item->answer]; |
||
59 | }); |
||
60 | |||
61 | $corrects = 0; |
||
62 | $wrongs = 0; |
||
63 | |||
64 | foreach ($this->answers as $qid => $answer) { |
||
65 | if ($answer == $questions[$qid]) { |
||
66 | $corrects++; |
||
67 | } elseif ($answer !== null) { |
||
68 | $wrongs++; |
||
69 | } |
||
70 | } |
||
71 | |||
72 | $this->corrects = $corrects; |
||
73 | $this->wrongs = $wrongs; |
||
74 | $this->marks = $this->corrects * $this->quiz->marks_per_question; |
||
75 | $this->marks = is_int($this->marks) ? $this->marks : round($this->marks, 2); |
||
0 ignored issues
–
show
|
|||
76 | $this->examined_at = now(); |
||
77 | |||
78 | return $this->save(); |
||
79 | } |
||
80 | } |
||
81 |