Passed
Push — master ( cd2cd2...6fd81b )
by Tristan
25:03 queued 13:24
created

CriteriaController::batchUpdate()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 37
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 22
c 1
b 0
f 0
dl 0
loc 37
rs 8.9457
cc 6
nc 9
nop 2
1
<?php
2
3
namespace App\Http\Controllers\Api;
4
5
use App\Http\Controllers\Controller;
6
use App\Models\Criteria;
7
use App\Models\JobPoster;
8
use App\Models\AssessmentPlanNotification;
9
use App\Models\Assessment;
10
use Illuminate\Http\Request;
11
12
class CriteriaController extends Controller
13
{
14
/**
15
     * Converts a Criteria to the shape sent and recieved by the api.
16
     *
17
     * @param Criteria $model
1 ignored issue
show
Coding Style Documentation introduced by
Missing parameter comment
Loading history...
18
     * @return void
1 ignored issue
show
Coding Style introduced by
Function return type is void, but function contains return statement
Loading history...
19
     */
20
    public function toApiArray(Criteria $model)
21
    {
22
        return array_merge($model->toArray(), $model->getTranslationsArray());
23
    }
24
25
    /**
26
     * Get the set of criteria associated with a Job.
27
     *
28
     * @param JobPoster $jobPoster
1 ignored issue
show
Coding Style Documentation introduced by
Missing parameter comment
Loading history...
29
     * @return \Illuminate\Http\Response
30
     */
31
    public function indexByJob(JobPoster $jobPoster)
32
    {
33
        $toApiArray = array($this, 'toApiArray');
34
        $criteriaAray = Criteria::where('job_poster_id', $jobPoster->id)->get()->map($toApiArray);
35
        return response()->json($criteriaAray);
36
    }
37
38
    /**
39
     * Update the set of criteria associated with a Job.
40
     *
41
     * @param Request $request
2 ignored issues
show
Coding Style Documentation introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 3 spaces after parameter type; 1 found
Loading history...
42
     * @param JobPoster $jobPoster
1 ignored issue
show
Coding Style Documentation introduced by
Missing parameter comment
Loading history...
43
     * @return \Illuminate\Http\Response
44
     */
45
    public function batchUpdate(Request $request, JobPoster $jobPoster)
46
    {
47
        $toApiArray = array($this, 'toApiArray');
48
49
        $newCriteria = collect($request->input()); // TODO: switch to validated
50
        $oldCriteria = $jobPoster->criteria;
51
52
        $updatedIds = [];
53
54
        // First, delete old criteria that weren't resubmitted, and update those that were
55
        foreach ($oldCriteria as $criteria) {
56
            $newData = $newCriteria->firstWhere('id', $criteria['id']);
57
            if ($newData) {
58
                $updatedIds[] = $criteria->id;
59
                $this->updateCriteria($criteria, $newData);
60
            } else {
61
                $this->deleteCriteria($criteria);
62
            }
63
        }
64
65
        $isUnsaved = function ($criteria, $savedIds): bool {
66
            return !array_key_exists('id', $criteria) || !in_array($criteria['id'], $savedIds);
67
        };
68
69
        // Now, save any new criteria that remain
70
        foreach ($newCriteria as $criteriaData) {
71
            if ($isUnsaved($criteriaData, $updatedIds)) {
72
                $criteria = new Criteria();
73
                $criteria->job_poster_id = $jobPoster->id;
74
                $fillableData = collect($criteriaData)->except(['id', 'job_poster_id'])->toArray();
75
                $criteria->fill($fillableData);
76
                $this->createCriteria($criteria);
77
            }
78
        }
79
80
        $criteriaAray = Criteria::where('job_poster_id', $jobPoster->id)->get()->map($toApiArray);
81
        return response()->json($criteriaAray);
82
    }
83
84
    /**
85
     * Save a new criteria and create a notification.
86
     *
87
     * @param Criteria $criteria
1 ignored issue
show
Coding Style Documentation introduced by
Missing parameter comment
Loading history...
88
     * @return void
1 ignored issue
show
Coding Style introduced by
Function return type is void, but function contains return statement
Loading history...
89
     */
90
    protected function createCriteria(Criteria $criteria)
91
    {
92
        $criteria->save();
93
94
        $notification = $this->makeAssessmentPlanNotification(
95
            'CREATE',
96
            $criteria
97
        );
98
        $notification->save();
99
100
        return $criteria;
101
    }
102
103
    /**
104
     * Update an existing Job Criteria and create a notification if necessary.
105
     *
106
     * @param  \App\Models\Criteria $oldCriteria Existing Critera.
107
     * @param  mixed[] $newData Updated version of the Critera.
2 ignored issues
show
Coding Style introduced by
Expected 14 spaces after parameter type; 1 found
Loading history...
Coding Style introduced by
Expected 5 spaces after parameter name; 1 found
Loading history...
108
     * @return void
109
     */
110
    protected function updateCriteria(Criteria $oldCriteria, $newData): void
1 ignored issue
show
Coding Style introduced by
Type hint "array" missing for $newData
Loading history...
111
    {
112
        // We only need to create a notification when the non-descriptive fields change
113
        if ($oldCriteria->skill_level_id != $newData['skill_level_id']
114
            || $oldCriteria->skill_id != $newData['skill_id']
115
        ) {
116
            $notification = $this->makeAssessmentPlanNotification(
117
                'UPDATE',
118
                $oldCriteria,
119
                $newData['skill_id'],
120
                $newData['skill_level_id'],
121
                $newData['criteria_type_id']
122
            );
123
            $notification->save();
124
        }
125
        // Get just the data that can be changed
126
        $fillableData = collect($newData)->except(['id', 'job_poster_id'])->toArray();
127
        $oldCriteria->fill($fillableData);
128
        $oldCriteria->save();
129
    }
130
131
    /**
132
     * Delete existing Job Criteria and create a notification.
133
     *
134
     * @param  \App\Models\Criteria $criteria Incoming Criteria.
135
     * @return void
136
     */
137
    protected function deleteCriteria(Criteria $criteria): void
138
    {
139
        $notification = $notification = $this->makeAssessmentPlanNotification(
0 ignored issues
show
Unused Code introduced by
The assignment to $notification is dead and can be removed.
Loading history...
140
            'DELETE',
141
            $criteria
142
        );
143
        $notification->save();
144
145
        // Delete assessments related to this criteria.
146
        Assessment::where('criterion_id', $criteria->id)->delete();
147
        $criteria->delete();
148
    }
149
150
    /**
151
     * Create a new AssessmentPlanNotification for a modification to a Criteria
152
     *
153
     * @param  string               $type            Can be CREATE, UPDATE or DELETE.
1 ignored issue
show
Coding Style introduced by
Expected 14 spaces after parameter name; 12 found
Loading history...
154
     * @param  \App\Models\Criteria $criteria        The Criteria (the OLD criteria if updating or deleting)
2 ignored issues
show
Coding Style introduced by
Expected 10 spaces after parameter name; 8 found
Loading history...
Coding Style Documentation introduced by
Parameter comment must end with a full stop
Loading history...
155
     * @param  integer|null         $newSkillId      Only used for UPDATE type notifications.
1 ignored issue
show
Coding Style introduced by
Expected 8 spaces after parameter name; 6 found
Loading history...
156
     * @param  integer|null         $newSkillLevelId Only used for UPDATE type notifications.
1 ignored issue
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
157
     * @param  integer|null         $newCriteriaTypeId Only used for UPDATE type notifications.
158
     * @return \App\Models\AssessmentPlanNotification
159
     */
160
    protected function makeAssessmentPlanNotification(
161
        string $type,
162
        Criteria $criteria,
163
        $newSkillId = null,
164
        $newSkillLevelId = null,
165
        $newCriteriaTypeId = null
166
    ) {
167
        $notification = new AssessmentPlanNotification();
168
        $notification->job_poster_id = $criteria->job_poster_id;
169
        $notification->type = $type;
170
        $notification->criteria_id = $criteria->id;
171
        $notification->skill_id = $criteria->skill_id;
172
        $notification->criteria_type_id = $criteria->criteria_type_id;
173
        $notification->skill_level_id = $criteria->skill_level_id;
174
        $notification->skill_id_new = $newSkillId;
175
        $notification->skill_level_id_new = $newSkillLevelId;
176
        $notification->criteria_type_id_new = $newCriteriaTypeId;
177
        $notification->acknowledged = false;
178
        return $notification;
179
    }
180
}
181