Passed
Push — dev ( 3f0821...f9a9e5 )
by Chris
18:25 queued 13:50
created

JobController   B

Complexity

Total Complexity 51

Size/Duplication

Total Lines 589
Duplicated Lines 0 %

Test Coverage

Coverage 80.23%

Importance

Changes 6
Bugs 0 Features 0
Metric Value
wmc 51
eloc 322
c 6
b 0
f 0
dl 0
loc 589
ccs 211
cts 263
cp 0.8023
rs 7.92

11 Methods

Rating   Name   Duplication   Size   Complexity  
A destroy() 0 3 1
A index() 0 29 2
A managerIndex() 0 25 4
A hrIndex() 0 6 1
A edit() 0 16 1
A createAsManager() 0 17 1
A fillAndSaveJobPosterQuestions() 0 28 5
A downloadApplicants() 0 51 5
C buildStructuredData() 0 127 13
C show() 0 153 14
A store() 0 31 4

How to fix   Complexity   

Complex Class

Complex classes like JobController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use JobController, and based on these observations, apply Extract Interface, too.

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 1
        $jobs = JobPoster::where('manager_id', $manager->id)
74
            ->with('classification')
75 1
            ->withCount('submitted_applications')
76 1
            ->get();
77 1
78 1
        foreach ($jobs as &$job) {
79
            // If the chosen language is null then set to english.
80 1
            $chosen_lang = $job->chosen_lang ?: 'en';
81
82 1
            // Show chosen lang title if current title is empty.
83
            if (empty($job->title)) {
84 1
                $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 1
    }
96
97
    /**
98 1
     * Display a listing of a hr advisor's JobPosters.
99 1
     *
100
     * @param  \Illuminate\Http\Request $request Incoming request object.
101
     * @return \Illuminate\Http\Response
102 1
     */
103
    public function hrIndex(Request $request)
104
    {
105 1
        $hrAdvisor = $request->user()->hr_advisor;
106 1
        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 1
            'jobs_l10n' => Lang::get('hr_advisor/job_index'),
108
            'hr_advisor_id' => $hrAdvisor->id
109
        ]);
110
    }
111
112 1
    /**
113
     * Delete a draft Job Poster.
114 1
     *
115 1
     * @param  \Illuminate\Http\Request $request   Incoming request object.
116
     * @param  \App\Models\JobPoster    $jobPoster Job Poster object.
117
     * @return \Illuminate\Http\Response
118
     */
119
    public function destroy(Request $request, JobPoster $jobPoster)
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 6
        ]);
139
140 6
        $user = Auth::user();
141 6
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 6
                'url' => '/images/user.png'
148
            ];
149
        }
150 6
151 6
        // 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 6
            }
161
        )->sortBy('id');
162 4
        $criteria = [
163 6
            'essential' => $essential,
164
            'asset' => $asset,
165 6
        ];
166
167 4
        $jobLang = Lang::get('applicant/job_post');
168 6
169
        $skillsLang = Lang::get('common/skills');
170
171
        $applyButton = [];
172 6
        if (WhichPortal::isManagerPortal()) {
173
            $applyButton = [
174 6
                '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

174
                'href' => /** @scrutinizer ignore-call */ route('manager.jobs.edit', $jobPoster->id),
Loading history...
175 6
                'title' => $jobLang['apply']['edit_link_title'],
176
                'text' => $jobLang['apply']['edit_link_label'],
177 4
            ];
178 4
        } elseif (WhichPortal::isHrPortal()) {
179 4
            if ($jobPoster->hr_advisors->contains('user_id', $user->id)) {
180
                $applyButton = [
181 2
                    'href' => route('hr_advisor.jobs.summary', $jobPoster->id),
182
                    'title' => null,
183 1
                    'text' => Lang::get('hr_advisor/job_summary.summary_title'),
184 1
                ];
185 1
            } else {
186
                $applyButton = [
187 1
                    'href' => route('hr_advisor.jobs.index'),
188
                    'title' => null,
189 1
                    'text' => Lang::get('hr_advisor/job_index.title'),
190 1
                ];
191 1
            }
192
        } elseif (Auth::check() && $jobPoster->isOpen()) {
193
            $application = JobApplication::where('applicant_id', Auth::user()->applicant->id)
194
                ->where('job_poster_id', $jobPoster->id)->first();
195
            // If applicants job application is not draft anymore then link to application preview page.
196
            if ($application != null && $application->application_status->name != 'draft') {
197
                $applyButton = [
198
                    'href' => route('applications.show', $application->id),
199
                    'title' => $jobLang['apply']['view_link_title'],
200
                    'text' => $jobLang['apply']['view_link_label'],
201 6
                ];
202 6
            } else {
203
                $applyButton = [
204 6
                    'href' => route('job.application.edit.1', $jobPoster->id),
205 6
                    'title' => $jobLang['apply']['apply_link_title'],
206 6
                    'text' => $jobLang['apply']['apply_link_label'],
207 6
                ];
208 6
            }
209 6
        } elseif (Auth::guest() && $jobPoster->isOpen()) {
210 6
            $applyButton = [
211 6
                'href' => route('job.application.edit.1', $jobPoster->id),
212 6
                'title' => $jobLang['apply']['login_link_title'],
213 6
                'text' => $jobLang['apply']['login_link_label'],
214
            ];
215
        } else {
216
            $applyButton = [
217
                'href' => null,
218
                'title' => null,
219
                'text' => $jobLang['apply']['job_closed_label'],
220
            ];
221
        }
