1 | <?php |
||
2 | |||
3 | namespace App\Services; |
||
4 | |||
5 | use App\Models\JobPoster; |
||
6 | use App\Models\JobPosterQuestion; |
||
7 | use Illuminate\Support\Facades\Lang; |
||
8 | use Illuminate\Support\Facades\Log; |
||
9 | |||
10 | class JobPosterDefaultQuestions |
||
11 | { |
||
12 | /** |
||
13 | * Get the localized default questions and add them to an array. |
||
14 | * |
||
15 | * @return mixed[]|void |
||
16 | */ |
||
17 | public function createDefaultQuestions(bool $isStrategicResponseJob = false) |
||
18 | { |
||
19 | |||
20 | $question_key = $isStrategicResponseJob |
||
21 | ? 'strategic_response_questions' |
||
22 | : 'questions'; |
||
23 | |||
24 | $defaultQuestions = [ |
||
25 | 'en' => array_values(Lang::get('manager/job_create', [], 'en')[$question_key]), |
||
26 | 'fr' => array_values(Lang::get('manager/job_create', [], 'fr')[$question_key]), |
||
27 | ]; |
||
28 | |||
29 | if (count($defaultQuestions['en']) !== count($defaultQuestions['fr'])) { |
||
30 | Log::warning('There must be the same number of French and English default questions for a Job Poster.'); |
||
31 | return; |
||
32 | } |
||
33 | |||
34 | $jobQuestions = []; |
||
35 | |||
36 | for ($i = 0; $i < count($defaultQuestions['en']); $i++) { |
||
0 ignored issues
–
show
|
|||
37 | $jobQuestion = new JobPosterQuestion(); |
||
38 | $jobQuestion->fill( |
||
39 | [ |
||
40 | 'question' => [ |
||
41 | 'en' => $defaultQuestions['en'][$i], |
||
42 | 'fr' => $defaultQuestions['fr'][$i], |
||
43 | ] |
||
44 | ] |
||
45 | ); |
||
46 | $jobQuestions[] = $jobQuestion; |
||
47 | } |
||
48 | |||
49 | return $jobQuestions; |
||
50 | } |
||
51 | |||
52 | public function initializeQuestionsIfEmpty(JobPoster $jobPoster) |
||
53 | { |
||
54 | if ($jobPoster->job_poster_questions === null || $jobPoster->job_poster_questions->count() === 0) { |
||
55 | $questions = $this->createDefaultQuestions($jobPoster->isInStrategicResponseDepartment()); |
||
56 | $jobPoster->job_poster_questions()->saveMany($questions); |
||
57 | $jobPoster->refresh(); |
||
58 | } |
||
59 | } |
||
60 | } |
||
61 |
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: