Passed
Push — task/all-applications-to-pdf ( cb7375...852a46 )
by Tristan
59:34 queued 50:51
created

JobController::get()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 10
ccs 0
cts 7
cp 0
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
crap 6
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
    /**
42
     * Get array representation of specified job poster
43
     *
44
     * @param \Illuminate\Http\Request $request   Incoming request object.
45
     * @param \App\Models\JobPoster    $jobPoster Job Poster object.
46
     *
47
     * @return mixed[]
48
     */
49
    public function get(Request $request, JobPoster $jobPoster)
0 ignored issues
show
introduced by
Method \App\Http\Controllers\JobController::get() does not have return type hint for its return value but it should be possible to add it based on @return annotation "mixed[]".
Loading history...
50
    {
51
        $jobWithTranslations = array_merge($jobPoster->toArray(), $jobPoster->getTranslationsArray());
52
        $criteria = Criteria::where('job_poster_id', $jobPoster->id)->get();
53
        $criteriaTranslated = [];
54
        foreach ($criteria as $criterion) {
55
            // TODO: getTranslationsArray probably makes DB calls every loop. Find a way to profile & optimize.
56
            $criteriaTranslated[] = array_merge($criterion->toArray(), $criterion->getTranslationsArray());
57
        }
58
        return array_merge($jobWithTranslations, ['criteria' => $criteriaTranslated]);
59
    }
60
61
    /**
62
 * Display a listing of JobPosters.
63
     *
64
     * @return \Illuminate\View\View|\Illuminate\Contracts\View\Factory
65
     */
66
    public function index()
67
    {
68
        $now = Carbon::now();
69
70
        // Find published jobs that are currently open for applications.
71
        // Eager load required relationships: Department, Province, JobTerm.
72
        // Eager load the count of submitted applications, to prevent the relationship
73
        // from being actually loaded and firing off events.
74
        $jobs = JobPoster::where('open_date_time', '<=', $now)
75
            ->where('close_date_time', '>=', $now)
76
            ->where('published', true)
77
            ->with([
78
                'department',
79
                'province',
80
                'job_term',
81
            ])
82
            ->withCount([
83
                'submitted_applications',
84
            ])
85
            ->get();
86
        return view('applicant/job_index', [
87
            'job_index' => Lang::get('applicant/job_index'),
88
            'jobs' => $jobs
89
        ]);
90
    }
91
92
    /**
93
     * Display a listing of a manager's JobPosters.
94
     *
95
     * @return \Illuminate\View\View|\Illuminate\Contracts\View\Factory
96
     */
97 1
    public function managerIndex()
98
    {
99 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...
100 1
        $jobs = JobPoster::where('manager_id', $manager->id)
101 1
            ->withCount('submitted_applications')
102 1
            ->get();
103
104 1
        return view('manager/job_index', [
105
            /*Localization Strings*/
106 1
            'jobs_l10n' => Lang::get('manager/job_index'),
107
108
            /* Data */
109 1
            'jobs' => $jobs,
110
        ]);
111
    }
112
113
    /**
114
     * Submit the Job Poster for review.
115
     *
116
     * @param \Illuminate\Http\Request $request   Incoming request object.
117
     * @param \App\Models\JobPoster    $jobPoster Job Poster object.
118
     *
119
     * @return \Illuminate\View\View|\Illuminate\Contracts\View\Factory
120
     */
121 1
    public function submitForReview(Request $request, JobPoster $jobPoster)
122
    {
123
        // Update review request timestamp
124 1
        $jobPoster->review_requested_at = new Date();
125 1
        $jobPoster->save();
126
127
        // Refresh model instance with updated DB values.
128 1
        $jobPoster = JobPoster::withCount('submitted_applications')->where('id', $jobPoster->id)->first();
129
130
        // Send email
131 1
        $reviewer_email = config('mail.reviewer_email');
132 1
        if (isset($reviewer_email)) {
133 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

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

400
                'form_action_url' => route(/** @scrutinizer ignore-type */ /** @scrutinizer ignore-type */ ...$route), // phpcs:ignore
Loading history...
401 1
                'skills' => $skills,
402 1
                'skill_levels' => $skillLevels,
403 1
                'skill_template' => $skillLangs,
404
            ]
405
        );
