Completed
Push — develop ( bb7f99...d04bd8 )
by Victor
03:30
created

CommentController   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 121
Duplicated Lines 7.44 %

Coupling/Cohesion

Components 1
Dependencies 8

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 8
c 2
b 0
f 0
lcom 1
cbo 8
dl 9
loc 121
ccs 0
cts 61
cp 0
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B roleAction() 0 58 5
B editCommentAction() 9 29 3

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\Comment;
6
use AppBundle\Form\Type\CommentAdminType;
7
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
8
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
9
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
10
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
11
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
12
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
13
use Symfony\Component\HttpFoundation\Request;
14
15
/**
16
 * Class CommentController
17
 * @package AppBundle\Controller\Admin
18
 * @Route("/admin")
19
 */
20
class CommentController extends Controller
21
{
22
    /**
23
     * @param Request $request
24
     * @param $page
25
     * @Method({"GET", "POST"})
26
     * @Route("/comments/{pager}/{page}", name="commentsAdmin",
27
     *     defaults={"pager": "page", "page": 1},
28
     *     requirements={
29
     *          "pager": "page",
30
     *          "page": "[1-9]\d*",
31
     *     })
32
     * @Template("AppBundle:admin:comments.html.twig")
33
     *
34
     * @return Response
35
     */
36
    public function roleAction(Request $request, $page = 1)
37
    {
38
        $em = $this->getDoctrine()->getManager();
39
        $comments = $em->getRepository("AppBundle:Comment")
40
            ->getRecentComments($page, 10);
41
42
        $formData = $comments->getQuery()->getResult();
43
44
        $form = $this->createFormBuilder($formData)
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...
45
            ->setAction($this->generateUrl('commentsAdmin'))
46
            ->setMethod('POST')
47
            ->add('comments', ChoiceType::class, array(
48
                    'choices'           => $formData,
49
                    'choices_as_values' => true,
50
                    'expanded'          => true,
51
                    'multiple'          => true,
52
                    'choice_value'      => 'id',
53
                    'label'             => false,
54
                    'choice_label'      => 'id',
55
                )
56
            )
57
            ->add('delete', SubmitType::class, array(
58
                    'label'     => 'Delete',
59
                    'attr'      => [
60
                        'class' => 'btn btn-xs btn-danger'
61
                    ],
62
                )
63
            )
64
            ->getForm();
65
66
        if ($request->getMethod() == 'POST') {
67
            $form->handleRequest($request);
68
            if ($form->isValid()) {
69
                $data = $form->getData();
70
                foreach ($data['comments'] as $comment) {
71
                    $em->remove($comment);
72
                }
73
74
                try {
75
                    $em->flush();
76
                } catch (\Exception $e) {
77
                    return $this->render(
78
                        'AppBundle:admin:failure.html.twig',
79
                        array(
80
                            'message' => 'Deleting record is failed. Because record has relation to other records or another reasons.',
81
                        )
82
                    );
83
                }
84
85
                return $this->redirectToRoute('commentsAdmin');
86
            }
87
        }
88
89
        return [
90
            'comments'  => $comments,
91
            'delete' => $form->createView(),
92
        ];
93
    }
94
95
    /**
96
     * @param $id
97
     * @param $action
98
     * @param Request $request
99
     * @Route("/comment/{action}/{id}", name="commentEdit",
100
     *     defaults={"id": 0},
101
     *     requirements={
102
     *      "action": "edit",
103
     *      "id": "\d+"
104
     *     })
105
     * @Method({"GET", "POST"})
106
     * @Template("AppBundle:admin/form:comment.html.twig")
107
     *
108
     * @return Response
109
     */
110
    public function editCommentAction($id, $action, Request $request)
111
    {
112
        $em = $this->getDoctrine()->getManager();
113
        $comment = $em->getRepository('AppBundle:Comment')
114
            ->find($id);
115
        $title = 'Edit comment id: "'.$id. '" for article "' . $comment->getArticle()->getTitle() . '"';
116
117
        $form = $this->createForm(CommentAdminType::class, $comment, [
118
            'em' => $em,
119
            'action' => $this->generateUrl('commentEdit', ['action' => $action, 'id' => $id]),
120
            'method' => Request::METHOD_POST,
121
        ])
122
            ->add('save', SubmitType::class, array('label' => 'Save'));
123
124 View Code Duplication
        if ($request->getMethod() == 'POST') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
125
            $form->handleRequest($request);
126
            if ($form->isValid()) {
127
                $em->persist($comment);
128
                $em->flush();
129
130
                return $this->redirectToRoute('commentsAdmin');
131
            }
132
        }
133
134
        return [
135
            'title' => $title,
136
            'form'  => $form->createView(),
137
        ];
138
    }
139
140
}
141