Completed
Push — master ( ae5e03...0447ee )
by Jeroen
10:35 queued 04:37
created

FormSubmissionsController   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 162
Duplicated Lines 8.64 %

Coupling/Cohesion

Components 1
Dependencies 11

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 11
dl 14
loc 162
ccs 0
cts 77
cp 0
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A exportAction() 0 13 1
A listAction() 0 13 1
A editAction() 0 20 1
A deleteAction() 0 39 3
A indexAction() 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 Kunstmaan\FormBundle\Controller;
4
5
use Doctrine\ORM\EntityManager;
6
use Kunstmaan\AdminBundle\Helper\Security\Acl\Permission\PermissionMap;
7
use Kunstmaan\AdminListBundle\AdminList\AdminList;
8
use Kunstmaan\AdminListBundle\AdminList\ExportList;
9
use Kunstmaan\FormBundle\AdminList\FormPageAdminListConfigurator;
10
use Kunstmaan\FormBundle\AdminList\FormSubmissionAdminListConfigurator;
11
use Kunstmaan\FormBundle\AdminList\FormSubmissionExportListConfigurator;
12
use Kunstmaan\FormBundle\Entity\FormSubmission;
13
use Kunstmaan\FormBundle\Entity\FormSubmissionField;
14
use Kunstmaan\NodeBundle\Entity\Node;
15
use Kunstmaan\NodeBundle\Entity\NodeTranslation;
16
use Symfony\Component\Routing\Annotation\Route;
17
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
18
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
19
use Symfony\Component\HttpFoundation\RedirectResponse;
20
use Symfony\Component\HttpFoundation\Request;
21
use Symfony\Component\HttpFoundation\Response;
22
use Kunstmaan\AdminBundle\FlashMessages\FlashTypes;
23
24
/**
25
 * The controller which will handle everything related with form pages and form submissions
26
 */