406
    }
407
408
    /**
409
     * Create a new resource in storage
410
     *
411
     * @param \Illuminate\Http\Request $request   Incoming request object.
412
     * @param \App\Models\JobPoster    $jobPoster Optional Job Poster object.
413
     *
414
     * @return \Illuminate\Routing\Redirector|\Illuminate\Http\RedirectResponse A redirect to the Job Index
415
     */
416 3
    public function store(Request $request, JobPoster $jobPoster = null)
417
    {
418
        // Don't allow edits for published Job Posters
419
        // Also check auth while we're at it
420 3
        if (isset($jobPoster)) {
421 3
            $this->authorize('update', $jobPoster);
422 3
            JobPosterValidator::validateUnpublished($jobPoster);
423
        } else {
424
            $this->authorize('create', JobPoster::class);
425
        }
426
427 3
        $input = $request->input();
428
429 3
        $job = (isset($jobPoster) ? $jobPoster : new JobPoster());
430
431 3
        if ($job->manager_id == null) {
432
            $job->manager_id = $request->user()->manager->id;
433
            $job->save();
434
        }
435
436 3
        $this->fillAndSaveJobPoster($input, $job);
437
438 3
        $this->fillAndSaveJobPosterTasks($input, $job, isset($jobPoster));
439
440 3
        $this->fillAndSaveJobPosterQuestions($input, $job, isset($jobPoster));
441
442 3
        $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

442
        $this->/** @scrutinizer ignore-call */ 
443
               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...
443
444 3
        return redirect(route('manager.jobs.show', $job->id));
445
    }
446
447
    /**
448
     * Fill Job Poster model's properties and save
449
     *
450
     * @param mixed[]               $input     Field values.
451
     * @param \App\Models\JobPoster $jobPoster Job Poster object.
452
     *
453
     * @return void
454
     */
455 3
    protected function fillAndSaveJobPoster(array $input, JobPoster $jobPoster) : void
456
    {
457 3
        $jobPoster->fill(
458
            [
459 3
                'job_term_id' => JobTerm::where('name', 'month')->firstOrFail()->id,
460 3
                'term_qty' => $input['term_qty'],
461 3
                'open_date_time' => ptDayStartToUtcTime($input['open_date']),
462 3
                'close_date_time' => ptDayEndToUtcTime($input['close_date']),
463 3
                'start_date_time' => ptDayStartToUtcTime($input['start_date']),
464 3
                'department_id' => $input['department'],
465 3
                'province_id' => $input['province'],
466 3
                'salary_min' => $input['salary_min'],
467 3
                'salary_max' => $input['salary_max'],
468 3
                'noc' => $input['noc'],
469 3
                'classification' => $input['classification'],
470 3
                'security_clearance_id' => $input['security_clearance'],
471 3
                'language_requirement_id' => $input['language_requirement'],
472 3
                'remote_work_allowed' => (isset($input['remote_work_allowed']) ? $input['remote_work_allowed'] : false),
473
                'en' => [
474 3
                    'city' => $input['city'],
475 3
                    'title' => $input['title']['en'],
476 3
                    'impact' => $input['impact']['en'],
477 3
                    'branch' => $input['branch']['en'],
478 3
                    'division' => $input['division']['en'],
479 3
                    'education' => $input['education']['en'],
480
                ],
481
                'fr' => [
482 3
                    'city' => $input['city'],
483 3
                    'title' => $input['title']['fr'],
484 3
                    'impact' => $input['impact']['fr'],
485 3
                    'branch' => $input['branch']['fr'],
486 3
                    'division' => $input['division']['fr'],
487 3
                    'education' => $input['education']['fr'],
488
                ],
489
            ]
490
        );
491 3
        $jobPoster->save();
492 3
    }