222
223
        $jpb_release_date = strtotime('2019-08-21 16:18:17');
224 2
        $job_created_at = strtotime($jobPoster->created_at);
225
226 2
        $custom_breadcrumbs = [
227 2
            'home' => route('home'),
228
            'jobs' => route(WhichPortal::prefixRoute('jobs.index')),
229 2
            $jobPoster->title ?: 'job-title-missing' => route(WhichPortal::prefixRoute('jobs.summary'), $jobPoster),
230
            'preview' => '',
231 2
        ];
232 2
233 2
        // If the poster is part of the Strategic Talent Response dept, use the talent stream template.
234
        // Else, If the job poster is created after the release of the JPB.
235
        // Then, render with updated poster template.
236 2
        // Else, render with old poster template.
237
        if ($jobPoster->isInStrategicResponseDepartment()) {
238
            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

238
            return /** @scrutinizer ignore-call */ view(
Loading history...
239
                'applicant/strategic_response_job_post',
240
                [
241
                    'job_post' => $jobLang,
242
                    'frequencies' => Lang::get('common/lookup/frequency'),
243
                    'skill_template' => $skillsLang,
244
                    'job' => $jobPoster,
245
                    'manager' => $jobPoster->manager,
246
                    'criteria' => $criteria,
247
                    'apply_button' => $applyButton,
248
                    'custom_breadcrumbs' => $custom_breadcrumbs,
249
                ]
250
            );
251
        } elseif ($job_created_at > $jpb_release_date) {
252
            // Updated job poster (JPB).
253
            return view(
254
                'applicant/jpb_job_post',
255
                [
256
                    'job_post' => $jobLang,
257 1
                    'frequencies' => Lang::get('common/lookup/frequency'),
258
                    'skill_template' => $skillsLang,
259 1
                    'job' => $jobPoster,
260
                    'manager' => $jobPoster->manager,
261
                    'criteria' => $criteria,
262
                    'apply_button' => $applyButton,
263
                    'custom_breadcrumbs' => $custom_breadcrumbs,
264
                    'structured_data' => $this->buildStructuredData($jobPoster),
265
                ]
266
            );
267
        } else {
268
            // Old job poster.
269 1
            return view(
270
                'applicant/job_post',
271 1
                [
272
                    'job_post' => $jobLang,
273
                    'frequencies' => Lang::get('common/lookup/frequency'),
274 1
                    'manager' => $jobPoster->manager,
275
                    'manager_profile_photo_url' => '/images/user.png', // TODO get real photo.
276
                    'team_culture' => $jobPoster->manager->team_culture,
277 1
                    'work_environment' => $jobPoster->manager->work_environment,
278 1
                    'workplace_photos' => $workplacePhotos,
279 1
                    'job' => $jobPoster,
280 1
                    'criteria' => $criteria,
281
                    'apply_button' => $applyButton,
282
                    'skill_template' => Lang::get('common/skills'),
283
                    'custom_breadcrumbs' => $custom_breadcrumbs,
284
                ]
285
            );
286
        }
287
    }
288
289
    /**
290
     * Display the form for editing an existing Job Poster
291 1
     * Only allows editing fields that don't appear on the react-built Job Poster Builder.
292
     *
293 1
     * @param  \Illuminate\Http\Request $request   Incoming request object.
294 1
     * @param  \App\Models\JobPoster    $jobPoster Job Poster object.
295
     * @return \Illuminate\Http\Response
296 1
     */
