Passed
Push — task/job-poster-structured-dat... ( 307c28...47a06e )
by
unknown
04:12
created

JobController::show()   F

Complexity

Conditions 26
Paths 5376

Size

Total Lines 266
Code Lines 194

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 194
c 1
b 0
f 0
dl 0
loc 266
rs 0
cc 26
nc 5376
nop 2

How to fix   Long Method    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 App\Http\Controllers\Controller;
6
use App\Models\JobApplication;
7
use App\Models\JobPoster;
8
use App\Models\JobPosterQuestion;
9
use App\Models\Lookup\ApplicationStatus;
10
use App\Models\Lookup\CitizenshipDeclaration;
11
use App\Models\Lookup\JobPosterStatus;
12
use App\Models\Lookup\VeteranStatus;
13
use App\Models\Manager;
14
use App\Services\JobPosterDefaultQuestions;
15
use App\Services\Validation\JobPosterValidator;
16
use Carbon\Carbon;
17
use Facades\App\Services\WhichPortal;
18
use Illuminate\Http\Request;
19
use Illuminate\Support\Facades\Auth;
20
use Illuminate\Support\Facades\Lang;
21
use Illuminate\Support\Facades\Response;
22
use Illuminate\Support\Facades\Validator;
23
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
24
25
class JobController extends Controller
26
{
27
    /**
28
     * Display a listing of JobPosters.
29
     *
30
     * @return \Illuminate\Http\Response
31
     */
32
    public function index()
33
    {
34
        // If true, show the Paused due to COVID-19 message.
35
        $emergency_response = config('seasonal.is_covid_emergency');
0 ignored issues
show
Bug introduced by
The function config was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

35
        $emergency_response = /** @scrutinizer ignore-call */ config('seasonal.is_covid_emergency');
Loading history...
36
37
        // Find published jobs that are currently open for applications.
38
        // Eager load required relationships: Department, Province, JobTerm.
39
        // Eager load the count of submitted applications, to prevent the relationship
40
        // from being actually loaded and firing off events.
41
        $jobs = JobPoster::where('internal_only', false)
42
            ->where('department_id', '!=', config('app.strategic_response_department_id'))
43
            ->where('job_poster_status_id', JobPosterStatus::where('key', 'live')->first()->id)
44
            ->with([
45
                'department',
46
                'province',
47
                'job_term',
48
            ])
49
            ->withCount([
50
                'submitted_applications',
51
            ])
52
            ->get();
53
54
        $null_alert = $emergency_response
55
            ? Lang::get('applicant/job_index.index.covid_null_alert')
56
            : Lang::get('applicant/job_index.index.null_alert');
57
        return view('applicant/job_index', [
0 ignored issues
show
Bug introduced by
The function view was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

57
        return /** @scrutinizer ignore-call */ view('applicant/job_index', [
Loading history...
58
            'job_index' => Lang::get('applicant/job_index'),
59
            'null_alert' => $null_alert,
60
            'jobs' => $jobs
61
        ]);
62
    }
63
64
    /**
65
     * Display a listing of a manager's JobPosters.
66
     *
67
     * @return \Illuminate\Http\Response
68
     */
69
    public function managerIndex()
70
    {
71
        $manager = Auth::user()->manager;
72
73
        $jobs = JobPoster::where('manager_id', $manager->id)
74
            ->with('classification')
75
            ->withCount('submitted_applications')
76
            ->get();
77
78
        foreach ($jobs as &$job) {
79
            // If the chosen language is null then set to english.
80
            $chosen_lang = $job->chosen_lang ?: 'en';
81
82
            // Show chosen lang title if current title is empty.
83
            if (empty($job->title)) {
84
                $job->title = $job->getTranslation('title', $chosen_lang);
85
                $job->trans_required = true;
86
            }
87
        }
88
89
        return view('manager/job_index', [
0 ignored issues
show
Bug introduced by
The function view was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

89
        return /** @scrutinizer ignore-call */ view('manager/job_index', [
Loading history...
90
            // Localization Strings.
91
            'jobs_l10n' => Lang::get('manager/job_index'),
92
            // Data.
93
            'jobs' => $jobs,
94
        ]);
95
    }
96
97
    /**
98
     * Display a listing of a hr advisor's JobPosters.
99
     *
100
     * @param  \Illuminate\Http\Request $request Incoming request object.
101
     * @return \Illuminate\Http\Response
102
     */
103
    public function hrIndex(Request $request)
104
    {
105
        $hrAdvisor = $request->user()->hr_advisor;
106
        return view('hr_advisor/job_index', [
0 ignored issues
show
Bug introduced by
The function view was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

106
        return /** @scrutinizer ignore-call */ view('hr_advisor/job_index', [
Loading history...
107
            'jobs_l10n' => Lang::get('hr_advisor/job_index'),
108
            'hr_advisor_id' => $hrAdvisor->id
109
        ]);
110
    }
111
112
    /**
113
     * Delete a draft Job Poster.
114
     *
115
     * @param  \Illuminate\Http\Request $request   Incoming request object.
116
     * @param  \App\Models\JobPoster    $jobPoster Job Poster object.
117
     * @return void
118
     */
119
    public function destroy(Request $request, JobPoster $jobPoster): void
120
    {
121
        $jobPoster->delete();
122
    }
123
124
    /**
125
     * Display the specified job poster.
126
     *
127
     * @param  \Illuminate\Http\Request $request   Incoming request object.
128
     * @param  \App\Models\JobPoster    $jobPoster Job Poster object.
129
     * @return \Illuminate\Http\Response
130
     */
131
    public function show(Request $request, JobPoster $jobPoster)
132
    {
133
        $jobPoster->load([
134
            'department',
135
            'criteria.skill.skill_type',
136
            'manager.team_culture',
137
            'manager.work_environment'
138
        ]);
139
140
        $user = Auth::user();
141
142
        // TODO: Improve workplace photos, and reference them in template direction from WorkEnvironment model.
143
        $workplacePhotos = [];
144
        foreach ($jobPoster->manager->work_environment->workplace_photo_captions as $photoCaption) {
145
            $workplacePhotos[] = [
146
                'description' => $photoCaption->description,
147
                'url' => '/images/user.png'
148
            ];
149
        }
150
151
        // TODO: replace route('manager.show',manager.id) in templates with link using slug.
152
        $essential = $jobPoster->criteria->filter(
153
            function ($value, $key) {
154
                return $value->criteria_type->name == 'essential';
155
            }
156
        )->sortBy('id');
157
        $asset = $jobPoster->criteria->filter(
158
            function ($value, $key) {
159
                return $value->criteria_type->name == 'asset';
160
            }
161
        )->sortBy('id');
162
        $criteria = [
163
            'essential' => $essential,
164
            'asset' => $asset,
165
        ];
166
167
        $jobLang = Lang::get('applicant/job_post');
168
169
        $gocLang = Lang::get('common/goc');
170
171
        $skillsLang = Lang::get('common/skills');
172
173
        $skillsArray = [];
174
        foreach ($essential as $criterion) {
175
            $skillsArray[] = [
176
                'skill' => $criterion['skill']['name'],
177
                'level' => $skillsLang['skill_levels'][$criterion
178
                ->skill->skill_type->name][$criterion->skill_level->name],
179
            ];
180
        }
181
        foreach ($asset as $criterion) {
182
            $skillsArray[] = [
183
                'skill' => $criterion['skill']['name'],
184
                'level' => $skillsLang['skill_levels'][$criterion
185
                ->skill->skill_type->name][$criterion->skill_level->name],
186
            ];
187
        }
188
189
        $skillsString = '';
190
        if (!empty($skillsArray)) {
191
            $lastSkill = end($skillsArray);
192
            foreach ($skillsArray as $skillItem) {
193
                $skillsString .= $skillItem['skill'].' - '.$skillItem['level'].($skillItem == $lastSkill ? '.' : ', ');
194
            }
195
        }
196
197
        $benefitsString = '';
198
        if (is_array($jobLang['structured_data']['benefits'])) {
199
            foreach ($jobLang['structured_data']['benefits'] as $benefit) {
200
                $benefitsString .= $benefit.' ';
201
            }
202
        }
203
204
        $tasksString = '';
205
        if (is_array($jobPoster['job_poster_key_tasks'])) {
206
            $lastTask = end($jobPoster['job_poster_key_tasks']);
0 ignored issues
show
Unused Code introduced by
The assignment to $lastTask is dead and can be removed.
Loading history...
207
            foreach ($jobPoster['job_poster_key_tasks'] as $task) {
208
                $tasksString .= $task['description'].' '.($skillItem == $lastSkill ? '' : ' | ');
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $skillItem does not seem to be defined for all execution paths leading up to this point.
Loading history...
Comprehensibility Best Practice introduced by
The variable $lastSkill does not seem to be defined for all execution paths leading up to this point.
Loading history...
209
            }
210
        }
211
212
        $securityClearanceString = $jobLang['structured_data']['security_clearance_requirement_level'].': '
213
        .$jobPoster['security_clearance']['value'].'. '
214
        .$jobLang['structured_data']['security_clearance_requirement_description'];
215
216
        $structuredData = [
217
            '@context' => 'https://schema.org',
218
            '@type' => 'JobPosting',
219
            '@id' => url()->current(),
0 ignored issues
show
Bug introduced by
The function url was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

219
            '@id' => /** @scrutinizer ignore-call */ url()->current(),
Loading history...
220
            'url' => url('/'),
221
            'inLanguage' => app()->getLocale(),
0 ignored issues
show
Bug introduced by
The function app was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

221
            'inLanguage' => /** @scrutinizer ignore-call */ app()->getLocale(),
Loading history...
222
            'applicantLocationRequirements' => [
223
                '@type' => 'Country',
224
                'sameAs' => 'https://www.wikidata.org/wiki/Q16',
225
                'name' => 'Canada'
226
            ],
227
            'applicationContact' => [
228
                '@type' => 'ContactPoint',
229
                'email' => '[email protected]'
230
            ],
231
            'baseSalary' => [
232
                '@type' => 'MonetaryAmount',
233
                'currency' => 'CAD',
234
                'minValue' => $jobPoster['salary_min'],
235
                'maxValue' => $jobPoster['salary_max'],
236
            ],
237
            'datePosted' => $jobPoster['open_date_time'],
238
            'employerOverview' => $jobLang['structured_data']['employer_overview'],
239
            'employmentType' => $jobLang['structured_data']['employment_type'],
240
            'estimatedSalary' => [
241
                '@type' => 'MonetaryAmount',
242
                'currency' => 'CAD',
243
                'minValue' => $jobPoster['salary_min'],
244
                'maxValue' => $jobPoster['salary_max']
245
            ],
246
            'hiringOrganization' => [
247
                '@type' => 'GovernmentOrganization',
248
                'name' => $jobPoster['manager']['user']['department']['name'],
249
                'parentOrganization' => [
250
                    '@type' => 'GovernmentOrganization',
251
                    'name' => $jobLang['structured_data']['parent_organization'],
252
                    'url' => $gocLang['logo_link'],
253
                    'logo' => asset('/images/logo_canada_colour.png'),
0 ignored issues
show
Bug introduced by
The function asset was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

253
                    'logo' => /** @scrutinizer ignore-call */ asset('/images/logo_canada_colour.png'),
Loading history...
254
                ]
255
            ],
256
            'industry' => $jobLang['structured_data']['industry'],
257
            'jobBenefits' => $benefitsString,
258
            'jobLocation' => [
259
                '@type' => 'Place',
260
                'address' => [
261
                    '@type' => 'PostalAddress',
262
                    'addressLocality' => $jobPoster['city'],
263
                    'addressRegion' => $jobPoster['province']['value'],
264
                    'addressCountry' => 'CA'
265
                ]
266
            ],
267
            'jobStartDate' => $jobPoster['start_date_time'],
268
            'qualifications' => $jobPoster['education'],
269
            'responsibilities' => $tasksString,
270
            'salaryCurrency' => 'CAD',
271
            'securityClearanceRequirement' => $securityClearanceString,
272
            'skills' => $skillsString,
273
            'specialCommitments' => $jobLang['structured_data']['special_commitments'],
274
            'title' => $jobPoster['title'],
275
            'totalJobOpenings' => '1',
276
            'validThrough' => $jobPoster['close_date_time'],
277
            'description' => $jobPoster['hire_impact'] ? nl2br($jobPoster['hire_impact']) : '',
278
        ];
279
280
        if ($jobPoster['remote_work_allowed'] == true) {
281
            $structuredData['jobLocationType'] = 'TELECOMMUTE';
282
        };
283
284
        $applyButton = [];
285
        if (WhichPortal::isManagerPortal()) {
286
            $applyButton = [
287
                'href' => route('manager.jobs.edit', $jobPoster->id),
0 ignored issues
show
Bug introduced by
The function route was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

287
                'href' => /** @scrutinizer ignore-call */ route('manager.jobs.edit', $jobPoster->id),
Loading history...
288
                'title' => $jobLang['apply']['edit_link_title'],
289
                'text' => $jobLang['apply']['edit_link_label'],
290
            ];
291
        } elseif (WhichPortal::isHrPortal()) {
292
            if ($jobPoster->hr_advisors->contains('user_id', $user->id)) {
293
                $applyButton = [
294
                    'href' => route('hr_advisor.jobs.summary', $jobPoster->id),
295
                    'title' => null,
296
                    'text' => Lang::get('hr_advisor/job_summary.summary_title'),
297
                ];
298
            } else {
299
                $applyButton = [
300
                    'href' => route('hr_advisor.jobs.index'),
301
                    'title' => null,
302
                    'text' => Lang::get('hr_advisor/job_index.title'),
303
                ];
304
            }
305
        } elseif (Auth::check() && $jobPoster->isOpen()) {
306
            $application = JobApplication::where('applicant_id', Auth::user()->applicant->id)
307
                ->where('job_poster_id', $jobPoster->id)->first();
308
            // If applicants job application is not draft anymore then link to application preview page.
309
            if ($application != null && $application->application_status->name != 'draft') {
310
                $applyButton = [
311
                    'href' => route('applications.show', $application->id),
312
                    'title' => $jobLang['apply']['view_link_title'],
313
                    'text' => $jobLang['apply']['view_link_label'],
314
                ];
315
            } else {
316
                $applyButton = [
317
                    'href' => route('job.application.edit.1', $jobPoster->id),
318
                    'title' => $jobLang['apply']['apply_link_title'],
319
                    'text' => $jobLang['apply']['apply_link_label'],
320
                ];
321
            }
322
        } elseif (Auth::guest() && $jobPoster->isOpen()) {
323
            $applyButton = [
324
                'href' => route('job.application.edit.1', $jobPoster->id),
325
                'title' => $jobLang['apply']['login_link_title'],
326
                'text' => $jobLang['apply']['login_link_label'],
327
            ];
328
        } else {
329
            $applyButton = [
330
                'href' => null,
331
                'title' => null,
332
                'text' => $jobLang['apply']['job_closed_label'],
333
            ];
334
        }
335
336
        $jpb_release_date = strtotime('2019-08-21 16:18:17');
337
        $job_created_at = strtotime($jobPoster->created_at);
338
339
        $custom_breadcrumbs = [
340
            'home' => route('home'),
341
            'jobs' => route(WhichPortal::prefixRoute('jobs.index')),
342
            $jobPoster->title ?: 'job-title-missing' => route(WhichPortal::prefixRoute('jobs.summary'), $jobPoster),
343
            'preview' => '',
344
        ];
345
346
        // If the poster is part of the Strategic Talent Response dept, use the talent stream template.
347
        // Else, If the job poster is created after the release of the JPB.
348
        // Then, render with updated poster template.
349
        // Else, render with old poster template.
350
        if ($jobPoster->isInStrategicResponseDepartment()) {
351
            return view(
0 ignored issues
show
Bug introduced by
The function view was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

351
            return /** @scrutinizer ignore-call */ view(
Loading history...
352
                'applicant/strategic_response_job_post',
353
                [
354
                    'job_post' => $jobLang,
355
                    'frequencies' => Lang::get('common/lookup/frequency'),
356
                    'skill_template' => $skillsLang,
357
                    'job' => $jobPoster,
358
                    'manager' => $jobPoster->manager,
359
                    'criteria' => $criteria,
360
                    'apply_button' => $applyButton,
361
                    'custom_breadcrumbs' => $custom_breadcrumbs,
362
                ]
363
            );
364
        } elseif ($job_created_at > $jpb_release_date) {
365
            // Updated job poster (JPB).
366
            return view(
367
                'applicant/jpb_job_post',
368
                [
369
                    'job_post' => $jobLang,
370
                    'frequencies' => Lang::get('common/lookup/frequency'),
371
                    'skill_template' => $skillsLang,
372
                    'job' => $jobPoster,
373
                    'manager' => $jobPoster->manager,
374
                    'criteria' => $criteria,
375
                    'apply_button' => $applyButton,
376
                    'custom_breadcrumbs' => $custom_breadcrumbs,
377
                    'structured_data' => $structuredData,
378
                ]
379
            );
380
        } else {
381
            // Old job poster.
382
            return view(
383
                'applicant/job_post',
384
                [
385
                    'job_post' => $jobLang,
386
                    'frequencies' => Lang::get('common/lookup/frequency'),
387
                    'manager' => $jobPoster->manager,
388
                    'manager_profile_photo_url' => '/images/user.png', // TODO get real photo.
389
                    'team_culture' => $jobPoster->manager->team_culture,
390
                    'work_environment' => $jobPoster->manager->work_environment,
391
                    'workplace_photos' => $workplacePhotos,
392
                    'job' => $jobPoster,
393
                    'criteria' => $criteria,
394
                    'apply_button' => $applyButton,
395
                    'skill_template' => Lang::get('common/skills'),
396
                    'custom_breadcrumbs' => $custom_breadcrumbs,
397
                ]
398
            );
399
        }
400
    }
401
402
    /**
403
     * Display the form for editing an existing Job Poster
404
     * Only allows editing fields that don't appear on the react-built Job Poster Builder.
405
     *
406
     * @param  \Illuminate\Http\Request $request   Incoming request object.
407
     * @param  \App\Models\JobPoster    $jobPoster Job Poster object.
408
     * @return \Illuminate\Http\Response
409
     */
410
    public function edit(Request $request, JobPoster $jobPoster)
411
    {
412
        $manager = $jobPoster->manager;
413
414
        $defaultQuestionManager = new JobPosterDefaultQuestions();
415
        $defaultQuestionManager->initializeQuestionsIfEmpty($jobPoster);
416
417
        return view(
0 ignored issues
show
Bug introduced by
The function view was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

417
        return /** @scrutinizer ignore-call */ view(
Loading history...
418
            'manager/job_create',
419
            [
420
                // Localization Strings.
421
                'job_l10n' => Lang::get('manager/job_edit'),
422
                // Data.
423
                'manager' => $manager,
424
                'job' => $jobPoster,
425
                'form_action_url' => route('admin.jobs.update', $jobPoster),
0 ignored issues
show
Bug introduced by
The function route was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

425
                'form_action_url' => /** @scrutinizer ignore-call */ route('admin.jobs.update', $jobPoster),
Loading history...
426
            ]
427
        );
428
    }
429
430
    /**
431
     * Create a blank job poster for the specified manager
432
     *
433
     * @param  \App\Models\Manager $manager Incoming Manager object.
434
     * @return \Illuminate\Http\Response Job Create view
435
     */
436
    public function createAsManager(Manager $manager)
437
    {
438
        $jobPoster = new JobPoster();
439
        $jobPoster->manager_id = $manager->id;
440
441
        // Save manager-specific info to the job poster - equivalent to the intro step of the JPB.
442
        $divisionEn = $manager->getTranslation('division', 'en');
443
        $divisionFr = $manager->getTranslation('division', 'fr');
444
        $jobPoster->fill([
445
            'department_id' => $manager->user->department_id,
446
            'division' => ['en' => $divisionEn],
447
            'division' => ['fr' => $divisionFr],
448
        ]);
449
450
        $jobPoster->save();
451
452
        return redirect()->route('manager.jobs.edit', $jobPoster->id);
0 ignored issues
show
Bug introduced by
The function redirect was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

452
        return /** @scrutinizer ignore-call */ redirect()->route('manager.jobs.edit', $jobPoster->id);
Loading history...
453
    }
454
455
    /**
456
     * Update a resource in storage
457
     * NOTE: Only saves fields that are not on the react-built Job Poster Builder
458
     *
459
     * @param  \Illuminate\Http\Request $request   Incoming request object.
460
     * @param  \App\Models\JobPoster    $jobPoster Optional Job Poster object.
461
     * @return \Illuminate\Http\Response
462
     */
463
    public function store(Request $request, JobPoster $jobPoster)
464
    {
465
        // Don't allow edits for published Job Posters
466
        // Also check auth while we're at it.
467
        $this->authorize('update', $jobPoster);
468
        JobPosterValidator::validateUnpublished($jobPoster);
469
470
        $input = $request->input();
471
472
        if ($jobPoster->manager_id == null) {
473
            $jobPoster->manager_id = $request->user()->manager->id;
474
            $jobPoster->save();
475
        }
476
477
        if ($request->input('question')) {
478
            $validator = Validator::make($request->input('question'), [
479
                '*.question.*' => 'required|string',
480
            ], [
481
                'required' => Lang::get('validation.custom.job_poster_question.required'),
482
                'string' => Lang::get('validation.custom.job_poster_question.string')
483
            ]);
484
485
            if ($validator->fails()) {
486
                $request->session()->flash('errors', $validator->errors());
487
                return redirect(route('admin.jobs.edit', $jobPoster->id));
0 ignored issues
show
Bug introduced by
The function redirect was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

487
                return /** @scrutinizer ignore-call */ redirect(route('admin.jobs.edit', $jobPoster->id));
Loading history...
Bug introduced by
The function route was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

487
                return redirect(/** @scrutinizer ignore-call */ route('admin.jobs.edit', $jobPoster->id));
Loading history...
488
            }
489
        }
490
491
        $this->fillAndSaveJobPosterQuestions($input, $jobPoster, true);
492
493
        return redirect(route('manager.jobs.preview', $jobPoster->id));
494
    }
495
496
    /**
497
     * Fill Job Poster's questions and save
498
     *
499
     * @param  mixed[]               $input     Field values.
500
     * @param  \App\Models\JobPoster $jobPoster Job Poster object.
501
     * @param  boolean               $replace   Remove existing relationships.
502
     * @return void
503
     */
504
    protected function fillAndSaveJobPosterQuestions(array $input, JobPoster $jobPoster, bool $replace): void
505
    {
506
        if ($replace) {
507
            $jobPoster->job_poster_questions()->delete();
508
        }
509
510
        if (!array_key_exists('question', $input) || !is_array($input['question'])) {
511
            return;
512
        }
513
514
        foreach ($input['question'] as $question) {
515
            $jobQuestion = new JobPosterQuestion();
516
            $jobQuestion->job_poster_id = $jobPoster->id;
517
            $jobQuestion->fill(
518
                [
519
                    'question' => [
520
                        'en' => $question['question']['en'],
521
                        'fr' => $question['question']['fr']
522
523
                    ],
524
                    'description' => [
525
                        'en' => $question['description']['en'],
526
                        'fr' => $question['description']['fr']
527
                    ]
528
                ]
529
            );
530
            $jobPoster->save();
531
            $jobQuestion->save();
532
        }
533
    }
534
535
    /**
536
     * Downloads a CSV file with the applicants who have applied to the job poster.
537
     *
538
     * @param  \App\Models\JobPoster $jobPoster Job Poster object.
539
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
540
     */
541
    protected function downloadApplicants(JobPoster $jobPoster)
542
    {
543
        $tables = [];
544
        // The first row in the array represents the names of the columns in the spreadsheet.
545
        $tables[0] = ['Status', 'Applicant Name', 'Email', 'Language'];
546
547
        $application_status_id = ApplicationStatus::where('name', 'submitted')->first()->id;
548
        $applications = JobApplication::where('job_poster_id', $jobPoster->id)
549
            ->where('application_status_id', $application_status_id)
550
            ->get();
551
552
        $index = 1;
553
        foreach ($applications as $application) {
554
            $status = '';
555
            $username = $application->user_name;
556
            $user_email = $application->user_email;
557
            $language = strtoupper($application->preferred_language->name);
558
            // If the applicants veteran status name is NOT 'none' then set status to veteran.
559
            $non_veteran = VeteranStatus::where('name', 'none')->first()->id;
560
            if ($application->veteran_status_id != $non_veteran) {
561
                $status = 'Veteran';
562
            } else {
563
                // Check if the applicant is a canadian citizen.
564
                $canadian_citizen = CitizenshipDeclaration::where('name', 'citizen')->first()->id;
565
                if ($application->citizenship_declaration->id == $canadian_citizen) {
566
                    $status = 'Citizen';
567
                } else {
568
                    $status = 'Non-citizen';
569
                }
570
            }
571
            $tables[$index] = [$status, $username, $user_email, $language];
572
            $index++;
573
        }
574
575
        $filename = $jobPoster->id . '-' . 'applicants-data.csv';
576
577
        // Open file.
578
        $file = fopen($filename, 'w');
579
        // Iterate through tables and add each line to csv file.
580
        foreach ($tables as $line) {
581
            fputcsv($file, $line);
0 ignored issues
show
Bug introduced by
It seems like $file can also be of type false; however, parameter $handle of fputcsv() does only seem to accept resource, 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

581
            fputcsv(/** @scrutinizer ignore-type */ $file, $line);
Loading history...
582
        }
583
        // Close open file.
584
        fclose($file);
0 ignored issues
show
Bug introduced by
It seems like $file can also be of type false; however, parameter $handle of fclose() does only seem to accept resource, 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

584
        fclose(/** @scrutinizer ignore-type */ $file);
Loading history...
585
586
        $headers = [
587
            'Content-Type' => 'text/csv',
588
            'Content-Disposition' => 'attachment; filename=' . $filename,
589
        ];
590
591
        return Response::download($filename, $filename, $headers);
592
    }
593
}
594