493
494
    /**
495
     * Fill Job Poster's tasks and save
496
     *
497
     * @param mixed[]               $input     Field values.
498
     * @param \App\Models\JobPoster $jobPoster Job Poster object.
499
     * @param boolean               $replace   Remove existing relationships.
500
     *
501
     * @return void
502
     */
503 3
    protected function fillAndSaveJobPosterTasks(array $input, JobPoster $jobPoster, bool $replace) : void
504
    {
505 3
        if ($replace) {
506 3
            $jobPoster->job_poster_key_tasks()->delete();
507
        }
508
509 3
        if (!array_key_exists('task', $input) || !is_array($input['task'])) {
510 3
            return;
511
        }
512
513
        foreach ($input['task'] as $task) {
514
            $jobPosterTask = new JobPosterKeyTask();
515
            $jobPosterTask->job_poster_id = $jobPoster->id;
516
            $jobPosterTask->fill(
517
                [
518
                    'en' => [
519
                        'description' => $task['en']
520
                    ],
521
                    'fr' => [
522
                        'description' => $task['fr']
523
                    ]
524
                ]
525
            );
526
            $jobPosterTask->save();
527
        }
528
    }
529
530
    /**
531
     * Fill Job Poster's questions and save
532
     *
533
     * @param mixed[]               $input     Field values.
534
     * @param \App\Models\JobPoster $jobPoster Job Poster object.
535
     * @param boolean               $replace   Remove existing relationships.
536
     *
537
     * @return void
538
     */
539 3
    protected function fillAndSaveJobPosterQuestions(array $input, JobPoster $jobPoster, bool $replace) : void
540
    {
541 3
        if ($replace) {
542 3
            $jobPoster->job_poster_questions()->delete();
543
        }
544
545 3
        if (!array_key_exists('question', $input) || !is_array($input['question'])) {
546 3
            return;
547
        }
548
549
        foreach ($input['question'] as $question) {
550
            $jobQuestion = new JobPosterQuestion();
551
            $jobQuestion->job_poster_id = $jobPoster->id;
552
            $jobQuestion->fill(
553
                [
554
                    'en' => [
555
                        'question' => $question['question']['en'],
556
                        'description' => $question['description']['en']
557
                    ],
558
                    'fr' => [
559
                        'question' => $question['question']['fr'],
560
                        'description' => $question['description']['fr']
561
                    ]
562
                ]
563
            );
564
            $jobQuestion->save();
565
        }
566
    }
567
568
    /**
569
     * Fill Job Poster's criteria and save
570
     *
571
     * @param mixed[]               $input     Field values.
572
     * @param \App\Models\JobPoster $jobPoster Job Poster object.
573
     *
574
     * @return void
575
     */
576 3
    protected function fillAndSaveJobPosterCriteria(array $input, JobPoster $jobPoster) : void
