Passed
Push — feature/job-builder/step-0 ( d77267 )
by Yonathan
10:26
created

JobController::fillAndSaveJobPosterCriteria()   C

Complexity

Conditions 12
Paths 10

Size

Total Lines 35
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 58.1223

Importance

Changes 0
Metric Value
eloc 18
dl 0
loc 35
ccs 6
cts 19
cp 0.3158
rs 6.9666
c 0
b 0
f 0
cc 12
nc 10
nop 2
crap 58.1223

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace App\Http\Controllers;
4
5
use Illuminate\Support\Facades\Lang;
6
use Illuminate\Support\Facades\Auth;
7
use Illuminate\Support\Facades\Log;
8
use Illuminate\Support\Facades\Mail;
9
use Illuminate\Http\RedirectResponse;
10
use Illuminate\Http\Request;
11
use Illuminate\Http\Response;
12
use Illuminate\View\View;
13
use App\Http\Controllers\Controller;
14
15
use Carbon\Carbon;
16
17
use App\Mail\JobPosterReviewRequested;
18
19
use App\Models\Criteria;
20
use App\Models\JobPoster;
21
use App\Models\JobPosterKeyTask;
22
use App\Models\JobPosterQuestion;
23
use App\Models\Lookup\JobTerm;
24
use App\Models\Lookup\Province;
25
use App\Models\Lookup\SecurityClearance;
26
use App\Models\Lookup\LanguageRequirement;
27
use App\Models\Lookup\Department;
28
use App\Models\Lookup\SkillLevel;
29
use App\Models\Lookup\CriteriaType;
30
use App\Models\Skill;
31
use App\Models\Manager;
32
33
use App\Services\Validation\JobPosterValidator;
34
use Jenssegers\Date\Date;
35
use App\Models\AssessmentPlanNotification;
36
use App\Models\Assessment;
37
38
class JobController extends Controller
39
{
40
    /**
41
     * Display a listing of JobPosters.
42
     *
43
     * @return \Illuminate\View\View|\Illuminate\Contracts\View\Factory
44
     */
45
    public function index()
46
    {
47
        $now = Carbon::now();
48
49
        // Find published jobs that are currently open for applications.
50
        // Eager load required relationships: Department, Province, JobTerm.
51
        // Eager load the count of submitted applications, to prevent the relationship
52
        // from being actually loaded and firing off events.
53
        $jobs = JobPoster::where('open_date_time', '<=', $now)
54
            ->where('close_date_time', '>=', $now)
55
            ->where('published', true)
56
            ->with([
57
                'department',
58
                'province',
59
                'job_term',
60
            ])
61
            ->withCount([
62
                'submitted_applications',
63
            ])
64
            ->get();
65
        return view('applicant/job_index', [
66
            'job_index' => Lang::get('applicant/job_index'),
67
            'jobs' => $jobs
68
        ]);
69
    }
70
71
    /**
72
     * Display a listing of a manager's JobPosters.
73
     *
74
     * @return \Illuminate\View\View|\Illuminate\Contracts\View\Factory
75
     */
76 1
    public function managerIndex()
77
    {
78 1
        $manager = Auth::user()->manager;
0 ignored issues
show
Bug introduced by
Accessing manager on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
79 1
        $jobs = JobPoster::where('manager_id', $manager->id)
80 1
            ->withCount('submitted_applications')
81 1
            ->get();
82
83 1
        return view('manager/job_index', [
84
            /*Localization Strings*/
85 1
            'jobs_l10n' => Lang::get('manager/job_index'),
86
87
            /* Data */
88 1
            'jobs' => $jobs,
89
        ]);
90
    }
91
92
    /**
93
     * Submit the Job Poster for review.
94
     *
95
     * @param \Illuminate\Http\Request $request   Incoming request object.
96
     * @param \App\Models\JobPoster    $jobPoster Job Poster object.
97
     *
98
     * @return \Illuminate\View\View|\Illuminate\Contracts\View\Factory
99
     */
100 1
    public function submitForReview(Request $request, JobPoster $jobPoster)
101
    {
102
        // Update review request timestamp
103 1
        $jobPoster->review_requested_at = new Date();
104 1
        $jobPoster->save();
105
106
        // Refresh model instance with updated DB values.
107 1
        $jobPoster = JobPoster::withCount('submitted_applications')->where('id', $jobPoster->id)->first();
108
109
        // Send email
110 1
        $reviewer_email = config('mail.reviewer_email');
111 1
        if (isset($reviewer_email)) {
112 1
            Mail::to($reviewer_email)->send(new JobPosterReviewRequested($jobPoster, Auth::user()));
0 ignored issues
show
Bug introduced by
It seems like Illuminate\Support\Facades\Auth::user() can also be of type null; however, parameter $manager of App\Mail\JobPosterReviewRequested::__construct() does only seem to accept App\Models\User, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

112
            Mail::to($reviewer_email)->send(new JobPosterReviewRequested($jobPoster, /** @scrutinizer ignore-type */ Auth::user()));
Loading history...
113
        } else {
114
            Log::error('The reviewer email environment variable is not set.');
115
        }
116
117 1
        return view('manager/job_index/job', [
118
            /*Localization Strings*/
119 1
            'jobs_l10n' => Lang::get('manager/job_index'),
120 1
            'job' => $jobPoster
121
        ]);
122
    }
123
124
    /**
125
     * Delete a draft Job Poster.
126
     *
127
     * @param \Illuminate\Http\Request $request   Incoming request object.
128
     * @param \App\Models\JobPoster    $jobPoster Job Poster object.
129
     *
130
     * @return void
131
     */
132
    public function destroy(Request $request, JobPoster $jobPoster) : void
133
    {
134
        $jobPoster->delete();
135
    }
136
137
    /**
138
     * Display the specified job poster.
139
     *
140
     * @param \Illuminate\Http\Request $request   Incoming request object.
141
     * @param \App\Models\JobPoster    $jobPoster Job Poster object.
142
     *
143
     * @return \Illuminate\View\View|\Illuminate\Contracts\View\Factory
144
     */
145 6
    public function show(Request $request, JobPoster $jobPoster)
146
    {
147 6
        $jobPoster->load([
148 6
            'department',
149
            'criteria.skill.skill_type',
150
            'manager.team_culture',
151
            'manager.work_environment'
152
        ]);
153
154 6
        $user = Auth::user();
0 ignored issues
show
Unused Code introduced by
The assignment to $user is dead and can be removed.
Loading history...
155
156
        //TODO: Improve workplace photos, and reference them in template direction from WorkEnvironment model
157 6
        $workplacePhotos = [];
158 6
        foreach ($jobPoster->manager->work_environment->workplace_photo_captions as $photoCaption) {
159
            $workplacePhotos[] = [
160
                'description' => $photoCaption->description,
161
                'url' => '/images/user.png'
162
            ];
163
        }
164
165
        //TODO: replace route('manager.show',manager.id) in templates with link using slug
166
167
        $criteria = [
168 6
            'essential' => $jobPoster->criteria->filter(
169
                function ($value, $key) {
170 2
                    return $value->criteria_type->name == 'essential';
171 6
                }
172
            ),
173 6
            'asset' => $jobPoster->criteria->filter(
174
                function ($value, $key) {
175 2
                    return $value->criteria_type->name == 'asset';
176 6
                }
177
            ),
178
        ];
179
180 6
        $jobLang = Lang::get('applicant/job_post');
181
182 6
        $applyButton = [];
183 6
        if (!$jobPoster->published && $this->authorize('update', $jobPoster)) {
184
            $applyButton = [
185 4
                'href' => route('manager.jobs.edit', $jobPoster->id),
186 4
                'title' => $jobLang['apply']['edit_link_title'],
187 4
                'text' => $jobLang['apply']['edit_link_label'],
188
            ];
189 2
        } elseif (Auth::check() && $jobPoster->isOpen()) {
190
            $applyButton = [
191 1
                'href' => route('job.application.edit.1', $jobPoster->id),
192 1
                'title' => $jobLang['apply']['apply_link_title'],
193 1
                'text' => $jobLang['apply']['apply_link_label'],
194
            ];
195 1
        } elseif (Auth::guest() && $jobPoster->isOpen()) {
196
            $applyButton = [
197 1
                'href' => route('job.application.edit.1', $jobPoster->id),
198 1
                'title' => $jobLang['apply']['login_link_title'],
199 1
                'text' => $jobLang['apply']['login_link_label'],
200
            ];
201
        } else {
202
            $applyButton = [
203
                'href' => null,
204
                'title' => null,
205
                'text' => $jobLang['apply']['job_closed_label'],
206
            ];
207
        }
208
209 6
        return view(
210 6
            'applicant/job_post',
211
            [
212 6
                'job_post' => $jobLang,
213 6
                'manager' => $jobPoster->manager,
214 6
                'manager_profile_photo_url' => '/images/user.png', //TODO get real photo
215 6
                'team_culture' => $jobPoster->manager->team_culture,
216 6
                'work_environment' => $jobPoster->manager->work_environment,
217 6
                'workplace_photos' => $workplacePhotos,
218 6
                'job' => $jobPoster,
219 6
                'criteria' => $criteria,
220 6
                'apply_button' => $applyButton,
221 6
                'skill_template' => Lang::get('common/skills'),
222
            ]
223
        );
224
    }
225
226
    /**
227
     * Create a blank job poster for the specified manager
228
     *
229
     * @param Manager $manager Incoming Manager object.
230
     *
231
     * @return \Illuminate\View\View|\Illuminate\Contracts\View\Factory Job Create view
232
     */
233 2
    public function createAsManager(Manager $manager)
234
    {
235 2
        $jobPoster = new JobPoster();
236 2
        $jobPoster->manager_id = $manager->id;
237
238 2
        $jobPoster->save();
239
240 2
        $defaultQuestions = $this->populateDefaultQuestions();
241 2
        if (!empty($defaultQuestions)) {
242 2
            $jobPoster->job_poster_questions()->saveMany($defaultQuestions);
243
        }
244
245 2
        return redirect()->route('manager.jobs.edit', $jobPoster->id);
1 ignored issue
show
Bug Best Practice introduced by
The expression return redirect()->route....edit', $jobPoster->id) returns the type Illuminate\Http\RedirectResponse which is incompatible with the documented return type Illuminate\Contracts\Vie...ry|Illuminate\View\View.
Loading history...
246
    }
247
248
    /**
249
     * Display the form for creating a new Job Poster
250
     *
251
     * @param \Illuminate\Http\Request $request Incoming request object.
252
     *
253
     * @return \Illuminate\View\View|\Illuminate\Contracts\View\Factory Job Create view
254
     */
255
    public function create(Request $request)
256
    {
257
        return $this->populateCreateView($request);
258
    }
259
260
    /**
261
     * Display the form for editing an existing Job Poster
262
     *
263
     * @param \Illuminate\Http\Request $request   Incoming request object.
264
     * @param \App\Models\JobPoster    $jobPoster Job Poster object.
265
     *
266
     * @return \Illuminate\View\View|\Illuminate\Contracts\View\Factory Job Create view
267
     */
268 1
    public function edit(Request $request, JobPoster $jobPoster)
269
    {
270 1
        return $this->populateCreateView($request, $jobPoster);
271
    }
272
273
    /**
274
     * Get the manager from the request object and check if creating or editing
275
     *
276
     * @param \Illuminate\Http\Request $request   Incoming request object.
277
     * @param \App\Models\JobPoster    $jobPoster Optional Job Poster object.
278
     *
279
     * @return \Illuminate\View\View|\Illuminate\Contracts\View\Factory Job Create view
280
     */
281 1
    public function populateCreateView(Request $request, JobPoster $jobPoster = null)
282
    {
283 1
        if ($jobPoster == null || $jobPoster->manager == null) {
284
            $manager = $request->user() ? $request->user()->manager : null;
285
        } else {
286 1
            $manager = $jobPoster->manager;
287
        }
288
289 1
        if (isset($jobPoster)) {
290 1
            $job = $jobPoster;
291 1
            $route = ['manager.jobs.update', $jobPoster];
292 1
            $jobHeading = 'manager/job_edit';
293
        } else {
294
            $job = [];
295
            $defaultQuestions = $this->populateDefaultQuestions();
296
            if (!empty($defaultQuestions)) {
297
                $job['job_poster_questions'] = $defaultQuestions;
298
            }
299
            $route = ['manager.jobs.store'];
300
            $jobHeading = 'manager/job_create';
301
        }
302
303 1
        $skillLangs = Lang::get('common/skills');
304
305 1
        $softSkills = Skill::whereHas(
306 1
            'skill_type',
307
            function ($query) : void {
308 1
                $query->where('name', '=', 'soft');
309 1
            }
310 1
        )->get()
311 1
            ->mapWithKeys(
312
                function ($skill) {
313
                    return [
314 1
                        $skill->id => $skill->name
315
                    ];
316 1
                }
317
            )
318 1
            ->all();
319
320 1
        $hardSkills = Skill::whereHas(
321 1
            'skill_type',
322
            function ($query) : void {
323 1
                $query->where('name', '=', 'hard');
324 1
            }
325 1
        )->get()
326 1
            ->mapWithKeys(
327
                function ($skill) {
328
                    return [
329 1
                        $skill->id => $skill->name
330
                    ];
331 1
                }
332
            )
333 1
            ->all();
334
335 1
        asort($softSkills, SORT_LOCALE_STRING);
336 1
        asort($hardSkills, SORT_LOCALE_STRING);
337
338
        $skills = [
339
            'essential' => [
340 1
                'hard' => $hardSkills,
341 1
                'soft' => $softSkills
342
            ],
343
            'asset' => [
344 1
                'hard' => $hardSkills,
345 1
                'soft' => $softSkills
346
            ]
347
        ];
348
349 1
        $skillLevelCollection = SkillLevel::all();
350
351 1
        $skillLevels = array();
352
353 1
        $skillLevels['hard'] = $skillLevelCollection->mapWithKeys(
354
            function ($skillLevel) use ($skillLangs) {
355 1
                return [$skillLevel->id => $skillLangs['skill_levels']['hard'][$skillLevel->name]];
356 1
            }
357 1
        )->all();
358
359 1
        $skillLevels['soft'] = $skillLevelCollection->mapWithKeys(
360
            function ($skillLevel) use ($skillLangs) {
361 1
                return [$skillLevel->id => $skillLangs['skill_levels']['soft'][$skillLevel->name]];
362 1
            }
363 1
        )->all();
364
365 1
        return view(
366 1
            'manager/job_create',
367
            [
368
                /*Localization Strings*/
369 1
                'job_l10n' => Lang::get('manager/job_create'),
370
371
                /* Data */
372 1
                'job' => Lang::get($jobHeading),
373 1
                'manager' => $manager,
374 1
                'provinces' => Province::all(),
375 1
                'departments' => Department::all(),
376 1
                'language_requirments' => LanguageRequirement::all(),
377 1
                'security_clearances' => SecurityClearance::all(),
378 1
                'job' => $job,
379 1
                'form_action_url' => route(/** @scrutinizer ignore-type */ ...$route), // phpcs:ignore
0 ignored issues
show
Bug introduced by
$route is expanded, but the parameter $name of route() does not expect variable arguments. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

379
                'form_action_url' => route(/** @scrutinizer ignore-type */ /** @scrutinizer ignore-type */ ...$route), // phpcs:ignore
Loading history...
380 1
                'skills' => $skills,
381 1
                'skill_levels' => $skillLevels,
382 1
                'skill_template' => $skillLangs,
383
            ]
384
        );
385
    }
386
387
    /**
388
     * Create a new resource in storage
389
     *
390
     * @param \Illuminate\Http\Request $request   Incoming request object.
391
     * @param \App\Models\JobPoster    $jobPoster Optional Job Poster object.
392
     *
393
     * @return \Illuminate\Routing\Redirector|\Illuminate\Http\RedirectResponse A redirect to the Job Index
394
     */
395 6
    public function store(Request $request, JobPoster $jobPoster = null)
396
    {
397
        // Don't allow edits for published Job Posters
398
        // Also check auth while we're at it
399 6
        if (isset($jobPoster)) {
400 6
            $this->authorize('update', $jobPoster);
401 6
            JobPosterValidator::validateUnpublished($jobPoster);
402
        } else {
403
            $this->authorize('create', JobPoster::class);
404
        }
405
406 6
        $input = $request->input();
407
408 6
        $job = (isset($jobPoster) ? $jobPoster : new JobPoster());
409
410 6
        if ($job->manager_id == null) {
411
            $job->manager_id = $request->user()->manager->id;
412
            $job->save();
413
        }
414
415 6
        $this->fillAndSaveJobPoster($input, $job);
416
417 6
        $this->fillAndSaveJobPosterTasks($input, $job, isset($jobPoster));
418
419 6
        $this->fillAndSaveJobPosterQuestions($input, $job, isset($jobPoster));
420
421 6
        $this->fillAndSaveJobPosterCriteria($input, $job, isset($jobPoster));
0 ignored issues
show
Unused Code introduced by
The call to App\Http\Controllers\Job...SaveJobPosterCriteria() has too many arguments starting with IssetNode. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

421
        $this->/** @scrutinizer ignore-call */ 
422
               fillAndSaveJobPosterCriteria($input, $job, isset($jobPoster));

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
422
423 6
        return redirect(route('manager.jobs.show', $job->id));
424
    }
425
426
    /**
427
     * Fill Job Poster model's properties and save
428
     *
429
     * @param mixed[]               $input     Field values.
430
     * @param \App\Models\JobPoster $jobPoster Job Poster object.
431
     *
432
     * @return void
433
     */
434 6
    protected function fillAndSaveJobPoster(array $input, JobPoster $jobPoster) : void
435
    {
436 6
        $jobPoster->fill(
437
            [
438 6
                'job_term_id' => JobTerm::where('name', 'month')->firstOrFail()->id,
439 6
                'term_qty' => $input['term_qty'],
440 6
                'open_date_time' => ptDayStartToUtcTime($input['open_date']),
441 6
                'close_date_time' => ptDayEndToUtcTime($input['close_date']),
442 6
                'start_date_time' => ptDayStartToUtcTime($input['start_date']),
443 6
                'department_id' => $input['department'],
444 6
                'province_id' => $input['province'],
445 6
                'salary_min' => $input['salary_min'],
446 6
                'salary_max' => $input['salary_max'],
447 6
                'noc' => $input['noc'],
448 6
                'classification' => $input['classification'],
449 6
                'security_clearance_id' => $input['security_clearance'],
450 6
                'language_requirement_id' => $input['language_requirement'],
451 6
                'remote_work_allowed' => (isset($input['remote_work_allowed']) ? $input['remote_work_allowed'] : false),
452
                'en' => [
453 6
                    'city' => $input['city'],
454 6
                    'title' => $input['title']['en'],
455 6
                    'impact' => $input['impact']['en'],
456 6
                    'branch' => $input['branch']['en'],
457 6
                    'division' => $input['division']['en'],
458 6
                    'education' => $input['education']['en'],
459
                ],
460
                'fr' => [
461 6
                    'city' => $input['city'],
462 6
                    'title' => $input['title']['fr'],
463 6
                    'impact' => $input['impact']['fr'],
464 6
                    'branch' => $input['branch']['fr'],
465 6
                    'division' => $input['division']['fr'],
466 6
                    'education' => $input['education']['fr'],
467
                ],
468
            ]
469
        );
470 6
        $jobPoster->save();
471 6
    }
472
473
    /**
474
     * Fill Job Poster's tasks and save
475
     *
476
     * @param mixed[]               $input     Field values.
477
     * @param \App\Models\JobPoster $jobPoster Job Poster object.
478
     * @param boolean               $replace   Remove existing relationships.
479
     *
480
     * @return void
481
     */
482 6
    protected function fillAndSaveJobPosterTasks(array $input, JobPoster $jobPoster, bool $replace) : void
483
    {
484 6
        if ($replace) {
485 6
            $jobPoster->job_poster_key_tasks()->delete();
486
        }
487
488 6
        if (!array_key_exists('task', $input) || !is_array($input['task'])) {
489 6
            return;
490
        }
491
492
        foreach ($input['task'] as $task) {
493
            $jobPosterTask = new JobPosterKeyTask();
494
            $jobPosterTask->job_poster_id = $jobPoster->id;
495
            $jobPosterTask->fill(
496
                [
497
                    'en' => [
498
                        'description' => $task['en']
499
                    ],
500
                    'fr' => [
501
                        'description' => $task['fr']
502
                    ]
503
                ]
504
            );
505
            $jobPosterTask->save();
506
        }
507
    }
508
509
    /**
510
     * Fill Job Poster's questions and save
511
     *
512
     * @param mixed[]               $input     Field values.
513
     * @param \App\Models\JobPoster $jobPoster Job Poster object.
514
     * @param boolean               $replace   Remove existing relationships.
515
     *
516
     * @return void
517
     */
518 6
    protected function fillAndSaveJobPosterQuestions(array $input, JobPoster $jobPoster, bool $replace) : void
519
    {
520 6
        if ($replace) {
521 6
            $jobPoster->job_poster_questions()->delete();
522
        }
523
524 6
        if (!array_key_exists('question', $input) || !is_array($input['question'])) {
525 6
            return;
526
        }
527
528
        foreach ($input['question'] as $question) {
529
            $jobQuestion = new JobPosterQuestion();
530
            $jobQuestion->job_poster_id = $jobPoster->id;
531
            $jobQuestion->fill(
532
                [
533
                    'en' => [
534
                        'question' => $question['question']['en'],
535
                        'description' => $question['description']['en']
536
                    ],
537
                    'fr' => [
538
                        'question' => $question['question']['fr'],
539
                        'description' => $question['description']['fr']
540
                    ]
541
                ]
542
            );
543
            $jobQuestion->save();
544
        }
545
    }
546
547
    /**
548
     * Fill Job Poster's criteria and save
549
     *
550
     * @param mixed[]               $input     Field values.
551
     * @param \App\Models\JobPoster $jobPoster Job Poster object.
552
     *
553
     * @return void
554
     */
555 6
    protected function fillAndSaveJobPosterCriteria(array $input, JobPoster $jobPoster) : void
556
    {
557 6
        $affectedCriteriaIds = [];
558
559 6
        if (array_key_exists('criteria', $input) && !is_array($input['criteria'])) {
560
            $criteria = $input['criteria'];
561
562
            // Old criteria must be updated, using the criteriaId that comes from the form element names.
563
            if (!empty($criteria['old'])) {
564
                foreach ($criteria['old'] as $criteriaType => $criteriaTypeInput) {
565
                    foreach ($criteriaTypeInput as $skillTypeInput) {
566
                        foreach ($skillTypeInput as $criteriaId => $criteriaInput) {
567
                            $updatedCriteria = $this->processCriteriaForm($jobPoster, $criteriaType, $criteriaInput, $criteriaId);
568
                            $affectedCriteriaIds[] = $updatedCriteria->id;
569
                        }
570
                    }
571
                }
572
            }
573
            // New criteria must be created from scratch, and the id in the form element name can be disregarded.
574
            if (!empty($criteria['new'])) {
575
                foreach ($criteria['new'] as $criteriaType => $criteriaTypeInput) {
576
                    foreach ($criteriaTypeInput as $skillTypeInput) {
577
                        foreach ($skillTypeInput as $criteriaInput) {
578
                            $newCriteria = $this->processCriteriaForm($jobPoster, $criteriaType, $criteriaInput, null);
579
                            $affectedCriteriaIds[] = $newCriteria->id;
580
                        }
581
                    }
582
                }
583
            }
584
        }
585
586
        // Existing criteria which were not resubmitted must be deleted.
587 6
        $deleteCriteria = $jobPoster->criteria()->whereNotIn('id', $affectedCriteriaIds)->get();
588 6
        foreach ($deleteCriteria as $criteria) {
589 6
            $this->deleteCriteria($criteria);
590
        }
591 6
    }
592
593
    /**
594
     * Process intput representing a single criteria from Job Poster form.
595
     *
596
     * @param JobPoster    $jobPoster
1 ignored issue
show
Coding Style Documentation introduced by
Missing parameter comment
Loading history...
597
     * @param string       $criteriaType
1 ignored issue
show
Coding Style Documentation introduced by
Missing parameter comment
Loading history...
598
     * @param array        $criteriaInput
1 ignored issue
show
introduced by
@param annotation of method \App\Http\Controllers\JobController::processCriteriaForm() does not specify type hint for items of its traversable parameter $criteriaInput.
Loading history...
Coding Style Documentation introduced by
Missing parameter comment
Loading history...
599
     * @param integer|null $criteriaId
1 ignored issue
show
Coding Style Documentation introduced by
Missing parameter comment
Loading history...
600
     * @return Criteria
601
     */
602
    protected function processCriteriaForm(JobPoster $jobPoster, string $criteriaType, array $criteriaInput, ?int $criteriaId): Criteria
603
    {
604
        $skillId = $criteriaInput['skill_id'];
605
606
        //If no description was provided, use the default skill description
607
        $descriptionEn = $criteriaInput['description']['en'] ?
608
            $criteriaInput['description']['en'] : Skill::find($skillId)->getTranslation('description', 'en');
609
        $descriptionFr = $criteriaInput['description']['fr'] ?
610
            $criteriaInput['description']['fr'] : Skill::find($criteriaInput['skill_id'])->getTranslation('description', 'fr');
611
        $data = [
612
            'skill_id' => $criteriaInput['skill_id'],
613
            'criteria_type_id' => CriteriaType::where('name', $criteriaType)->firstOrFail()->id,
614
            'skill_level_id' => $criteriaInput['skill_level_id'],
615
            'en' => [
616
                'description' => $descriptionEn,
617
            ],
618
            'fr' => [
619
                'description' => $descriptionFr,
620
            ],
621
        ];
622
623
        if ($criteriaId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $criteriaId of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
624
            $existingCriteria = Criteria::find($criteriaId);
625
            $this->updateCriteria($existingCriteria, $data);
626
            return $existingCriteria;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $existingCriteria could return the type null which is incompatible with the type-hinted return App\Models\Criteria. Consider adding an additional type-check to rule them out.
Loading history...
627
        } else {
628
            $newCriteria = $this->createCriteria($jobPoster, $skillId, $data);
629
            return $newCriteria;
630
        }
631
    }
632
633
    /**
634
     * Create a Job Criteria
635
     *
636
     * @param JobPoster $jobPoster
1 ignored issue
show
Coding Style Documentation introduced by
Missing parameter comment
Loading history...
637
     * @param integer   $skillId
1 ignored issue
show
Coding Style Documentation introduced by
Missing parameter comment
Loading history...
638
     * @param array     $data
1 ignored issue
show
introduced by
@param annotation of method \App\Http\Controllers\JobController::createCriteria() does not specify type hint for items of its traversable parameter $data.
Loading history...
Coding Style Documentation introduced by
Missing parameter comment
Loading history...
639
     * @return Criteria
640
     */
641
    protected function createCriteria(JobPoster $jobPoster, int $skillId, array $data): Criteria
642
    {
643
        $criteria = new Criteria();
644
        $criteria->job_poster_id = $jobPoster->id;
645
        $criteria->skill_id = $skillId;
646
        $criteria->fill($data);
647
        $criteria->save();
648
649
        $notification = $this->makeAssessmentPlanNotification(
650
            'CREATE',
651
            $criteria
652
        );
653
        $notification->save();
654
655
        return $criteria;
656
    }
657
658
    /**
659
     * Update an existing Job Criteria
660
     *
661
     * @param Criteria $criteria
1 ignored issue
show
Coding Style Documentation introduced by
Missing parameter comment
Loading history...
662
     * @param array    $data
1 ignored issue
show
introduced by
@param annotation of method \App\Http\Controllers\JobController::updateCriteria() does not specify type hint for items of its traversable parameter $data.
Loading history...
Coding Style Documentation introduced by
Missing parameter comment
Loading history...
663
     * @return void
664
     */
665
    protected function updateCriteria(Criteria $criteria, array $data): void
666
    {
667
        if ($criteria->skill_level_id != $data['skill_level_id'] ||
668
        $criteria->skill_id != $data['skill_id']) {
669
            $notification = $this->makeAssessmentPlanNotification(
670
                'UPDATE',
671
                $criteria,
672
                $data['skill_id'],
673
                $data['skill_level_id']
674
            );
675
            $notification->save();
676
        }
677
        $criteria->fill($data);
678
        $criteria->save();
679
    }
680
681
    /**
682
     * Delete existing Job Criteria
683
     *
684
     * @param Criteria $criteria
1 ignored issue
show
Coding Style Documentation introduced by
Missing parameter comment
Loading history...
685
     * @return void
686
     */
687 6
    protected function deleteCriteria(Criteria $criteria): void
688
    {
689 6
        $notification = $notification = $this->makeAssessmentPlanNotification(
0 ignored issues
show
Unused Code introduced by
The assignment to $notification is dead and can be removed.
Loading history...
690 6
            'DELETE',
691 6
            $criteria
692
        );
693 6
        $notification->save();
694
695
        // Delete assessments related to this criteria
696 6
        Assessment::where("criterion_id", $criteria->id)->delete();
697 6
        $criteria->delete();
698 6
    }
699
700
    /**
701
     * Create a new AssessmentPlanNotification for a modification to a Criteria
702
     *
703
     * @param string       $type            Can be CREATE, UPDATE or DELETE.
704
     * @param Criteria     $criteria
1 ignored issue
show
Coding Style Documentation introduced by
Missing parameter comment
Loading history...
705
     * @param integer|null $newSkillId      Only used for UPDATE type notifications.
706
     * @param integer|null $newSkillLevelId Only used for UPDATE type notifications.
707
     * @return AssessmentPlanNotification
708
     */
709 6
    protected function makeAssessmentPlanNotification(string $type, Criteria $criteria, $newSkillId = null, $newSkillLevelId = null): AssessmentPlanNotification
0 ignored issues
show
introduced by
Method \App\Http\Controllers\JobController::makeAssessmentPlanNotification() does not have parameter type hint for its parameter $newSkillId but it should be possible to add it based on @param annotation "integer|null".
Loading history...
introduced by
Method \App\Http\Controllers\JobController::makeAssessmentPlanNotification() does not have parameter type hint for its parameter $newSkillLevelId but it should be possible to add it based on @param annotation "integer|null".
Loading history...
710
    {
711 6
        $notification = new AssessmentPlanNotification();
712 6
        $notification->job_poster_id = $criteria->job_poster_id;
713 6
        $notification->type = $type;
714 6
        $notification->criteria_id = $criteria->id;
715 6
        $notification->skill_id = $criteria->skill_id;
716 6
        $notification->criteria_type_id = $criteria->criteria_type_id;
717 6
        $notification->skill_level_id = $criteria->skill_level_id;
718 6
        $notification->skill_id_new = $newSkillId;
719 6
        $notification->skill_level_id_new = $newSkillLevelId;
720 6
        $notification->acknowledged = false;
721 6
        return $notification;
722
    }
723
724
    /**
725
     * Get the localized default questions and add them to an array.
726
     *
727
     * @return mixed[]|void
728
     */
729 2
    protected function populateDefaultQuestions()
730
    {
731
        $defaultQuestions = [
732 2
            'en' => array_values(Lang::get('manager/job_create', [], 'en')['questions']),
733 2
            'fr' => array_values(Lang::get('manager/job_create', [], 'fr')['questions']),
734
        ];
735
736 2
        if (count($defaultQuestions['en']) !== count($defaultQuestions['fr'])) {
737
            Log::warning('There must be the same number of French and English default questions for a Job Poster.');
738
            return;
739
        }
740
741 2
        $jobQuestions = [];
742
743 2
        for ($i = 0; $i < count($defaultQuestions['en']); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
744 2
            $jobQuestion = new JobPosterQuestion();
745 2
            $jobQuestion->fill(
746
                [
747
                    'en' => [
748 2
                        'question' => $defaultQuestions['en'][$i],
749
                    ],
750
                    'fr' => [
751 2
                        'question' => $defaultQuestions['fr'][$i],
752
                    ]
753
                ]
754
            );
755 2
            $jobQuestions[] = $jobQuestion;
756
        }
757
758 2
        return $jobQuestions;
759
    }
760
}
761