Completed
Branch develop (b9c805)
by Pavel
06:33
created

QuestionController   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 132
Duplicated Lines 10.61 %

Coupling/Cohesion

Components 1
Dependencies 9

Test Coverage

Coverage 76.92%

Importance

Changes 12
Bugs 2 Features 7
Metric Value
wmc 13
c 12
b 2
f 7
lcom 1
cbo 9
dl 14
loc 132
ccs 50
cts 65
cp 0.7692
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A createQuestionAction() 0 23 3
B editQuestionAction() 0 35 6
A removeQuestionAction() 0 13 1
A showQuestionAction() 0 20 2
A createFormDelete() 14 14 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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
        $form = $this->createForm(QuestionType::class, $question);
31
32 1
        $form->handleRequest($request);
33
34 1
        if ($form->isValid()) {
35
            if ($this->get('app.checkCount.answer')->checkCount($question)) {
36
                $question->setModule($module);
37
                $em->persist($question);
38
                $em->flush();
39
                return $this->redirectToRoute('create_question', array('idModule' => $idModule));
40
            }
41
        }
42
43 1
        return ['form' => $form->createView(),
44
                'idModule' => $idModule
45 1
        ];
46
    }
47
48
    /**
49
     * @Route("/admin/question/edit/{id}/{idModule}", name="edit_question")
50
     * @Template("@App/admin/question/editQuestion.html.twig")
51
     */
52 1
    public function editQuestionAction(Request $request, $id, $idModule)
53
    {
54 1
        $em = $this->getDoctrine()->getManager();
55
56 1
        $question = $em->getRepository('AppBundle:Question')
57 1
            ->find($id);
58
59 1
        $originalAnswers = new ArrayCollection();
60
61
        // Create an ArrayCollection of the current Tag objects in the database
62 1
        foreach ($question->getAnswers() as $answer) {
63 1
            $originalAnswers->add($answer);
64 1
        }
65
66 1
        $form = $this->createForm(QuestionType::class, $question);
67
68 1
        $form->handleRequest($request);
69
70 1
        if ($form->isValid()) {
71
            if ($this->get('app.checkCount.answer')->checkCount($question)) {
72
                foreach ($originalAnswers as $answer) {
73
                    if (false === $question->getAnswers()->contains($answer)) {
74
                        $em->remove($answer);
75
                    }
76
                }
77
                $em->flush();
78
            }
79
80
            return $this->redirectToRoute('edit_question', array('id' => $id, 'idModule' => $idModule));
81
        }
82
83 1
        return ['form' => $form->createView(),
84
                'idModule' => $idModule
85 1
        ];
86
    }
87
88
    /**
89
     * @Route("/admin/question/remove/{id}/{idModule}", name="remove_question")
90
     * @Method("DELETE")
91
     */
92 1
    public function removeQuestionAction($id, $idModule)
93
    {
94 1
        $em = $this->getDoctrine()->getManager();
95
96 1
        $question = $em->getRepository('AppBundle:Question')
97 1
            ->find($id);
98
99 1
        $em->remove($question);
100 1
        $em->flush();
101
102 1
        return $this->redirectToRoute('show_question', array('idModule' => $idModule));
103
104
    }
105
106
    /**
107
     * @Route("/admin/question/show/{idModule}", name="show_question")
108
     * @Template("@App/admin/question/showQuestion.html.twig")
109
     */
110 1
    public function showQuestionAction($idModule)
111
    {
112 1
        $em = $this->getDoctrine()->getManager();
113
114 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...
115 1
            ->findByModuleWithSorting($idModule);
116
117 1
        $form_delete = [];
118
119 1
        foreach ($question as $item) {
120 1
            $form_delete[$item->getId()] = $this->createFormDelete($item->getId(), $idModule)->createView();
121 1
        }
122
123
        return [
124 1
            'idModule' => $idModule,
125 1
            'questions' => $question,
126
            'form_remove' => $form_delete
127 1
        ];
128
129
    }
130
131
    /**
132
     * @return \Symfony\Component\Form\Form
133
     */
134 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...
135
    {
136 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...
137 1
            ->setAction($this->generateUrl('remove_question', ['id' => $id, 'idModule' => $idModule]))
138 1
            ->setMethod('DELETE')
139 1
            ->add('submit', SubmitType::class, [
140 1
                'label' => ' ',
141
                'attr' => [
142 1
                    'class' => 'glyphicon glyphicon-remove btn-link',
143
                    'onclick' => 'return confirm("Are you sure?")'
144 1
                ]
145 1
            ])
146 1
            ->getForm();
147
    }
148
149
}
150