Passed
Push — master ( 795d23...149f73 )
by Grant
06:52 queued 12s
created

createDefaultQuestions()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 33
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 18
dl 0
loc 33
rs 9.6666
c 0
b 0
f 0
cc 4
nc 6
nop 1
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
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...
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