Completed
Pull Request — dev (#24)
by
unknown
04:06
created

SurveyController::apiSurveyAction()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 29
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 29
ccs 0
cts 0
cp 0
rs 8.5806
c 1
b 0
f 0
cc 4
eloc 19
nc 4
nop 1
crap 20
1
<?php
2
3
namespace AppBundle\Controller\Api;
4
5
use AppBundle\Entity\SurveyAnswer;
6
use AppBundle\Entity\Survey;
7
use AppBundle\Entity\SurveyQuestion;
8
use Mcfedr\JsonFormBundle\Controller\JsonController;
9
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
10
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
11
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
12
use Symfony\Component\HttpFoundation\Request;
13
14
class SurveyController extends JsonController
15
{
16
    /**
17
     * @Route("/surveys", name="api_surveys")
18
     * @Method("GET")
19
     */
20 2
    public function apiSurveysAction()
21
    {
22 2
        $user = $this->getUser();
23 2
        if (!$user) {
24
            return $this->json(['message' => 'User is not authorized'], 401);
25
        }
26 2
        $em = $this->getDoctrine()->getManager();
27 2
        $surveys = $em->getRepository(Survey::class)->findSurveyByUser($user);
28 2
        if (!$surveys) {
29
            return $this->json(['message' => 'No surveys'], 404);
30
        }
31 2
        $serializer = $this->get('serializer');
32
33 2
        $json = $serializer->normalize(
34
            $surveys,
35 2
            null,
36 2
            array('groups' => array('group1'))
37
        );
38
39 2
        return $this->json(['surveys' => $json], 200);
40
    }
41
42
    /**
43
     * @param Survey $survey
44
     * @Route("/surveys/{id}", name="api_survey")
45
     * @Method("GET")
46
     * @ParamConverter("survey", class="AppBundle:Survey")
47
     */
48
    public function apiSurveyAction(Survey $survey)
49
    {
50
        $user = $this->getUser();
51
        if (!$user) {
52
            return $this->json(['message' => 'User is not authorized'], 401);
53
        }
54
55
        if (!$survey) {
56
            return $this->json(['message' => 'No surveys'], 404);
57
        }
58
        $serializer = $this->get('serializer');
59
        $jsonSurvey = $serializer->normalize(
60
            $survey,
61
            null,
62
            array('groups' => array('group1', 'group2'))
63
        );
64
        if ($survey->getStatus() == 'submited') {
65
            $answers = $survey->getAnswers();
66
            $jsonAnswers = $serializer->normalize(
67
                $answers,
68
                null,
69
                array('groups' => array('group3'))
70
            );
71
72
            return $this->json(['survey' => $jsonSurvey, 'answers' => $jsonAnswers], 200);
73
        }
74
75
        return $this->json(['survey' => $jsonSurvey], 200);
76
    }
77
78
    /**
79
     * @param Request $request, Survey $survey
0 ignored issues
show
Documentation introduced by
There is no parameter named $request,. Did you maybe mean $request?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

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

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

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

Loading history...
80
     * @Route("/surveys/{id}", name="api_survey_update")
81
     * @Method("PUT")
82
     * @ParamConverter("survey", class="AppBundle:Survey")
83
     */
84 1
    public function apiSurveyUpdateAction(Request $request, Survey $survey)
85
    {
86 1
        $user = $this->getUser();
87 1
        if (!$user) {
88
            return $this->json(['message' => 'User is not authorized'], 401);
89
        }
90 1
        if (!$survey || $survey->getStatus() == 'submited') {
91
            return $this->json(['message' => 'No survey'], 404);
92
        }
93 1
        foreach ($survey->getType()->getSections() as $section) {
94 1
            foreach ($section->getQuestions() as $question) {
95 1
                $questKey[] = $question->getId();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$questKey was never initialized. Although not strictly required by PHP, it is generally a good practice to add $questKey = 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...
96
            }
97
        }
98 1
        $data = json_decode($request->getContent(), true);
99 1
        $em = $this->getDoctrine()->getManager();
100 1
        foreach ($questKey as $key) {
0 ignored issues
show
Bug introduced by
The variable $questKey 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...
101 1
            $answer = $data[$key];
102 1
            if ($answer == null) {
103
                return $this->json(['message' => 'Survey is not filled out'], 400);
104
            }
105 1
            $question = $em->getRepository(SurveyQuestion::class)->find($key);
106 1
            $variants = $question->getVariants();
107 1
            if (count($variants) > 0 & !in_array($answer, $variants)) {
108
                return $this->json(['message' => 'Wrong answer variant.'], 400);
109
            }
110 1
            $newAnswer = new SurveyAnswer();
111 1
            $newAnswer->setSurvey($survey);
112 1
            $newAnswer->setQuestion($question);
113 1
            $newAnswer->setContent($answer);
114 1
            $em->persist($newAnswer);
115
        }
116 1
        $survey->setStatus('submited');
117 1
        $em->flush();
118
119 1
        return $this->json(['message' => 'Survey updated'], 200);
120
    }
121
}
122