Completed
Push — sf2.7 ( 7854b3...548f02 )
by Laurent
03:24
created

SubFamilyLogController::updateAction()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 1
Metric Value
c 2
b 1
f 1
dl 0
loc 25
rs 8.8571
cc 2
eloc 16
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 View Code Duplication
    public function createAction(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...
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->redirect(
92
                    $this->generateUrl(
93
                        'admin_subfamilylog_show',
94
                        array('slug' => $subfamilylog->getSlug())
95
                    )
96
                );
97
            } 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...
98
                $this->addFlash('info', 'gestock.settings.add_ok');
99
                $url = $this->redirect($this->generateUrl('admin_subfamilylog_new'));
100
            }
101
            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...
102
        }
103
104
        return array(
105
            'subfamilylog' => $subfamilylog,
106
            'form'   => $form->createView(),
107
        );
108
    }
109
110
    /**
111
     * Displays a form to edit an existing SubFamilyLog entity.
112
     *
113
     * @Route("/{slug}/edit", name="admin_subfamilylog_edit")
114
     * @Method("GET")
115
     * @Template()
116
     */
117 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...
118
    {
119
        $editForm = $this->createForm(new SubFamilyLogType(), $subfamilylog, array(
120
            'action' => $this->generateUrl(
121
                'admin_subfamilylog_update',
122
                array('slug' => $subfamilylog->getSlug())
123
            ),
124
            'method' => 'PUT',
125
        ));
126
        $deleteForm = $this->createDeleteForm($subfamilylog->getId(), 'admin_subfamilylog_delete');
127
128
        return array(
129
            'subfamilylog' => $subfamilylog,
130
            'edit_form'   => $editForm->createView(),
131
            'delete_form' => $deleteForm->createView(),
132
        );
133
    }
134
135
    /**
136
     * Edits an existing SubFamilyLog entity.
137
     *
138
     * @Route("/{slug}/update", name="admin_subfamilylog_update")
139
     * @Method("PUT")
140
     * @Template("AppBundle:SubFamilyLog:edit.html.twig")
141
     */
142
    public function updateAction(SubFamilyLog $subfamilylog, Request $request)
143
    {
144
        $editForm = $this->createForm(new SubFamilyLogType(), $subfamilylog, array(
145
            'action' => $this->generateUrl(
146
                'admin_subfamilylog_update',
147
                array('slug' => $subfamilylog->getSlug())
148
            ),
149
            'method' => 'PUT',
150
        ));
151
        if ($editForm->handleRequest($request)->isValid()) {
152
            $this->getDoctrine()->getManager()->flush();
153
154
            return $this->redirect($this->generateUrl(
155
                'admin_subfamilylog_edit',
156
                array('slug' => $subfamilylog->getSlug())
157
            ));
158
        }
159
        $deleteForm = $this->createDeleteForm($subfamilylog->getId(), 'admin_subfamilylog_delete');
160
161
        return array(
162
            'subfamilylog' => $subfamilylog,
163
            'edit_form'   => $editForm->createView(),
164
            'delete_form' => $deleteForm->createView(),
165
        );
166
    }
167
168
169
    /**
170
     * Save order.
171
     *
172
     * @Route("/order/{field}/{type}", name="admin_subfamilylog_sort")
173
     */
174
    public function sortAction($field, $type)
175
    {
176
        $this->setOrder('subfamilylog', $field, $type);
177
178
        return $this->redirect($this->generateUrl('admin_subfamilylog'));
179
    }
180
181
    /**
182
     * @param string $name  session name
183
     * @param string $field field name
184
     * @param string $type  sort type ("ASC"/"DESC")
185
     */
186
    protected function setOrder($name, $field, $type = 'ASC')
187
    {
188
        $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...
189
            'sort.' . $name,
190
            array('field' => $field, 'type' => $type)
191
        );
192
    }
193
194
    /**
195
     * @param  string $name
196
     * @return array
197
     */
198
    protected function getOrder($name)
199
    {
200
        $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...
201
202
        return $session->has('sort.' . $name) ? $session->get('sort.' . $name) : null;
203
    }
204
205
    /**
206
     * @param QueryBuilder $qb
207
     * @param string       $name
208
     */
209 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...
210
    {
211
        $alias = current($qb->getDQLPart('from'))->getAlias();
212
        if (is_array($order = $this->getOrder($name))) {
213
            $qb->orderBy($alias . '.' . $order['field'], $order['type']);
214
        }
215
    }
216
217
    /**
218
     * Deletes a SubFamilyLog entity.
219
     *
220
     * @Route("/{id}/delete", name="admin_subfamilylog_delete", requirements={"id"="\d+"})
221
     * @Method("DELETE")
222
     */
223
    public function deleteAction(SubFamilyLog $subfamilylog, Request $request)
224
    {
225
        $form = $this->createDeleteForm($subfamilylog->getId(), 'admin_subfamilylog_delete');
226
        if ($form->handleRequest($request)->isValid()) {
227
            $em = $this->getDoctrine()->getManager();
228
            $em->remove($subfamilylog);
229
            $em->flush();
230
        }
231
232
        return $this->redirect($this->generateUrl('admin_subfamilylog'));
233
    }
234
235
    /**
236
     * Create Delete form
237
     *
238
     * @param integer                       $id
239
     * @param string                        $route
240
     * @return \Symfony\Component\Form\Form
241
     */
242
    protected function createDeleteForm($id, $route)
243
    {
244
        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...
245
            ->setAction($this->generateUrl($route, array('id' => $id)))
246
            ->setMethod('DELETE')
247
            ->getForm()
248
        ;
249
    }
250
}
251