297 1
    public function edit(Request $request, JobPoster $jobPoster)
298 1
    {
299 1
        $manager = $jobPoster->manager;
300
301
        $defaultQuestionManager = new JobPosterDefaultQuestions();
302 1
        $defaultQuestionManager->initializeQuestionsIfEmpty($jobPoster);
303
304 1
        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

304
        return /** @scrutinizer ignore-call */ view(
Loading history...
305
            'manager/job_create',
306 1
            [
307
                // Localization Strings.
308 1
                'job_l10n' => Lang::get('manager/job_edit'),
309 1
                // Data.
310
                'manager' => $manager,
311 1
                'job' => $jobPoster,
312 1
                '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

312
                'form_action_url' => /** @scrutinizer ignore-call */ route('admin.jobs.update', $jobPoster),
Loading history...
313 1
            ]
314 1
        );
315
    }
316
317 1
    /**
318
     * Create a blank job poster for the specified manager
319 1
     *
320
     * @param  \App\Models\Manager $manager Incoming Manager object.
321 1
     * @return \Illuminate\Http\Response Job Create view
322
     */
323 1
    public function createAsManager(Manager $manager)
324 1
    {
325
        $jobPoster = new JobPoster();
326
        $jobPoster->manager_id = $manager->id;
327
328 1
        // Save manager-specific info to the job poster - equivalent to the intro step of the JPB.
329 1
        $divisionEn = $manager->getTranslation('division', 'en');
330
        $divisionFr = $manager->getTranslation('division', 'fr');
331
        $jobPoster->fill([
332 1
            'department_id' => $manager->user->department_id,
333 1
            'division' => ['en' => $divisionEn],
334
            'division' => ['fr' => $divisionFr],
335
        ]);
336
337 1
        $jobPoster->save();
338
339 1
        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

339
        return /** @scrutinizer ignore-call */ redirect()->route('manager.jobs.edit', $jobPoster->id);
Loading history...
340
    }
341 1
342
    /**
343 1
     * Update a resource in storage
344 1
     * NOTE: Only saves fields that are not on the react-built Job Poster Builder
345 1
     *
346
     * @param  \Illuminate\Http\Request $request   Incoming request object.
347 1
     * @param  \App\Models\JobPoster    $jobPoster Optional Job Poster object.
348
     * @return \Illuminate\Http\Response
349 1
     */
350 1
    public function store(Request $request, JobPoster $jobPoster)
351 1
    {
352
        // Don't allow edits for published Job Posters
353 1
        // Also check auth while we're at it.
354 1
        $this->authorize('update', $jobPoster);
355
        JobPosterValidator::validateUnpublished($jobPoster);
356
357 1
        $input = $request->input();
358
359 1
        if ($jobPoster->manager_id == null) {
360 1
            $jobPoster->manager_id = $request->user()->manager->id;
361 1
            $jobPoster->save();
362 1
        }
363 1
364 1
        if ($request->input('question')) {
365 1
            $validator = Validator::make($request->input('question'), [
366 1
                '*.question.*' => 'required|string',
367 1
            ], [
368 1
                'required' => Lang::get('validation.custom.job_poster_question.required'),
369 1
                'string' => Lang::get('validation.custom.job_poster_question.string')
370
            ]);
371
372
            if ($validator->fails()) {
373
                $request->session()->flash('errors', $validator->errors());
374
                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

374
                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

374
                return redirect(/** @scrutinizer ignore-call */ route('admin.jobs.edit', $jobPoster->id));
Loading history...
375
            }
376
        }
377
378
        $this->fillAndSaveJobPosterQuestions($input, $jobPoster, true);
379
380
        return redirect(route('manager.jobs.preview', $jobPoster->id));
381 6
    }
382
383
    /**
384
     * Fill Job Poster's questions and save
385 6
     *
386 6
     * @param  mixed[]               $input     Field values.
387 6
     * @param  \App\Models\JobPoster $jobPoster Job Poster object.
388
     * @param  boolean               $replace   Remove existing relationships.
389
     * @return void
390
     */
391
    protected function fillAndSaveJobPosterQuestions(array $input, JobPoster $jobPoster, bool $replace): void
