Completed
Pull Request — master (#2)
by Andrew
05:50
created

AdminEstateController::estateEditAction()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 22
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

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

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
88
            $entityManager->persist($estate);
89
            $entityManager->flush();
90
            $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...
91
                ? 'admin_estate_new'
92
                : 'admin_estates';
93
            return $this->redirectToRoute($nextAction);
94
        }
95
        return $this->render('@App/admin/estate/new_estate.html.twig', array(
96
            'form' => $form->createView(),
97
            'estate' => $estate
98
        ));
99
    }
100
101
    /**
102
     * @Route("/estate/edit/{slug}", name="admin_estate_edit")
103
     * @Method({"GET", "POST"})
104
     */
105
    public function estateEditAction($slug, Request $request)
106
    {
107
        $estate = $this->getDoctrine()->getRepository('AppBundle:Estate')->getOneEstateWithAll($slug);
108
        $entityManager = $this->getDoctrine()->getManager();
109
        $this->denyAccessUnlessGranted('edit', $estate);
110
        $finalCategories = $this->container->get('app.final_category_finder')->findFinalCategories();
111
        $editForm = $this->createForm(EstateType::class, $estate, array(
112
            'categories_choices' => $finalCategories, 'isDeleteImages' => true));
113
        $deleteForm = $this->createDeleteForm($estate);
114
        $editForm->handleRequest($request);
115
        if ($editForm->isSubmitted() && $editForm->isValid()) {
116
            $estate = $this->get('app.file_manager')->fileManager($estate);
117
            $entityManager->persist($estate);
118
            $entityManager->flush();
119
            return $this->redirectToRoute('admin_estate_show', array('slug' => $estate->getSlug()));
120
        }
121
        return $this->render('@App/admin/estate/edit_estate.html.twig', array(
122
            'estate' => $estate,
123
            'edit_form' => $editForm->createView(),
124
            'delete_form' => $deleteForm->createView(),
125
        ));
126
    }
127
128
    /**
129
     * @Route("/estate/delete/{slug}", name="admin_estate_delete")
130
     * @Method("DELETE")
131
     * @Security("is_granted('remove', estate)")
132
     * @ParamConverter("estate", options={"mapping": {"slug": "slug"}})
133
     */
134 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...
135
    {
136
        $this->denyAccessUnlessGranted('remove', $estate);
137
        $form = $this->createDeleteForm($estate);
138
        $form->handleRequest($request);
139
        if ($form->isSubmitted() && $form->isValid()) {
140
            $entityManager = $this->getDoctrine()->getManager();
141
            $entityManager->remove($estate);
142
            $entityManager->flush();
143
        }
144
        return $this->redirectToRoute('admin_estates');
145
    }
146
147 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...
148
    {
149
        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...
150
            ->setAction($this->generateUrl('admin_estate_delete', array('slug' => $estate->getSlug())))
151
            ->setMethod('DELETE')
152
            ->getForm();
153
    }
154
155
    /**
156
     * @Route("/do_main_foto/{slug}/{id}", name="do_main_foto")
157
     * @Method("GET")
158
     * @ParamConverter("estate", class="AppBundle\Entity\Estate", options={"mapping": {"slug": "slug"}})
159
     * @ParamConverter("file", class="AppBundle\Entity\File", options={"mapping": {"id": "id"}})
160
     */
161
    public function doMainFotoAction(Estate $estate, File $file, Request $request)
162
    {
163
        $entityManager = $this->getDoctrine()->getManager();
164
        $estate->setMainFoto($file);
165
        $entityManager->flush();
166
167
        return $this->redirectToRoute('admin_estate_edit', array('slug' => $estate->getSlug()));
168
    }
169
170
}
171