577
    {
578 3
        if (!array_key_exists('criteria', $input) || !is_array($input['criteria'])) {
579 3
            return;
580
        }
581
582
        $criteria = $input['criteria'];
583
584
        $affectedCriteriaIds = [];
585
        // Old criteria must be updated, using the criteriaId that comes from the form element names.
586
        if (!empty($criteria['old'])) {
587
            foreach ($criteria['old'] as $criteriaType => $criteriaTypeInput) {
588
                foreach ($criteriaTypeInput as $skillTypeInput) {
589
                    foreach ($skillTypeInput as $criteriaId => $criteriaInput) {
590
                        $updatedCriteria = $this->processCriteriaForm($jobPoster, $criteriaType, $criteriaInput, $criteriaId);
591
                        $affectedCriteriaIds[] = $updatedCriteria->id;
592
                    }
593
                }
594
            }
595
        }
596
        // New criteria must be created from scratch, and the id in the form element name can be disregarded.
597
        if (!empty($criteria['new'])) {
598
            foreach ($criteria['new'] as $criteriaType => $criteriaTypeInput) {
599
                foreach ($criteriaTypeInput as $skillTypeInput) {
600
                    foreach ($skillTypeInput as $criteriaInput) {
601
                        $newCriteria = $this->processCriteriaForm($jobPoster, $criteriaType, $criteriaInput, null);
602
                        $affectedCriteriaIds[] = $newCriteria->id;
603
                    }
604
                }
605
            }
606
        }
607
        // Existing criteria which were not resubmitted must be deleted.
608
        $deleteCriteria = $jobPoster->criteria()->whereNotIn('id', $affectedCriteriaIds)->get();
609
        foreach ($deleteCriteria as $criteria) {
610
            $this->deleteCriteria($criteria);
611
        }
612
    }
613
614
    /**
615
     * Process intput representing a single criteria from Job Poster form.
616
     *
617
     * @param JobPoster    $jobPoster
1 ignored issue
show
Coding Style Documentation introduced by
Missing parameter comment
Loading history...
618
     * @param string       $criteriaType
1 ignored issue
show
Coding Style Documentation introduced by
Missing parameter comment
Loading history...
619
     * @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...
620
     * @param integer|null $criteriaId
1 ignored issue
show
Coding Style Documentation introduced by
Missing parameter comment
Loading history...
621
     * @return Criteria
622
     */
623
    protected function processCriteriaForm(JobPoster $jobPoster, string $criteriaType, array $criteriaInput, ?int $criteriaId): Criteria
624
    {
625
        $skillId = $criteriaInput['skill_id'];
626
627
        //If no description was provided, use the default skill description
628
        $descriptionEn = $criteriaInput['description']['en'] ?
629
            $criteriaInput['description']['en'] : Skill::find($skillId)->getTranslation('description', 'en');
630
        $descriptionFr = $criteriaInput['description']['fr'] ?
631
            $criteriaInput['description']['fr'] : Skill::find($criteriaInput['skill_id'])->getTranslation('description', 'fr');
632
        $data = [
633
            'skill_id' => $criteriaInput['skill_id'],
634
            'criteria_type_id' => CriteriaType::where('name', $criteriaType)->firstOrFail()->id,
635
            'skill_level_id' => $criteriaInput['skill_level_id'],
636
            'en' => [
637
                'description' => $descriptionEn,
638
            ],
639
            'fr' => [
640
                'description' => $descriptionFr,
641
            ],
642
        ];
643
644
        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...
645
            $existingCriteria = Criteria::find($criteriaId);
646
            $this->updateCriteria($existingCriteria, $data);
647
            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...
648
        } else {
649
            $newCriteria = $this->createCriteria($jobPoster, $skillId, $data);
650
            return $newCriteria;
651
        }
652
    }
653
654
    /**
655
     * Create a Job Criteria
656
     *
657
     * @param JobPoster $jobPoster
1 ignored issue
show
Coding Style Documentation introduced by
Missing parameter comment
Loading history...
658
     * @param integer   $skillId
1 ignored issue
show
Coding Style Documentation introduced by
Missing parameter comment
Loading history...
659
     * @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...
660
     * @return Criteria
661
     */
662
    protected function createCriteria(JobPoster $jobPoster, int $skillId, array $data): Criteria
663
    {
664
        $criteria = new Criteria();
665
        $criteria->job_poster_id = $jobPoster->id;
666
        $criteria->skill_id = $skillId;
667
        $criteria->fill($data);
668
        $criteria->save();
669
670
        $notification = $this->makeAssessmentPlanNotification(
671
            'CREATE',
672
            $criteria
673
        );
674
        $notification->save();
675
676
        return $criteria;
677
    }
