Completed
Pull Request — master (#58)
by Laurent
03:26
created

AbstractController::abstractCreateAction()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 29
Code Lines 20

Duplication

Lines 5
Ratio 17.24 %

Importance

Changes 5
Bugs 1 Features 0
Metric Value
c 5
b 1
f 0
dl 5
loc 29
rs 8.439
cc 6
eloc 20
nc 5
nop 4
1
<?php
2
/**
3
 * AbstractController controller des méthodes communes.
4
 *
5
 * PHP Version 5
6
 *
7
 * @author    Quétier Laurent <[email protected]>
8
 * @copyright 2014 Dev-Int GLSR
9
 * @license   http://opensource.org/licenses/gpl-license.php GNU Public License
10
 *
11
 * @version since 1.0.0
12
 *
13
 * @link      https://github.com/Dev-Int/glsr
14
 */
15
namespace AppBundle\Controller;
16
17
use Symfony\Component\HttpFoundation\Request;
18
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
19
use Doctrine\ORM\QueryBuilder;
20
21
/**
22
 * Abstract controller.
23
 *
24
 * @category Controller
25
 */
26
abstract class AbstractController extends Controller
27
{
28
    /**
29
     * Lists all items entity.
30
     *
31
     * @param string $entityName Name of Entity
32
     * @return array
33
     */
34
    public function abstractIndexAction($entityName)
35
    {
36
        $etm = $this->getDoctrine()->getManager();
37
        $entities = $etm->getRepository('AppBundle:'.$entityName)->findAll();
38
39
        return array(
40
            'entities'  => $entities,
41
            'ctEntity' => count($entities),
42
        );
43
    }
44
45
    /**
46
     * Finds and displays an item entity.
47
     *
48
     * @param Object $entity     Entity
49
     * @param string $entityName Name of Entity
50
     * @return array
51
     */
52
    public function abstractShowAction($entity, $entityName)
53
    {
54
        $deleteForm = $this->createDeleteForm($entity->getId(), $entityName.'_delete');
55
56
        return array(
57
            $entityName => $entity,
58
            'delete_form' => $deleteForm->createView(),
59
        );
60
    }
61
62
    /**
63
     * Displays a form to create a new item entity.
64
     *
65
     * @param string $entity     Entity
66
     * @param string $entityPath Path of Entity
67
     * @param string $typePath   Path of FormType
68
     * @return array
69
     */
70
    public function abstractNewAction($entity, $entityPath, $typePath)
71
    {
72
        $etm = $this->getDoctrine()->getManager();
73
        $ctEntity = count($etm->getRepository('AppBundle:'.$entity)->findAll());
74
        
75
        if ($entity === 'Company' || $entity === 'Settings' && $ctEntity >= 1) {
76
            $return = $this->redirectToRoute('_home');
1 ignored issue
show
Unused Code introduced by
$return is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
77
            $this->addFlash('danger', 'gestock.settings.'.strtolower($entity).'.add2');
78
        }
79
80
        $entityNew = $etm->getClassMetadata($entityPath)->newInstance();
81
        $form = $this->createForm(new $typePath(), $entityNew, array(
82
            'action' => $this->generateUrl(strtolower($entity).'_create'),
83
        ));
84
85
        $return = array(strtolower($entity) => $entityNew, 'form'   => $form->createView(),);
86
87
        return $return;
88
    }
89
90
    /**
91
     * Creates a new item entity.
92
     *
93
     * @param Request $request   Request in progress
94
     * @param string $entity     Entity
95
     * @param string $entityPath Path of Entity
96
     * @param string $typePath   Path of FormType
97
     * @return array
98
     */
99
    public function abstractCreateAction(Request $request, $entity, $entityPath, $typePath)
100
    {
101
        $param = array();
1 ignored issue
show
Unused Code introduced by
$param is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
102
        $etm = $this->getDoctrine()->getManager();
103
        $entityNew = $etm->getClassMetadata($entityPath)->newInstance();
104
        $form = $this->createForm(new $typePath(), $entityNew, array(
105
            'action' => $this->generateUrl(strtolower($entity).'_create'),
106
        ));
107
108
        if ($form->handleRequest($request)->isValid()) {
109
            $etm = $this->getDoctrine()->getManager();
110
            $etm->persist($entityNew);
111
            $etm->flush();
112
            $this->addFlash('info', 'gestock.create.ok');
113
114 View Code Duplication
            if ($entity === 'company' || $entity === 'settings' || $entity === 'tva') {
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...
115
                $param = array('id' => $entityNew->getId());
116
            } else {
117
                $param = array('slug' => $entityNew->getSlug());
118
            }
119
            $return = $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...
120
                ? $entity.'_new'
121
                : $entity.'_show';
122
123
            return $this->redirectToRoute($return, $param);
124
        }
125
126
        return array($entity => $entityNew, 'form' => $form->createView(),);
127
    }
128
129
    /**
130
     * Displays a form to edit an existing item entity.
131
     *
132
     * @param Object $entity     Entity
133
     * @param string $entityName Name of Entity
134
     * @param string $typePath   Path of FormType
135
     * @return array
136
     */
137
    public function abstractEditAction($entity, $entityName, $typePath)
138
    {
139 View Code Duplication
        if ($entityName === 'company' || $entityName === 'settings' || $entityName === 'tva') {
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...
140
            $param = array('id' => $entity->getId());
141
        } else {
142
            $param = array('slug' => $entity->getSlug());
143
        }
144
        $editForm = $this->createForm(new $typePath(), $entity, array(
145
            'action' => $this->generateUrl($entityName.'_update', $param),
146
            'method' => 'PUT',
147
        ));
148
        $deleteForm = $this->createDeleteForm($entity->getId(), $entityName.'_delete');
149
150
        return array(
151
            $entityName => $entity,
152
            'edit_form'   => $editForm->createView(),
153
            'delete_form' => $deleteForm->createView(),
154
        );
155
    }
156
157
    /**
158
     * Edits an existing item entity.
159
     *
160
     * @param Object $entity     Entity
161
     * @param Request $request   Request in progress
162
     * @param string $entityName Name of Entity
163
     * @param string $typePath   Path of FormType
164
     * @return array
165
     */
166
    public function abstractUpdateAction($entity, Request $request, $entityName, $typePath)
167
    {
168 View Code Duplication
        if ($entityName === 'company' || $entityName === 'settings' || $entityName === 'tva') {
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...
169
            $param = array('id' => $entity->getId());
170
        } else {
171
            $param = array('slug' => $entity->getSlug());
172
        }
173
        $editForm = $this->createForm(new $typePath(), $entity, array(
174
            'action' => $this->generateUrl($entityName.'_update', $param),
175
            'method' => 'PUT',
176
        ));
177
        if ($editForm->handleRequest($request)->isValid()) {
178
            $this->getDoctrine()->getManager()->flush();
179
            $this->addFlash('info', 'gestock.edit.ok');
180
181
            return $this->redirectToRoute($entityName.'_edit', $param);
182
        }
183
        $deleteForm = $this->createDeleteForm($entity->getId(), $entityName.'_delete');
184
185
        return array(
186
            $entityName => $entity,
187
            'edit_form'   => $editForm->createView(),
188
            'delete_form' => $deleteForm->createView(),
189
        );
190
    }
191
192
    /**
193
     * Deletes an item entity.
194
     *
195
     * @param Object $entity     Entity
196
     * @param Request $request   Request in progress
197
     * @param string $entityName Name of Entity
198
     * @return array
199
     */
200
    public function abstractDeleteAction($entity, Request $request, $entityName)
201
    {
202
        $form = $this->createDeleteForm($entity->getId(), $entityName.'_delete');
203
        if ($form->handleRequest($request)->isValid()) {
204
            $etm = $this->getDoctrine()->getManager();
205
            $etm->remove($entity);
206
            $etm->flush();
207
        }
208
    }
209
210
    /**
211
     * SetOrder for the SortAction in views.
212
     *
213
     * @param string $name  session name
214
     * @param string $field field name
215
     * @param string $type  sort type ("ASC"/"DESC")
216
     */
217
    protected function setOrder($name, $field, $type = 'ASC')
218
    {
219
        $this->getRequest()->getSession()->set('sort.'.$name, array('field' => $field, 'type' => $type));
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...
220
    }
221
222
    /**
223
     * GetOrder for the SortAction in views.
224
     *
225
     * @param string $name
226
     *
227
     * @return array
228
     */
229
    protected function getOrder($name)
230
    {
231
        $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...
232
233
        return $session->has('sort.' . $name) ? $session->get('sort.' . $name) : null;
234
    }
235
236
    /**
237
     * AddQueryBuilderSort for the SortAction in views.
238
     *
239
     * @param QueryBuilder $qb
240
     * @param string       $name
241
     */
242
    protected function addQueryBuilderSort(QueryBuilder $qb, $name)
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $qb. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
243
    {
244
        $alias = current($qb->getDQLPart('from'))->getAlias();
245
        if (is_array($order = $this->getOrder($name))) {
246
            $qb->orderBy($alias . '.' . $order['field'], $order['type']);
247
        }
248
    }
249
250
    /**
251
     * Create Delete form.
252
     *
253
     * @param int    $id
254
     * @param string $route
255
     *
256
     * @return \Symfony\Component\Form\Form
257
     */
258
    protected function createDeleteForm($id, $route)
259
    {
260
        return $this->createFormBuilder(null, array('attr' => array('id' => 'delete')))
261
            ->setAction($this->generateUrl($route, array('id' => $id)))
262
            ->setMethod('DELETE')
263
            ->getForm()
264
        ;
265
    }
266
267
    /**
268
     * Test Inventory.
269
     *
270
     * @return string|null
271
     */
272
    protected function testInventory()
273
    {
274
        $url = null;
275
        $etm = $this->getDoctrine()->getManager();
276
        $inventories = $etm->getRepository('AppBundle:Inventory')->getInventory();
277
278
        if (empty($inventories)) {
279
            $url = 'gs_install_st7';
280
        } else {
281
            foreach ($inventories as $inventory) {
282
                if ($inventory->getstatus() === 1 || $inventory->getStatus() === 2) {
283
                    $message = $this->get('translator')
284
                        ->trans('yet', array(), 'gs_inventories');
285
                    $this->addFlash('danger', $message);
286
                    $url = 'inventory';
287
                    break;
288
                }
289
            }
290
        }
291
292
        return $url;
293
    }
294
}
295