27
class FormSubmissionsController extends Controller
0 ignored issues
show
Deprecated Code introduced by
The class Symfony\Bundle\Framework...e\Controller\Controller has been deprecated with message: since Symfony 4.2, use "Symfony\Bundle\FrameworkBundle\Controller\AbstractController" instead.

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
28
{
29
    /**
30
     * The index action will use an admin list to list all the form pages
31
     *
32
     * @Route("/", name="KunstmaanFormBundle_formsubmissions")
33
     * @Template("@KunstmaanAdminList/Default/list.html.twig")
34
     *
35
     * @return array
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use array<string,AdminList>.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
36
     */
37 View Code Duplication
    public function indexAction(Request $request)
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...
38
    {
39
        /* @var EntityManager $em */
40
        $em = $this->getDoctrine()->getManager();
41
        $aclHelper = $this->container->get('kunstmaan_admin.acl.helper');
42
43
        /* @var AdminList $adminList */
44
        $adminList = $this->get('kunstmaan_adminlist.factory')->createList(
45
            new FormPageAdminListConfigurator($em, $aclHelper, PermissionMap::PERMISSION_VIEW)
0 ignored issues
show
Documentation introduced by
$aclHelper is of type object|null, but the function expects a object<Kunstmaan\AdminBu...Security\Acl\AclHelper>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
46
        );
47
        $adminList->bindRequest($request);
48
49
        return array('adminlist' => $adminList);
50
    }
51
52
    /**
53
     * The list action will use an admin list to list all the form submissions related to the given $nodeTranslationId
54
     *
55
     * @param int $nodeTranslationId
56
     *
57
     * @Route("/list/{nodeTranslationId}", requirements={"nodeTranslationId" = "\d+"},
58
     *                                     name="KunstmaanFormBundle_formsubmissions_list", methods={"GET", "POST"})
59
     * @Template("@KunstmaanForm/FormSubmissions/list.html.twig")
60
     *
61
     * @return array
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use array<string,object|null>.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
62
     */
63
    public function listAction(Request $request, $nodeTranslationId)
64
    {
65
        $em = $this->getDoctrine()->getManager();
66
        $nodeTranslation = $em->getRepository(NodeTranslation::class)->find($nodeTranslationId);
67
68
        /** @var AdminList $adminList */
69
        $adminList = $this->get('kunstmaan_adminlist.factory')->createList(
70
            new FormSubmissionAdminListConfigurator($em, $nodeTranslation, $this->getParameter('kunstmaan_form.deletable_formsubmissions'))
0 ignored issues
show
Compatibility introduced by
$em of type object<Doctrine\Persistence\ObjectManager> is not a sub-type of object<Doctrine\ORM\EntityManager>. It seems like you assume a concrete implementation of the interface Doctrine\Persistence\ObjectManager to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
Documentation introduced by
$nodeTranslation is of type object|null, but the function expects a object<Kunstmaan\NodeBun...Entity\NodeTranslation>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
71
        );
72
        $adminList->bindRequest($request);
73
74
        return array('nodetranslation' => $nodeTranslation, 'adminlist' => $adminList);
75
    }
76
77
    /**
78
     * The edit action will be used to edit a given submission.
79
     *
80
     * @param int $nodeTranslationId The node translation id
81
     * @param int $submissionId      The submission id
82
     *
83
     * @Route("/list/{nodeTranslationId}/{submissionId}", requirements={"nodeTranslationId" = "\d+", "submissionId" =
84
     *                                                    "\d+"}, name="KunstmaanFormBundle_formsubmissions_list_edit", methods={"GET", "POST"})
85
     * @Template("@KunstmaanForm/FormSubmissions/edit.html.twig")
86
     *
87
     * @return array
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use array<string,object|null>.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
88
     */
89
    public function editAction($nodeTranslationId, $submissionId)
90
    {
91
        $em = $this->getDoctrine()->getManager();
92
        $nodeTranslation = $em->getRepository(NodeTranslation::class)->find($nodeTranslationId);
93
        $formSubmission = $em->getRepository(FormSubmission::class)->find($submissionId);
94
        $request = $this->container->get('request_stack')->getCurrentRequest();
95
        $deletableFormsubmission = $this->getParameter('kunstmaan_form.deletable_formsubmissions');
96
97
        /** @var AdminList $adminList */
98
        $adminList = $this->get('kunstmaan_adminlist.factory')->createList(
99
            new FormSubmissionAdminListConfigurator($em, $nodeTranslation, $deletableFormsubmission)
0 ignored issues
show
Compatibility introduced by
$em of type object<Doctrine\Persistence\ObjectManager> is not a sub-type of object<Doctrine\ORM\EntityManager>. It seems like you assume a concrete implementation of the interface Doctrine\Persistence\ObjectManager to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
Documentation introduced by
$nodeTranslation is of type object|null, but the function expects a object<Kunstmaan\NodeBun...Entity\NodeTranslation>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
100
        );
101
        $adminList->bindRequest($request);
102
103
        return [
104
            'nodetranslation' => $nodeTranslation,
105
            'formsubmission' => $formSubmission,
106
            'adminlist' => $adminList,
107
        ];
108
    }
109
110
    /**
111
     * Export as CSV of all the form submissions for the given $nodeTranslationId
112
     *
113
     * @param int $nodeTranslationId
114
     *
115
     * @Route("/export/{nodeTranslationId}.{_format}", requirements={"nodeTranslationId" = "\d+","_format" =
116
     *                                                 "csv|xlsx|ods"}, name="KunstmaanFormBundle_formsubmissions_export", methods={"GET"})
117
     *
118
     * @return Response
119
     */
120
    public function exportAction($nodeTranslationId, $_format)
121
    {
122
        $em = $this->getDoctrine()->getManager();
123
        /** @var NodeTranslation $nodeTranslation */
124
        $nodeTranslation = $em->getRepository(NodeTranslation::class)->find($nodeTranslationId);
125
        $translator = $this->get('translator');
126
127
        /** @var ExportList $exportList */
128
        $configurator = new FormSubmissionExportListConfigurator($em, $nodeTranslation, $translator);
0 ignored issues
show
Compatibility introduced by
$em of type object<Doctrine\Persistence\ObjectManager> is not a sub-type of object<Doctrine\ORM\EntityManagerInterface>. It seems like you assume a child interface of the interface Doctrine\Persistence\ObjectManager to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
129
        $exportList = $this->get('kunstmaan_adminlist.factory')->createExportList($configurator);
130
131
        return $this->get('kunstmaan_adminlist.service.export')->getDownloadableResponse($exportList, $_format);
132
    }
133
134
    /**
135
     * @Route(
136
     *      "/{id}/delete",
137
     *      requirements={"id" = "\d+"},
138
     *      name="KunstmaanFormBundle_formsubmissions_delete",
139
     *      methods={"POST"}
140
     * )
141
     *
142
     * @param Request $request
143
     * @param int     $id
144
     *
145
     * @return RedirectResponse
146
     *
147
     * @throws AccessDeniedException
148
     */
149
    public function deleteAction(Request $request, $id)
150
    {
151
        $em = $this->getDoctrine()->getManager();
152
        $submission = $em->getRepository(FormSubmission::class)->find($id);
153
154
        $node = $em->getRepository(Node::class)->find($submission->getNode());
155
        $nt = $node->getNodeTranslation($request->getLocale());
156
157
        $this->denyAccessUnlessGranted(PermissionMap::PERMISSION_DELETE, $node);
158
159
        $url = $this->get('router')->generate(
160
            'KunstmaanFormBundle_formsubmissions_list',
161
            ['nodeTranslationId' => $nt->getId()]
162
        );
163
164
        $fields = $em->getRepository(FormSubmissionField::class)->findBy(['formSubmission' => $submission]);
165
166
        try {
167
            foreach ($fields as $field) {
168
                $em->remove($field);
169
            }
170
171
            $em->remove($submission);
0 ignored issues
show
Bug introduced by
It seems like $submission defined by $em->getRepository(\Kuns...sion::class)->find($id) on line 152 can also be of type null; however, Doctrine\Persistence\ObjectManager::remove() does only seem to accept object, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
172
            $em->flush();
173
174
            $this->addFlash(
175
                FlashTypes::SUCCESS,
176
                $this->get('translator')->trans('formsubmissions.delete.flash.success')
177
            );
178
        } catch (\Exception $e) {
179
            $this->get('logger')->error($e->getMessage());
180
            $this->addFlash(
181
                FlashTypes::DANGER,
182
                $this->get('translator')->trans('formsubmissions.delete.flash.error')
183
            );
184
        }
185
186
        return new RedirectResponse($url);
187
    }
188
}
189