Completed
Pull Request — master (#30)
by
unknown
05:03
created

SurveyNormalizer::supportsNormalization()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 2
crap 1
1
<?php
2
3
namespace AppBundle\Serializer;
4
5
use AppBundle\Entity\Survey\Survey;
6
use AppBundle\Entity\Survey\SurveyAnswer;
7
use Doctrine\Bundle\DoctrineBundle\Registry;
8
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
9
use Symfony\Component\PropertyInfo\PropertyTypeExtractorInterface;
10
use Symfony\Component\Serializer\Exception\LogicException;
11
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
12
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
13
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
14
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
15
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
16
17
class SurveyNormalizer extends ObjectNormalizer
18
{
19
    /**
20
     * @var Registry
21
     */
22
    protected $doctrine;
23
24
    /**
25
     * SurveyNormalizer constructor.
26
     *
27
     * @param ClassMetadataFactoryInterface|null  $classMDF
28
     * @param NameConverterInterface|null         $nameCv
29
     * @param PropertyAccessorInterface|null      $propertyAs
0 ignored issues
show
Bug introduced by
There is no parameter named $propertyAs. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
30
     * @param PropertyTypeExtractorInterface|null $propTE
31
     * @param Registry                            $doctrine
32
     */
33 4
    public function __construct($classMDF, $nameCv, $propAs, $propTE, Registry $doctrine)
34
    {
35 4
        parent::__construct($classMDF, $nameCv, $propAs, $propTE);
36 4
        $this->doctrine = $doctrine;
37 4
    }
38
39
    /**
40
     * {@inheritdoc}
41
     */
42 4
    public function supportsNormalization($data, $format = null)
43
    {
44 4
        return $data instanceof Survey;
45
    }
46
    /**
47
     * {@inheritdoc}
48
     */
49 2
    public function normalize($object, $format = null, array $context = [])
50
    {
51 2
        if (!$this->serializer instanceof NormalizerInterface) {
52
            throw new LogicException('Cannot normalize attributes because injected serializer is not a normalizer');
53
        }
54
        /** @var Survey $survey */
55 2
        $survey = &$object;
56 2
        if (isset($context[ObjectNormalizer::GROUPS])) {
57 2
            if ($context[ObjectNormalizer::GROUPS][0] == 'list') {
58 2
                return $this->serializer->normalize(new \ArrayObject([
59 2
                    'id' => $survey->getId(),
60 2
                    'type' => $survey->getType(),
61 2
                    'status' => $survey->getStatus(),
62 2
                    'createdAt' => $survey->getCreatedAt(),
63 2
                    'updatedAt' => $survey->getUpdatedAt(),
64
                ]), $format, $context);
65
            }
66
        }
67
68
        return $this->serializer->normalize(new \ArrayObject([
69
            'id' => $survey->getId(),
70
            'type' => $survey->getType(),
71
            'status' => $survey->getStatus(),
72
            'answers' => $survey->getAnswers(),
73
            'createdAt' => $survey->getCreatedAt(),
74
            'updatedAt' => $survey->getUpdatedAt(),
75
        ]), $format, $context);
76
    }
77
78
    /**
79
     * {@inheritdoc}
80
     */
81 1
    public function denormalize($data, $class, $format = null, array $context = array())
82
    {
83 1
        if (!$this->serializer instanceof DenormalizerInterface) {
84
            throw new LogicException('Cannot normalize attributes because injected serializer is not a normalizer');
85
        }
86 1
        if (!isset($context[ObjectNormalizer::OBJECT_TO_POPULATE])) {
87
            throw new LogicException('Not found object_to_populate');
88
        }
89
        /** @var Survey $survey */
90 1
        $survey = $context[ObjectNormalizer::OBJECT_TO_POPULATE];
91
92 1
        if (!array_key_exists('answers', $data)) {
93
            throw new LogicException('Wrong json consruction');
94
        }
95 1
        foreach ($data['answers'] as $item) {
96 1
            $answer = $this->serializer->denormalize($item, SurveyAnswer::class, $format, $context);
97 1
            $answer->setSurvey($survey);
98 1
            $answers[] = $answer;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$answers was never initialized. Although not strictly required by PHP, it is generally a good practice to add $answers = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
99 1
            $this->doctrine->getManager()->persist($answer);
100
        }
101 1
        foreach ($answers as $answer) {
0 ignored issues
show
Bug introduced by
The variable $answers does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
102 1
            $questions[] = $answer->getQuestion()->getId();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$questions was never initialized. Although not strictly required by PHP, it is generally a good practice to add $questions = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
103
        }
104 1
        foreach ($survey->getQuestions() as $question) {
105 1
            $surveyQuestions[] = $question->getId();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$surveyQuestions was never initialized. Although not strictly required by PHP, it is generally a good practice to add $surveyQuestions = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
106
        }
107 1
        if ($surveyQuestions !== $questions) {
0 ignored issues
show
Bug introduced by
The variable $surveyQuestions does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
The variable $questions does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
108
            throw new LogicException('Wrong json content');
109
        }
110 1
        $survey->setStatus('submited');
111 1
        $this->doctrine->getManager()->persist($survey);
112 1
        $this->doctrine->getManager()->flush();
113
114 1
        return $survey;
115
    }
116
117
    /**
118
     * {@inheritdoc}
119
     */
120 1
    public function supportsDenormalization($data, $type, $format = null)
121
    {
122 1
        if ($type != Survey::class) {
123
            return false;
124
        }
125
126 1
        return true;
127
    }
128
}
129