Completed
Push — sf2.7 ( 6f1cdc...5a2174 )
by Laurent
18:27
created

SubFamilyLogController::updateAction()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 22
Code Lines 14

Duplication

Lines 22
Ratio 100 %

Importance

Changes 3
Bugs 1 Features 1
Metric Value
c 3
b 1
f 1
dl 22
loc 22
rs 9.2
cc 2
eloc 14
nc 2
nop 2
1
<?php
2
3
namespace AppBundle\Controller\Settings\Divers;
4
5
use Symfony\Component\HttpFoundation\Request;
6
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
7
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
8
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
9
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
10
use AppBundle\Entity\SubFamilyLog;
11
use AppBundle\Form\Type\SubFamilyLogType;
12
13
/**
14
 * SubFamilyLog controller.
15
 *
16
 * @Route("/admin/settings/divers/subfamilylog")
17
 */
18
class SubFamilyLogController extends Controller
19
{
20
    /**
21
     * Lists all SubFamilyLog entities.
22
     *
23
     * @Route("/", name="admin_subfamilylog")
24
     * @Method("GET")
25
     * @Template()
26
     */
27
    public function indexAction(Request $request)
28
    {
29
        $em = $this->getDoctrine()->getManager();
30
        $qb = $em->getRepository('AppBundle:SubFamilyLog')->createQueryBuilder('s');
31
        $this->addQueryBuilderSort($qb, 'subfamilylog');
32
        $paginator = $this->get('knp_paginator')->paginate($qb, $request->query->get('page', 1), 20);
33
        
34
        return array(
35
            'paginator' => $paginator,
36
        );
37
    }
38
39
    /**
40
     * Finds and displays a SubFamilyLog entity.
41
     *
42
     * @Route("/{slug}/show", name="admin_subfamilylog_show")
43
     * @Method("GET")
44
     * @Template()
45
     */
46
    public function showAction(SubFamilyLog $subfamilylog)
47
    {
48
        $deleteForm = $this->createDeleteForm($subfamilylog->getId(), 'admin_subfamilylog_delete');
49
50
        return array(
51
            'subfamilylog' => $subfamilylog,
52
            'delete_form' => $deleteForm->createView(),
53
        );
54
    }
55
56
    /**
57
     * Displays a form to create a new SubFamilyLog entity.
58
     *
59
     * @Route("/new", name="admin_subfamilylog_new")
60
     * @Method("GET")
61
     * @Template()
62
     */
63
    public function newAction()
64
    {
65
        $subfamilylog = new SubFamilyLog();
66
        $form = $this->createForm(new SubFamilyLogType(), $subfamilylog);
67
68
        return array(
69
            'subfamilylog' => $subfamilylog,
70
            'form'   => $form->createView(),
71
        );
72
    }
73
74
    /**
75
     * Creates a new SubFamilyLog entity.
76
     *
77
     * @Route("/create", name="admin_subfamilylog_create")
78
     * @Method("POST")
79
     * @Template("AppBundle:SubFamilyLog:new.html.twig")
80
     */
81
    public function createAction(Request $request)
82
    {
83
        $subfamilylog = new SubFamilyLog();
84
        $form = $this->createForm(new SubFamilyLogType(), $subfamilylog);
85
        if ($form->handleRequest($request)->isValid()) {
86
            $em = $this->getDoctrine()->getManager();
87
            $em->persist($subfamilylog);
88
            $em->flush();
89
90
            if ($form->get('save')->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
                $url = $this->redirectToRoute('admin_subfamilylog_show', array('slug' => $subfamilylog->getSlug()));
92
            } elseif ($form->get('addmore')->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...
93
                $this->addFlash('info', 'gestock.settings.add_ok');
94
                $url = $this->redirectToRoute('admin_subfamilylog_new');
95
            }
96
            return $url;
0 ignored issues
show
Bug introduced by
The variable $url does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
97
        }
98
99
        return array(
100
            'subfamilylog' => $subfamilylog,
101
            'form'   => $form->createView(),
102
        );
103
    }
104
105
    /**
106
     * Displays a form to edit an existing SubFamilyLog entity.
107
     *
108
     * @Route("/{slug}/edit", name="admin_subfamilylog_edit")
109
     * @Method("GET")
110
     * @Template()
111
     */
112 View Code Duplication
    public function editAction(SubFamilyLog $subfamilylog)
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...
113
    {
114
        $editForm = $this->createForm(new SubFamilyLogType(), $subfamilylog, array(
115
            'action' => $this->generateUrl(
116
                'admin_subfamilylog_update',
117
                array('slug' => $subfamilylog->getSlug())
118
            ),
119
            'method' => 'PUT',
120
        ));
121
        $deleteForm = $this->createDeleteForm($subfamilylog->getId(), 'admin_subfamilylog_delete');
122
123
        return array(
124
            'subfamilylog' => $subfamilylog,
125
            'edit_form'   => $editForm->createView(),
126
            'delete_form' => $deleteForm->createView(),
127
        );
128
    }
129
130
    /**
131
     * Edits an existing SubFamilyLog entity.
132
     *
133
     * @Route("/{slug}/update", name="admin_subfamilylog_update")
134
     * @Method("PUT")
135
     * @Template("AppBundle:SubFamilyLog:edit.html.twig")
136
     */
137 View Code Duplication
    public function updateAction(SubFamilyLog $subfamilylog, 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...
138
    {
139
        $editForm = $this->createForm(new SubFamilyLogType(), $subfamilylog, array(
140
            'action' => $this->generateUrl(
141
                'admin_subfamilylog_update',
142
                array('slug' => $subfamilylog->getSlug())
143
            ),
144
            'method' => 'PUT',
145
        ));
146
        if ($editForm->handleRequest($request)->isValid()) {
147
            $this->getDoctrine()->getManager()->flush();
148
149
            return $this->redirectToRoute('admin_subfamilylog_edit', array('slug' => $subfamilylog->getSlug()));
150
        }
151
        $deleteForm = $this->createDeleteForm($subfamilylog->getId(), 'admin_subfamilylog_delete');
152
153
        return array(
154
            'subfamilylog' => $subfamilylog,
155
            'edit_form'   => $editForm->createView(),
156
            'delete_form' => $deleteForm->createView(),
157
        );
158
    }
159
160
161
    /**
162
     * Save order.
163
     *
164
     * @Route("/order/{field}/{type}", name="admin_subfamilylog_sort")
165
     */
166
    public function sortAction($field, $type)
167
    {
168
        $this->setOrder('subfamilylog', $field, $type);
169
170
        return $this->redirectToRoute('admin_subfamilylog');
171
    }
172
173
    /**
174
     * @param string $name  session name
175
     * @param string $field field name
176
     * @param string $type  sort type ("ASC"/"DESC")
177
     */
178
    protected function setOrder($name, $field, $type = 'ASC')
179
    {
180
        $this->getRequest()->getSession()->set(
0 ignored issues
show
Deprecated Code introduced by
The method Symfony\Bundle\Framework...ontroller::getRequest() has been deprecated with message: since version 2.4, to be removed in 3.0. Ask Symfony to inject the Request object into your controller method instead by type hinting it in the method's signature.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

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

Loading history...
181
            'sort.' . $name,
182
            array('field' => $field, 'type' => $type)
183
        );
184
    }
185
186
    /**
187
     * @param  string $name
188
     * @return array
189
     */
190
    protected function getOrder($name)
191
    {
192
        $session = $this->getRequest()->getSession();
0 ignored issues
show
Deprecated Code introduced by
The method Symfony\Bundle\Framework...ontroller::getRequest() has been deprecated with message: since version 2.4, to be removed in 3.0. Ask Symfony to inject the Request object into your controller method instead by type hinting it in the method's signature.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

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

Loading history...
193
194
        return $session->has('sort.' . $name) ? $session->get('sort.' . $name) : null;
195
    }
196
197
    /**
198
     * @param QueryBuilder $qb
199
     * @param string       $name
200
     */
201 View Code Duplication
    protected function addQueryBuilderSort(\Doctrine\ORM\QueryBuilder $qb, $name)
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...
202
    {
203
        $alias = current($qb->getDQLPart('from'))->getAlias();
204
        if (is_array($order = $this->getOrder($name))) {
205
            $qb->orderBy($alias . '.' . $order['field'], $order['type']);
206
        }
207
    }
208
209
    /**
210
     * Deletes a SubFamilyLog entity.
211
     *
212
     * @Route("/{id}/delete", name="admin_subfamilylog_delete", requirements={"id"="\d+"})
213
     * @Method("DELETE")
214
     */
215
    public function deleteAction(SubFamilyLog $subfamilylog, Request $request)
216
    {
217
        $form = $this->createDeleteForm($subfamilylog->getId(), 'admin_subfamilylog_delete');
218
        if ($form->handleRequest($request)->isValid()) {
219
            $em = $this->getDoctrine()->getManager();
220
            $em->remove($subfamilylog);
221
            $em->flush();
222
        }
223
224
        return $this->redirectToRoute('admin_subfamilylog');
225
    }
226
227
    /**
228
     * Create Delete form
229
     *
230
     * @param integer                       $id
231
     * @param string                        $route
232
     * @return \Symfony\Component\Form\Form
233
     */
234
    protected function createDeleteForm($id, $route)
235
    {
236
        return $this->createFormBuilder(null, array('attr' => array('id' => 'delete')))
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...
237
            ->setAction($this->generateUrl($route, array('id' => $id)))
238
            ->setMethod('DELETE')
239
            ->getForm()
240
        ;
241
    }
242
}
243