QuestionController::showQuestionAction()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 2

Importance

Changes 3
Bugs 0 Features 1
Metric Value
c 3
b 0
f 1
dl 0
loc 20
ccs 11
cts 11
cp 1
rs 9.4285
cc 2
eloc 11
nc 2
nop 1
crap 2
1
<?php
2
3
namespace AppBundle\Controller\Admin;
4
5
use AppBundle\Entity\Answer;
6
use AppBundle\Entity\Module;
7
use AppBundle\Entity\Question;
8
use AppBundle\Form\QuestionType;
9
use Doctrine\Common\Collections\ArrayCollection;
10
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
11
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
12
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
13
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
14
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
15
use Symfony\Component\HttpFoundation\Request;
16
17
18
class QuestionController extends Controller
19
{
20
    /**
21
     * @Route("/admin/question/new/{idModule}", name="create_question")
22
     * @Template("@App/admin/question/createQuestion.html.twig")
23
     */
24 1
    public function createQuestionAction(Request $request, $idModule)
25
    {
26 1
        $em = $this->getDoctrine()->getManager();
27 1
        $module = $em->getRepository('AppBundle:Module')->find($idModule);
28 1
        $question = new Question();
29
30 1
        $maxSort =  $em->getRepository('AppBundle:Question')->findMaxSortByModuleId($idModule);
31
32 1
        $form = $this->createForm(QuestionType::class, $question, ['new_sort'=> ++$maxSort['max_sort']]);
33
34 1
        $form->handleRequest($request);
35
36 1
        if ($form->isValid()) {
37
            if ($this->get('app.checkCount.answer')->checkCount($question)) {
38
                $question->setModule($module);
39
                $em->persist($question);
40
                $em->flush();
41
                return $this->redirectToRoute('create_question', array('idModule' => $idModule));
42
            }
43
        }
44
45 1
        return ['form' => $form->createView(),
46
                'idModule' => $idModule
47 1
        ];
48
    }
49
50
    /**
51
     * @Route("/admin/question/edit/{id}/{idModule}", name="edit_question")
52
     * @Template("@App/admin/question/editQuestion.html.twig")
53
     */
54 1
    public function editQuestionAction(Request $request, $id, $idModule)
55
    {
56 1
        $em = $this->getDoctrine()->getManager();
57
58 1
        $question = $em->getRepository('AppBundle:Question')
59 1
            ->find($id);
60
61 1
        $originalAnswers = new ArrayCollection();
62
63
        // Create an ArrayCollection of the current Tag objects in the database
64 1
        foreach ($question->getAnswers() as $answer) {
65 1
            $originalAnswers->add($answer);
66 1
        }
67
68 1
        $form = $this->createForm(QuestionType::class, $question);
69
70 1
        $form->handleRequest($request);
71
72 1
        if ($form->isValid()) {
73
            if ($this->get('app.checkCount.answer')->checkCount($question)) {
74
                foreach ($originalAnswers as $answer) {
75
                    if (false === $question->getAnswers()->contains($answer)) {
76
                        $em->remove($answer);
77
                    }
78
                }
79
                $em->flush();
80
            }
81
82
            return $this->redirectToRoute('edit_question', array('id' => $id, 'idModule' => $idModule));
83
        }
84
85 1
        return ['form' => $form->createView(),
86
                'idModule' => $idModule
87 1
        ];
88
    }
89
90
    /**
91
     * @Route("/admin/question/remove/{id}/{idModule}", name="remove_question")
92
     * @Method("DELETE")
93
     */
94 1
    public function removeQuestionAction($id, $idModule)
95
    {
96 1
        $em = $this->getDoctrine()->getManager();
97
98 1
        $question = $em->getRepository('AppBundle:Question')
99 1
            ->find($id);
100
101 1
        $em->remove($question);
102 1
        $em->flush();
103
104 1
        return $this->redirectToRoute('show_question', array('idModule' => $idModule));
105
106
    }
107
108
    /**
109
     * @Route("/admin/question/show/{idModule}", name="show_question")
110
     * @Template("@App/admin/question/showQuestion.html.twig")
111
     */
112 1
    public function showQuestionAction($idModule)
113
    {
114 1
        $em = $this->getDoctrine()->getManager();
115
116 1
        $question = $em->getRepository('AppBundle:Question')
0 ignored issues
show
Bug introduced by
The method findByModuleWithSorting() does not exist on Doctrine\Common\Persistence\ObjectRepository. Did you maybe mean findBy()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
117 1
            ->findByModuleWithSorting($idModule);
118
119 1
        $form_delete = [];
120
121 1
        foreach ($question as $item) {
122 1
            $form_delete[$item->getId()] = $this->createFormDelete($item->getId(), $idModule)->createView();
123 1
        }
124
125
        return [
126 1
            'idModule' => $idModule,
127 1
            'questions' => $question,
128
            'form_remove' => $form_delete
129 1
        ];
130
131
    }
132
133
    /**
134
     * @return \Symfony\Component\Form\Form
135
     */
136 1 View Code Duplication
    private function createFormDelete($id, $idModule)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
137
    {
138 1
        return $this->createFormBuilder()
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Symfony\Component\Form\FormConfigBuilder as the method add() does only exist in the following sub-classes of Symfony\Component\Form\FormConfigBuilder: Symfony\Component\Form\FormBuilder. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
139 1
            ->setAction($this->generateUrl('remove_question', ['id' => $id, 'idModule' => $idModule]))
140 1
            ->setMethod('DELETE')
141 1
            ->add('submit', SubmitType::class, [
142 1
                'label' => ' ',
143
                'attr' => [
144 1
                    'class' => 'glyphicon glyphicon-remove btn-link',
145
                    'onclick' => 'return confirm("Are you sure?")'
146 1
                ]
147 1
            ])
148 1
            ->getForm();
149
    }
150
151
}
152