QuestionNormalizer::normalize()   B
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 26
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 26
rs 8.8571
c 0
b 0
f 0
cc 1
eloc 18
nc 1
nop 3
1
<?php declare(strict_types=1);
2
3
namespace VSV\GVQ_API\Question\Serializers;
4
5
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
6
use VSV\GVQ_API\Question\Models\Answer;
7
use VSV\GVQ_API\Question\Models\Question;
8
9
class QuestionNormalizer implements NormalizerInterface
10
{
11
    /**
12
     * @var CategoryNormalizer
13
     */
14
    private $categoryNormalizer;
15
16
    /**
17
     * @var AnswerNormalizer
18
     */
19
    private $answerNormalizer;
20
21
    /**
22
     * @param CategoryNormalizer $categoryNormalizer
23
     * @param AnswerNormalizer $answerNormalizer
24
     */
25
    public function __construct(
26
        CategoryNormalizer $categoryNormalizer,
27
        AnswerNormalizer $answerNormalizer
28
    ) {
29
        $this->categoryNormalizer = $categoryNormalizer;
30
        $this->answerNormalizer = $answerNormalizer;
31
    }
32
33
    /**
34
     * @inheritdoc
35
     * @param Question $question
36
     */
37
    public function normalize($question, $format = null, array $context = []): array
38
    {
39
        $category = $this->categoryNormalizer->normalize(
40
            $question->getCategory(),
41
            $format
42
        );
43
44
        $answers = array_map(
45
            function (Answer $answer) use ($format) {
46
                return $this->answerNormalizer->normalize(
47
                    $answer,
48
                    $format
49
                );
50
            },
51
            $question->getAnswers()->toArray()
52
        );
53
54
        return [
55
            'id' => $question->getId()->toString(),
56
            'language' => $question->getLanguage()->toNative(),
57
            'year' => $question->getYear()->toNative(),
58
            'category' => $category,
59
            'text' => $question->getText()->toNative(),
60
            'imageFileName' => $question->getImageFileName()->toNative(),
61
            'answers' => $answers,
62
            'feedback' => $question->getFeedback()->toNative(),
63
        ];
64
    }
65
66
    /**
67
     * @inheritdoc
68
     */
69
    public function supportsNormalization($data, $format = null): bool
70
    {
71
        return ($data instanceof Question) && ($format === 'json');
72
    }
73
}
74