Completed
Pull Request — master (#2)
by Kate
03:29
created

AdminEstateController::estateEditAction()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 19
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 2
Bugs 1 Features 2
Metric Value
c 2
b 1
f 2
dl 0
loc 19
ccs 0
cts 19
cp 0
rs 9.4285
cc 3
eloc 15
nc 2
nop 2
crap 12
1
<?php
2
3
namespace AppBundle\Controller\Admin;
4
5
use AppBundle\Entity\Estate;
6
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
7
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
8
use Symfony\Component\HttpFoundation\Request;
9
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
10
use AppBundle\Form\EstateType;
11
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
12
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
13
use AppBundle\Utils;
14
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
15
16
17
/**
18
 * @Security("has_role('ROLE_MANAGER')")
19
 * @Route("/admin")
20
 */
21
class AdminEstateController extends Controller
22
{
23
    /**
24
     * @Route("/", name="admin_index")
25
     */
26
    public function indexAction(Request $request)
27
    {
28
        $users = $this->getDoctrine()->getRepository('AppBundle:User')->findAll();
29
        $districts = $this->getDoctrine()->getRepository('AppBundle:District')->findAll();
30
        $comments = $this->getDoctrine()->getRepository('AppBundle:Comment')->getDisabledComments();
31
        $estates = $this->getDoctrine()->getRepository('AppBundle:Estate')->findAll();
32
        return $this->render('AppBundle::admin/index.html.twig', array('count_disabled_comments' => count($comments),
33
            'count_estates' => count($estates),
34
            'count_users' => count($users),
35
            'count_districts' => count($districts),
36
            'base_dir' => realpath($this->getParameter('kernel.root_dir') . '/..'),
37
        ));
38
    }
39
40
    /**
41
     * @Route("/estates", name="admin_estates")
42
     * @Method("GET")
43
     */
44 View Code Duplication
    public function estatesAction(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...
45
    {
46
        $estates = $this->getDoctrine()->getRepository('AppBundle:Estate')->findAll();
47
        $paginator = $this->get('knp_paginator');
48
        $pagination = $paginator->paginate(
49
            $estates,
50
            $request->query->getInt('page', 1),
51
            10
52
        );
53
        return $this->render('@App/admin/estate/estates.html.twig', array('pagination' => $pagination));
54
    }
55
56
    /**
57
     * @Route("/estate/show/{slug}", name="admin_estate_show")
58
     * @Method("GET")
59
     * @ParamConverter("estate", options={"mapping": {"slug": "slug"}})
60
     */
61 View Code Duplication
    public function estateShowAction(Estate $estate, 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...
62
    {
63
        $deleteForm = $this->createDeleteForm($estate);
64
        return $this->render('@App/admin/estate/show_estate.html.twig', array(
65
            'estate'        => $estate,
66
            'delete_form' => $deleteForm->createView(),
67
        ));
68
    }
69
70
    /**
71
     * @Route("/estate/new", name="admin_estate_new")
72
     * @Method({"GET", "POST"})
73
     * @Security("is_granted('create', estate)")
74
     */
75
    public function newEstateAction(Request $request)
76
    {
77
        $entityManager = $this->getDoctrine()->getManager();
78
        $estate = new Estate();
79
        $finalCategories = $this->container->get('app.final_category_finder')->findFinalCategories();
80
        $this->denyAccessUnlessGranted('create', $estate);
81
        $form = $this->createForm(EstateType::class, $estate, array('categories_choices' => $finalCategories))
82
        ->add('saveAndCreateNew', SubmitType::class);
83
        $form->handleRequest($request);
84
        if ($form->isSubmitted() && $form->isValid()) {
85
            $estate = $this->get('app.file_manager')->fileManager($estate);
86
            $entityManager->persist($estate);
87
            $entityManager->flush();
88
            $nextAction = $form->get('saveAndCreateNew')->isClicked()
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Form\FormInterface as the method isClicked() does only exist in the following implementations of said interface: Symfony\Component\Form\SubmitButton.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
89
                ? 'admin_estate_new'
90
                : 'admin_estates';
91
            return $this->redirectToRoute($nextAction);
92
        }
93
        return $this->render('@App/admin/estate/new_estate.html.twig', array(
94
            'estate' => $estate,
95
            'form' => $form->createView(),
96
        ));
97
    }
98
99
    /**
100
     * @Route("/estate/edit/{slug}", name="admin_estate_edit")
101
     * @Method({"GET", "POST"})
102
     * @Security("is_granted('edit', estate)")
103
     * @ParamConverter("estate", options={"mapping": {"slug": "slug"}})
104
     */
105
    public function estateEditAction(Estate $estate, Request $request)
106
    {
107
        $entityManager = $this->getDoctrine()->getManager();
108
        $this->denyAccessUnlessGranted('edit', $estate);
109
        $editForm = $this->createForm(EstateType::class, $estate);
110
        $deleteForm = $this->createDeleteForm($estate);
111
        $editForm->handleRequest($request);
112
        if ($editForm->isSubmitted() && $editForm->isValid()) {
113
            $estate = $this->get('app.file_manager')->fileManager($estate);
114
            $entityManager->persist($estate);
115
            $entityManager->flush();
116
            return $this->redirectToRoute('admin_estate_show', array('slug' => $estate->getSlug()));
117
        }
118
        return $this->render('@App/admin/estate/edit_estate.html.twig', array(
119
            'estate'        => $estate,
120
            'edit_form'   => $editForm->createView(),
121
            'delete_form' => $deleteForm->createView(),
122
        ));
123
    }
124
125
    /**
126
     * @Route("/estate/delete/{slug}", name="admin_estate_delete")
127
     * @Method("DELETE")
128
     * @Security("is_granted('remove', estate)")
129
     * @ParamConverter("estate", options={"mapping": {"slug": "slug"}})
130
131
     */
132 View Code Duplication
    public function estateDeleteAction(Request $request, Estate $estate)
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...
133
    {
134
        $this->denyAccessUnlessGranted('delete', $estate);
135
        $form = $this->createDeleteForm($estate);
136
        $form->handleRequest($request);
137
        if ($form->isSubmitted() && $form->isValid()) {
138
            $entityManager = $this->getDoctrine()->getManager();
139
            $entityManager->remove($estate);
140
            $entityManager->flush();
141
        }
142
        return $this->redirectToRoute('admin_estates');
143
    }
144
145 View Code Duplication
    private function createDeleteForm(Estate $estate)
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...
146
    {
147
        return $this->createFormBuilder()
0 ignored issues
show
Bug introduced by
The method getForm() does not exist on Symfony\Component\Form\FormConfigBuilder. Did you maybe mean getFormConfig()?

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...
148
            ->setAction($this->generateUrl('admin_estate_delete', array('slug' => $estate->getSlug())))
149
            ->setMethod('DELETE')
150
            ->getForm()
151
            ;
152
    }
153
}
154