392 6
    {
393
        if ($replace) {
394 6
            $jobPoster->job_poster_questions()->delete();
395
        }
396 6
397
        if (!array_key_exists('question', $input) || !is_array($input['question'])) {
398
            return;
399
        }
400
401 6
        foreach ($input['question'] as $question) {
402
            $jobQuestion = new JobPosterQuestion();
403 6
            $jobQuestion->job_poster_id = $jobPoster->id;
404
            $jobQuestion->fill(
405 6
                [
406
                    'question' => [
407 6
                        'en' => $question['question']['en'],
408
                        'fr' => $question['question']['fr']
409 6
410
                    ],
411
                    'description' => [
412
                        'en' => $question['description']['en'],
413
                        'fr' => $question['description']['fr']
414
                    ]
415
                ]
416
            );
417
            $jobPoster->save();
418
            $jobQuestion->save();
419 6
        }
420
    }
421 6
422
    /**
423 6
     * Downloads a CSV file with the applicants who have applied to the job poster.
424 6
     *
425 6
     * @param  \App\Models\JobPoster $jobPoster Job Poster object.
426 6
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
427 6
     */
428 6
    protected function downloadApplicants(JobPoster $jobPoster)
429 6
    {
430 6
        $tables = [];
431 6
        // The first row in the array represents the names of the columns in the spreadsheet.
432 6
        $tables[0] = ['Status', 'Applicant Name', 'Email', 'Language'];
433 6
434 6
        $application_status_id = ApplicationStatus::where('name', 'submitted')->first()->id;
435 6
        $applications = JobApplication::where('job_poster_id', $jobPoster->id)
436 6
            ->where('application_status_id', $application_status_id)
437
            ->get();
438 6
439 6
        $index = 1;
440 6
        foreach ($applications as $application) {
441 6
            $status = '';
442 6
            $username = $application->user_name;
443 6
            $user_email = $application->user_email;
444
            $language = strtoupper($application->preferred_language->name);
445
            // If the applicants veteran status name is NOT 'none' then set status to veteran.
446 6
            $non_veteran = VeteranStatus::where('name', 'none')->first()->id;
447 6
            if ($application->veteran_status_id != $non_veteran) {
448 6
                $status = 'Veteran';
449 6
            } else {
450 6
                // Check if the applicant is a canadian citizen.
451 6
                $canadian_citizen = CitizenshipDeclaration::where('name', 'citizen')->first()->id;
452
                if ($application->citizenship_declaration->id == $canadian_citizen) {
453
                    $status = 'Citizen';
454
                } else {
455 6
                    $status = 'Non-citizen';
456 6
                }
457
            }
458
            $tables[$index] = [$status, $username, $user_email, $language];
459
            $index++;
460
        }
461
462
        $filename = $jobPoster->id . '-' . 'applicants-data.csv';
463
464
        // Open file.
465
        $file = fopen($filename, 'w');
466 6
        // Iterate through tables and add each line to csv file.
467
        foreach ($tables as $line) {
468 6
            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

468
            fputcsv(/** @scrutinizer ignore-type */ $file, $line);
Loading history...
469 6
        }
470
        // Close open file.
471
        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

471
        fclose(/** @scrutinizer ignore-type */ $file);
Loading history...
472 6
473 6
        $headers = [
474
            'Content-Type' => 'text/csv',
475
            'Content-Disposition' => 'attachment; filename=' . $filename,
476
        ];
477
478
        return Response::download($filename, $filename, $headers);
479
    }
480
481
    /**
482
     * Build Job Poster's structured data
483
     *
484
     * @param  \App\Models\JobPoster $jobPoster Job Poster object.
485
     * @return array
486
     */
487
    protected function buildStructuredData(JobPoster $jobPoster)
