Passed
Pull Request — develop (#11)
by
unknown
03:46 queued 56s
created

Invitation   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 75
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 20
dl 0
loc 75
rs 10
c 0
b 0
f 0
wmc 6

4 Methods

Rating   Name   Duplication   Size   Complexity  
A student() 0 3 1
A group() 0 3 1
A scopeOfStudentInCourse() 0 5 1
A create() 0 25 3
1
<?php
2
3
namespace App\Judite\Models;
4
5
use Illuminate\Support\Facades\DB;
6
use Illuminate\Database\Eloquent\Model;
7
use App\Exceptions\UserHasAlreadyAnInviteInGroupException;
8
9
class Invitation extends Model
10
{
11
    /**
12
     * Get the student of this invitation.
13
     *
14
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
15
     */
16
    public function student()
17
    {
18
        return $this->belongsTo(Student::class);
19
    }
20
21
    /**
22
     * Get the group of this invitation.
23
     *
24
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
25
     */
26
    public function group()
27
    {
28
        return $this->belongsTo(Group::class);
29
    }
30
31
    /**
32
     * Scope a query to get the student amount of invitations in a given course.
33
     *
34
     * @param \Illuminate\Database\Eloquent\Builder $query
35
     * @param string                                $studentNumber
36
     * @param int                                   $courseId
37
     *
38
     * @return \Illuminate\Database\Eloquent\Builder
39
     */
40
    public function scopeOfStudentInCourse($query, $studentNumber, $courseId)
41
    {
42
        return $query->where([
43
            ['course_id', '=', $courseId],
44
            ['student_number', '=', $studentNumber],
45
            ]);
46
    }
47
48
    /**
49
     * Saves new invitation.
50
     *
51
     * @param $studentNumber
52
     * @param $groupId
53
     * @param $courseId
54
     *
55
     * @throws \App\Exceptions\UserHasAlreadyAnInviteInGroupException
56
     *
57
     * @return invitation
58
     */
59
    public static function create($studentNumber, $groupId, $courseId)
60
    {
61
        $exception = DB::transaction(function () use ($studentNumber, $groupId) {
62
            $findAnyInvitation = self::where([
63
                    ['student_number', $studentNumber],
64
                    ['group_id', $groupId],
65
                ]);
66
67
            if ($findAnyInvitation->exists()) {
68
                return new UserHasAlreadyAnInviteInGroupException(Group::find($groupId));
69
            }
70
        });
71
72
        if ($exception) {
73
            throw $exception;
74
        }
75
76
        $invitation = new self();
77
        $invitation->student_number = $studentNumber;
78
        $invitation->group_id = $groupId;
79
        $invitation->course_id = $courseId;
80
81
        $invitation->save();
82
83
        return $invitation;
84
    }
85
}
86