Passed
Push — feature/job-builder/criteria-a... ( a8d7d9 )
by Tristan
15:36
created

CriteriaController::indexByJob()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
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 6
    public function toApiArray(Criteria $model)
21
    {
22 6
        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 1
    public function indexByJob(JobPoster $jobPoster)
32
    {
33 1
        $toApiArray = array($this, 'toApiArray');
34 1
        $criteriaAray = Criteria::where('job_poster_id', $jobPoster->id)->get()->map($toApiArray);
35 1
        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 5
    public function batchUpdate(Request $request, JobPoster $jobPoster)
46
    {
47 5
        $toApiArray = array($this, 'toApiArray');
48
49 5
        $newCriteria = collect($request->input()); // TODO: switch to validated
50 5
        $oldCriteria = $jobPoster->criteria;
51
52 5
        $updatedIds = [];
53
54
        // First, delete old criteria that weren't resubmitted, and update those that were
55 5
        foreach ($oldCriteria as $criteria) {
56 3
            $newData = $newCriteria->firstWhere('id', $criteria['id']);
57 3
            if ($newData) {
58 3
                $updatedIds[] = $criteria->id;
59 3
                $this->updateCriteria($criteria, $newData);
60
            } else {
61 2
                $this->deleteCriteria($criteria);
62
            }
63
        }
64
65
        $isUnsaved = function ($criteria, $savedIds): bool {
66 5
            return !array_key_exists('id', $criteria) || !in_array($criteria['id'], $savedIds);
67 5
        };
68
69
        // Now, save any new criteria that remain
70 5
        foreach ($newCriteria as $criteriaData) {
71 5
            if ($isUnsaved($criteriaData, $updatedIds)) {
72 4
                $criteria = new Criteria();
73 4
                $criteria->job_poster_id = $jobPoster->id;
74 4
                $fillableData = collect($criteriaData)->except(['id', 'job_poster_id'])->toArray();
75 4
                $criteria->fill($fillableData);
76 4
                $this->createCriteria($criteria);
77
            }
78
        }
79
80 5
        $criteriaAray = Criteria::where('job_poster_id', $jobPoster->id)->get()->map($toApiArray);
81 5
        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 4
    protected function createCriteria(Criteria $criteria)
91
    {
92 4
        $criteria->save();
93
94 4
        $notification = $this->makeAssessmentPlanNotification(
95 4
            'CREATE',
96 4
            $criteria
97
        );
98 4
        $notification->save();
99
100 4
        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 3
    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 3
        if ($oldCriteria->skill_level_id != $newData['skill_level_id']
114 3
            || $oldCriteria->skill_id != $newData['skill_id']
115
        ) {
116 2
            $notification = $this->makeAssessmentPlanNotification(
117 2
                'UPDATE',
118 2
                $oldCriteria,
119 2
                $newData['skill_id'],
120 2
                $newData['skill_level_id']
121
                // FIXME: Add Criteria Type id
122
            );
123 2
            $notification->save();
124
        }
125
        // Get just the data that can be changed
126 3
        $fillableData = collect($newData)->except(['id', 'job_poster_id'])->toArray();
127 3
        $oldCriteria->fill($fillableData);
128 3
        $oldCriteria->save();
129 3
    }
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 2
    protected function deleteCriteria(Criteria $criteria): void
138
    {
139 2
        $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 2
            'DELETE',
141 2
            $criteria
142
        );
143 2
        $notification->save();
144
145
        // Delete assessments related to this criteria.
146 2
        Assessment::where('criterion_id', $criteria->id)->delete();
147 2
        $criteria->delete();
148 2
    }
149
150
    /**
151
     * Create a new AssessmentPlanNotification for a modification to a Criteria
152
     *
153
     * @param  string               $type            Can be CREATE, UPDATE or DELETE.
154
     * @param  \App\Models\Criteria $criteria        The Criteria (the OLD criteria if updating or deleting)
1 ignored issue
show
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.
156
     * @param  integer|null         $newSkillLevelId Only used for UPDATE type notifications.
157
     * @return \App\Models\AssessmentPlanNotification
158
     */
159 5
    protected function makeAssessmentPlanNotification(string $type, Criteria $criteria, $newSkillId = null, $newSkillLevelId = null)
160
    {
161 5
        $notification = new AssessmentPlanNotification();
162 5
        $notification->job_poster_id = $criteria->job_poster_id;
163 5
        $notification->type = $type;
164 5
        $notification->criteria_id = $criteria->id;
165 5
        $notification->skill_id = $criteria->skill_id;
166 5
        $notification->criteria_type_id = $criteria->criteria_type_id;
167 5
        $notification->skill_level_id = $criteria->skill_level_id;
168 5
        $notification->skill_id_new = $newSkillId;
169 5
        $notification->skill_level_id_new = $newSkillLevelId;
170 5
        $notification->acknowledged = false;
171 5
        return $notification;
172
    }
173
}
174