488
    {
489
        $gocLang = Lang::get('common/goc');
490
491
        $jobLang = Lang::get('applicant/job_post');
492
493
        $essential = $jobPoster->criteria->filter(
494
            function ($value) {
495
                return $value->criteria_type->name == 'essential';
496
            }
497
        )->sortBy('id');
498
        $asset = $jobPoster->criteria->filter(
499
            function ($value) {
500
                return $value->criteria_type->name == 'asset';
501 6
            }
502
        )->sortBy('id');
503 6
504 6
        $skillsArray = [];
505
        foreach ($essential as $criterion) {
506
            $skillsArray[] = [
507 6
                'skill' => $criterion['skill']['name'],
508 6
                'level' => $criterion->level_name,
509
            ];
510
        }
511
        foreach ($asset as $criterion) {
512
            $skillsArray[] = [
513
                'skill' => $criterion['skill']['name'],
514
                'level' => $criterion->level_name,
515
            ];
516
        }
517
518
        $skillsString = '';
519
        if (!empty($skillsArray)) {
520
            $lastSkill = end($skillsArray);
521
            foreach ($skillsArray as $skillItem) {
522
                $skillsString .= $skillItem['skill'].' - '.$skillItem['level'].($skillItem == $lastSkill ? '.' : ', ');
523
            }
524
        }
525
526
        $benefitsString = '';
527
        if (is_array($jobLang['structured_data']['benefits'])) {
528
            foreach ($jobLang['structured_data']['benefits'] as $benefit) {
529
                $benefitsString .= $benefit.' ';
530
            }
531
        }
532
533
        $tasksString = '';
534
        if (is_array($jobPoster['job_poster_key_tasks'])) {
535
            $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...
536
            foreach ($jobPoster['job_poster_key_tasks'] as $task) {
537 6
                $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...
538
            }
539 6
        }
540
541 6
        $securityClearanceString = $jobLang['structured_data']['security_clearance_requirement_level'].': '
542 2
        .$jobPoster['security_clearance']['value'].'. '
543
        .$jobLang['structured_data']['security_clearance_requirement_description'];
544
545 2
        $structuredData = [
546 1
            '@context' => 'https://schema.org',
547 1
            '@type' => 'JobPosting',
548 1
            '@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

548
            '@id' => /** @scrutinizer ignore-call */ url()->current(),
Loading history...
549 1
            'url' => url('/'),
550 1
            '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

550
            'inLanguage' => /** @scrutinizer ignore-call */ app()->getLocale(),
Loading history...
551
            'applicantLocationRequirements' => [
552
                '@type' => 'Country',
553
                'sameAs' => 'https://www.wikidata.org/wiki/Q16',
554
                'name' => 'Canada'
555
            ],
556 2
            'applicationContact' => [
557 1
                '@type' => 'ContactPoint',
558 1
                'email' => '[email protected]'
559 1
            ],
560 1
            'baseSalary' => [
561 1
                '@type' => 'MonetaryAmount',
562
                'currency' => 'CAD',
563
                'minValue' => $jobPoster['salary_min'],
564
                'maxValue' => $jobPoster['salary_max'],
565
            ],
566
            'datePosted' => $jobPoster['open_date_time'],
567
            'employerOverview' => $jobLang['structured_data']['employer_overview'],
568
            'employmentType' => $jobLang['structured_data']['employment_type'],
569 6
            'estimatedSalary' => [
570 6
                '@type' => 'MonetaryAmount',
571 6
                'currency' => 'CAD',
572
                'minValue' => $jobPoster['salary_min'],
573 6
                'maxValue' => $jobPoster['salary_max']
574
            ],
575
            'hiringOrganization' => [
576
                '@type' => 'GovernmentOrganization',
577
                'name' => $jobPoster['manager']['user']['department']['name'],
578
                'parentOrganization' => [
579
                    '@type' => 'GovernmentOrganization',
580
                    'name' => $jobLang['structured_data']['parent_organization'],
581
                    'url' => $gocLang['logo_link'],
582
                    '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

582
                    'logo' => /** @scrutinizer ignore-call */ asset('/images/logo_canada_colour.png'),
Loading history...
583
                ]
584 2
            ],
585
            'industry' => $jobLang['structured_data']['industry'],
586 2
            'jobBenefits' => $benefitsString,
587
            'jobLocation' => [
588
                '@type' => 'Place',
589 2
                'address' => [
590 2
                    '@type' => 'PostalAddress',
591 2
                    'addressLocality' => $jobPoster['city'],
592 2
                    'addressRegion' => $jobPoster['province']['value'],
593
                    'addressCountry' => 'CA'
594 2
                ]
595 2
            ],
596 2
            'jobStartDate' => $jobPoster['start_date_time'],
597
            'qualifications' => $jobPoster['education'],
598 2
            'responsibilities' => $tasksString,
599
            'salaryCurrency' => 'CAD',
600
            'securityClearanceRequirement' => $securityClearanceString,
601 2
            'skills' => $skillsString,
602
            'specialCommitments' => $jobLang['structured_data']['special_commitments'],
603
            'title' => $jobPoster['title'],
604
            'totalJobOpenings' => '1',
605 2
            'validThrough' => $jobPoster['close_date_time'],
606 1
            'description' => $jobPoster['hire_impact'] ? nl2br($jobPoster['hire_impact']) : '',
607 1
        ];
608 1
609
        if ($jobPoster['remote_work_allowed'] == true) {
610 1
            $structuredData['jobLocationType'] = 'TELECOMMUTE';
611 1
        };
612
613
        return $structuredData;
614
    }
615
}
616