678
679
    /**
680
     * Update an existing Job Criteria
681
     *
682
     * @param Criteria $criteria
1 ignored issue
show
Coding Style Documentation introduced by
Missing parameter comment
Loading history...
683
     * @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...
684
     * @return void
685
     */
686
    protected function updateCriteria(Criteria $criteria, array $data): void
687
    {
688
        if ($criteria->skill_level_id != $data['skill_level_id'] ||
689
        $criteria->skill_id != $data['skill_id']) {
690
            $notification = $this->makeAssessmentPlanNotification(
691
                'UPDATE',
692
                $criteria,
693
                $data['skill_id'],
694
                $data['skill_level_id']
695
            );
696
            $notification->save();
697
        }
698
        $criteria->fill($data);
699
        $criteria->save();
700
    }
701
702
    /**
703
     * Delete existing Job Criteria
704
     *
705
     * @param Criteria $criteria
1 ignored issue
show
Coding Style Documentation introduced by
Missing parameter comment
Loading history...
706
     * @return void
707
     */
708
    protected function deleteCriteria(Criteria $criteria): void
709
    {
710
        $notification = $notification = $this->makeAssessmentPlanNotification(
0 ignored issues
show
Unused Code introduced by
The assignment to $notification is dead and can be removed.
Loading history...
711
            'DELETE',
712
            $criteria
713
        );
714
        $notification->save();
715
716
        // Delete assessments related to this criteria
717
        Assessment::where("criterion_id", $criteria->id)->delete();
718
719
        $criteria->delete();
720
    }
721
722
    /**
723
     * Create a new AssessmentPlanNotification for a modification to a Criteria
724
     *
725
     * @param string       $type            Can be CREATE, UPDATE or DELETE.
726
     * @param Criteria     $criteria
1 ignored issue
show
Coding Style Documentation introduced by
Missing parameter comment
Loading history...
727
     * @param integer|null $newSkillId      Only used for UPDATE type notifications.
728
     * @param integer|null $newSkillLevelId Only used for UPDATE type notifications.
729
     * @return AssessmentPlanNotification
730
     */
731
    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...
732
    {
733
        $notification = new AssessmentPlanNotification();
734
        $notification->job_poster_id = $criteria->job_poster_id;
735
        $notification->type = $type;
736
        $notification->criteria_id = $criteria->id;
737
        $notification->skill_id = $criteria->skill_id;
738
        $notification->criteria_type_id = $criteria->criteria_type_id;
739
        $notification->skill_level_id = $criteria->skill_level_id;
740
        $notification->skill_id_new = $newSkillId;
741
        $notification->skill_level_id_new = $newSkillLevelId;
742
        $notification->acknowledged = false;
743
        return $notification;
744
    }
745
746
    /**
747
     * Get the localized default questions and add them to an array.
748
     *
749
     * @return mixed[]|void
750
     */
751 2
    protected function populateDefaultQuestions()
752
    {
753
        $defaultQuestions = [
754 2
            'en' => array_values(Lang::get('manager/job_create', [], 'en')['questions']),
755 2
            'fr' => array_values(Lang::get('manager/job_create', [], 'fr')['questions']),
756
        ];
757
758 2
        if (count($defaultQuestions['en']) !== count($defaultQuestions['fr'])) {
759
            Log::warning('There must be the same number of French and English default questions for a Job Poster.');
760
            return;
761
        }
762
763 2
        $jobQuestions = [];
764
765 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...
766 2
            $jobQuestion = new JobPosterQuestion();
767 2
            $jobQuestion->fill(
768
                [
769
                    'en' => [
770 2
                        'question' => $defaultQuestions['en'][$i],
771
                    ],
772
                    'fr' => [
773 2
                        'question' => $defaultQuestions['fr'][$i],
774
                    ]
775
                ]
776
            );
777 2
            $jobQuestions[] = $jobQuestion;
778
        }
779
780 2
        return $jobQuestions;
781
    }
782
}
783