Completed
Push — master ( fe7869...b5829e )
by Laurent
02:59
created

AbstractController::abstractNewAction()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 25
rs 8.439
cc 5
eloc 16
nc 4
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\Component\HttpFoundation\Session\Session;
19
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
20
use Doctrine\ORM\QueryBuilder;
21
22
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
23
24
/**
25
 * Abstract controller.
26
 *
27
 * @category Controller
28
 */
29
abstract class AbstractController extends Controller
30
{
31
    /**
32
     * Lists all items entity.
33
     *
34
     * @param string $entityName Name of Entity
35
     * @param \Symfony\Component\HttpFoundation\Request $request Sort request
36
     * @return array
37
     */
38
    public function abstractIndexAction($entityName, Request $request = null)
39
    {
40
        $etm = $this->getDoctrine()->getManager();
41
        $paginator = '';
42
        $entities = $this->getEntity($entityName, $etm);
43
        
44
        if ($request !== null) {
45
            $item = $this->container->getParameter('knp_paginator.page_range');
46
            $this->addQueryBuilderSort($entities, strtolower($entityName));
47
            $paginator = $this->get('knp_paginator')->paginate($entities, $request->query->get('page', 1), $item);
48
        }
49
50
        return array('entities'  => $entities, 'ctEntity' => count($entities), 'paginator' => $paginator,);
51
    }
52
53
    /**
54
     * Get the entity
55
     *
56
     * @param string $entityName Name of Entity
57
     * @param \Doctrine\Common\Persistence\ObjectManager $etm ObjectManager instances
58
     * @return type
59
     */
60
    protected function getEntity($entityName, $etm)
61
    {
62
        $roles = ['ROLE_ADMIN', 'ROLE_SUPER_ADMIN'];
63
        switch ($entityName) {
64 View Code Duplication
            case 'Article':
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...
65
                if ($this->getUser() !== null && in_array($this->getUser()->getRoles()[0], $roles)) {
66
                    $entities = $etm->getRepository('AppBundle:'.$entityName)->getAllArticles();
67
                } else {
68
                    $entities = $etm->getRepository('AppBundle:'.$entityName)->getArticles();
69
                }
70
                break;
71 View Code Duplication
            case 'Supplier':
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...
72
                if ($this->getUser() !== null && in_array($this->getUser()->getRoles()[0], $roles)) {
73
                    $entities = $etm->getRepository('AppBundle:'.$entityName)->getAllSuppliers();
74
                } else {
75
                    $entities = $etm->getRepository('AppBundle:'.$entityName)->getSuppliers();
76
                }
77
                break;
78
            case 'User':
79
                $entities = $etm->getRepository('AppBundle:'.$entityName)->getUsers();
80
                break;
81
            case 'FamilyLog':
82
                $entities = $etm->getRepository('AppBundle:'.$entityName)->childrenHierarchy();
83
                break;
84
            case 'UnitStorage':
85
                $entities = $etm->getRepository('AppBundle:'.$entityName)->createQueryBuilder('u');
86
                break;
87
            default:
88
                $entities = $etm->getRepository('AppBundle:'.$entityName)->findAll();
89
        }
90
        return $entities;
91
    }
92
93
    /**
94
     * Finds and displays an item entity.
95
     *
96
     * @param Object $entity     Entity
97
     * @param string $entityName Name of Entity
98
     * @return array
99
     */
100
    public function abstractShowAction($entity, $entityName)
101
    {
102
        $deleteForm = $this->createDeleteForm($entity->getId(), $entityName.'_delete');
103
104
        return array(
105
            $entityName => $entity,
106
            'delete_form' => $deleteForm->createView(),
107
        );
108
    }
109
110
    /**
111
     * Displays a form to create a new item entity.
112
     *
113
     * @param string      $entity     Entity
114
     * @param string      $entityPath Path of Entity
115
     * @param string      $typePath   Path of FormType
116
     * @param string|null $options    Options of Form
117
     * @return array
118
     */
119
    public function abstractNewAction($entity, $entityPath, $typePath, $options = null)
120
    {
121
        $etm = $this->getDoctrine()->getManager();
122
        $ctEntity = count($etm->getRepository('AppBundle:'.$entity)->findAll());
123
        
124
        if ($entity === 'Company' || $entity === 'Settings' && $ctEntity >= 1) {
125
            $return = $this->redirectToRoute('_home');
126
            $this->addFlash('danger', 'gestock.settings.'.strtolower($entity).'.add2');
127
        }
128
129
        $entityNew = $etm->getClassMetadata($entityPath)->newInstance();
130
        if ($entity === 'User') {
131
            $form = $this->createForm($typePath, $entityNew, array(
132
                'action' => $this->generateUrl(strtolower($entity).'_create'),
133
                'roles' => $options['roles'],
134
            ));
135
        } else {
136
            $form = $this->createForm($typePath, $entityNew, array(
137
                'action' => $this->generateUrl(strtolower($entity).'_create'),
138
            ));
139
        }
140
        $return = array(strtolower($entity) => $entityNew, 'form'   => $form->createView(),);
141
142
        return $return;
143
    }
144
145
    /**
146
     * Creates a new item entity.
147
     *
148
     * @param Request $request   Request in progress
149
     * @param string $entity     Entity <i>First letter Upper</i>
150
     * @param string $entityPath Path of Entity
151
     * @param string $typePath   Path of FormType
152
     * @return array
153
     */
154
    public function abstractCreateAction(Request $request, $entity, $entityPath, $typePath)
155
    {
156
        $param = array();
157
        $etm = $this->getDoctrine()->getManager();
158
        $entityNew = $etm->getClassMetadata($entityPath)->newInstance();
159
        $form = $this->createForm($typePath, $entityNew, array(
160
            'action' => $this->generateUrl(strtolower($entity).'_create'),
161
        ));
162
        $form->handleRequest($request);
163
        $return = [$entity => $entityNew, 'form' => $form->createView(),];
164
165
        if ($form->isValid()) {
166
            $etm = $this->getDoctrine()->getManager();
167
            $etm->persist($entityNew);
168
            $etm->flush();
169
            $this->addFlash('info', 'gestock.create.ok');
170
171
            $param = $this->testReturnParam($entityNew, strtolower($entity));
172
            $route = $form->get('addmore')->isClicked() ? strtolower($entity).'_new' : strtolower($entity).'_show';
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...
173
174
            $return = $this->redirectToRoute($route, $param);
175
        }
176
177
        return $return;
178
    }
179
180
    /**
181
     * Displays a form to edit an existing item entity.
182
     *
183
     * @param Object $entity     Entity
184
     * @param string $entityName Name of Entity
185
     * @param string $typePath   Path of FormType
186
     * @return array
187
     */
188
    public function abstractEditAction($entity, $entityName, $typePath)
189
    {
190
        $param = $this->testReturnParam($entity, $entityName);
191
        $editForm = $this->createForm($typePath, $entity, array(
192
            'action' => $this->generateUrl($entityName.'_update', $param),
193
            'method' => 'PUT',
194
        ));
195
        if ($entityName === 'group') {
196
            $this->addRoles($editForm, $entity);
197
        }
198
        $deleteForm = $this->createDeleteForm($entity->getId(), $entityName.'_delete');
199
200
        return array(
201
            $entityName => $entity,
202
            'edit_form'   => $editForm->createView(),
203
            'delete_form' => $deleteForm->createView(),
204
        );
205
    }
206
207
    /**
208
     * Edits an existing item entity.
209
     *
210
     * @param Object $entity     Entity
211
     * @param Request $request   Request in progress
212
     * @param string $entityName Name of Entity
213
     * @param string $typePath   Path of FormType
214
     * @return array
215
     */
216
    public function abstractUpdateAction($entity, Request $request, $entityName, $typePath)
217
    {
218
        $param = $this->testReturnParam($entity, $entityName);
219
        $editForm = $this->createForm($typePath, $entity, array(
220
            'action' => $this->generateUrl($entityName.'_update', $param),
221
            'method' => 'PUT',
222
        ));
223
        if ($entityName === 'group') {
224
            $this->addRoles($editForm, $entity);
225
        }
226
227
        $deleteForm = $this->createDeleteForm($entity->getId(), $entityName.'_delete');
228
229
        $return = array(
230
            $entityName => $entity,
231
            'edit_form'   => $editForm->createView(),
232
            'delete_form' => $deleteForm->createView(),
233
        );
234
235
        if ($editForm->handleRequest($request)->isValid()) {
236
            $this->getDoctrine()->getManager()->flush();
237
            $this->addFlash('info', 'gestock.edit.ok');
238
239
            $return = $this->redirectToRoute($entityName.'_edit', $param);
240
        }
241
242
        return $return;
243
    }
244
245
    /**
246
     * Deletes an item entity.
247
     *
248
     * @param Object $entity     Entity
249
     * @param Request $request   Request in progress
250
     * @param string $entityName Name of Entity
251
     * @return array
252
     */
253
    public function abstractDeleteAction($entity, Request $request, $entityName)
254
    {
255
        $form = $this->createDeleteForm($entity->getId(), $entityName.'_delete');
256
        if ($form->handleRequest($request)->isValid()) {
257
            $etm = $this->getDoctrine()->getManager();
258
            $etm->remove($entity);
259
            $etm->flush();
260
        }
261
    }
262
263
    private function testReturnParam($entity, $entityName)
264
    {
265
        $entityArray = ['company', 'settings', 'group', 'tva'];
266
        if (in_array($entityName, $entityArray, true)) {
267
            $param = array('id' => $entity->getId());
268
        } else {
269
            $param = array('slug' => $entity->getSlug());
270
        }
271
272
        return $param;
273
    }
274
275
    /**
276
     * SetOrder for the SortAction in views.
277
     *
278
     * @param string $name   session name
279
     * @param string $entity entity name
280
     * @param string $field  field name
281
     * @param string $type   sort type ("ASC"/"DESC")
282
     */
283
    protected function setOrder($name, $entity, $field, $type = 'ASC')
284
    {
285
        $session = new Session();
286
287
        $session->set('sort.'.$name, array('entity' => $entity, 'field' => $field, 'type' => $type));
288
    }
289
290
    /**
291
     * GetOrder for the SortAction in views.
292
     *
293
     * @param string $name session name
294
     *
295
     * @return array
296
     */
297
    protected function getOrder($name)
298
    {
299
        $session = new Session();
300
301
        return $session->has('sort.' . $name) ? $session->get('sort.' . $name) : null;
302
    }
303
304
    /**
305
     * AddQueryBuilderSort for the SortAction in views.
306
     *
307
     * @param QueryBuilder $qbd
308
     * @param string       $name
309
     */
310
    protected function addQueryBuilderSort(QueryBuilder $qbd, $name)
311
    {
312
        $alias = '';
313
        if (is_array($order = $this->getOrder($name))) {
314
            if ($name !== $order['entity']) {
315
                $rootAlias = current($qbd->getDQLPart('from'))->getAlias();
316
                $join = current($qbd->getDQLPart('join'));
317
                foreach ($join as $item) {
318
                    if ($item->getJoin() === $rootAlias.'.'.$order['entity']) {
319
                        $alias = $item->getAlias();
320
                    }
321
                }
322
            } else {
323
                $alias = current($qbd->getDQLPart('from'))->getAlias();
324
            }
325
            $qbd->orderBy($alias . '.' . $order['field'], $order['type']);
326
        }
327
    }
328
329
    /**
330
     * Create Delete form.
331
     *
332
     * @param int    $id
333
     * @param string $route
334
     *
335
     * @return \Symfony\Component\Form\Form
336
     */
337
    protected function createDeleteForm($id, $route)
338
    {
339
        return $this->createFormBuilder(null, array('attr' => array('id' => 'delete')))
340
            ->setAction($this->generateUrl($route, array('id' => $id)))
341
            ->setMethod('DELETE')
342
            ->getForm()
343
        ;
344
    }
345
346
    /**
347
     * Array of file (`pdf`) layout.
348
     *
349
     * @param string $date File date
350
     * @param string $title File title
351
     * @return array<string,integer|string|boolean>
352
     */
353
    protected function getArray($date, $title)
354
    {
355
        $array = array(
356
            'margin-top' => 15,
357
            'header-spacing' => 5,
358
            'header-font-size' => 8,
359
            'header-left' => 'G.L.S.R.',
360
            'header-center' => $title,
361
            'header-right' => $date,
362
            'header-line' => true,
363
            'margin-bottom' => 15,
364
            'footer-spacing' => 5,
365
            'footer-font-size' => 8,
366
            'footer-left' => 'GLSR &copy 2014 and beyond.',
367
            'footer-right' => 'Page [page]/[toPage]',
368
            'footer-line' => true,
369
        );
370
        return $array;
371
    }
372
373
    /**
374
     * Get the existing roles
375
     *
376
     * @return array Array of roles
377
     */
378
    private function getExistingRoles()
379
    {
380
        $roleHierarchy = $this->container->getParameter('security.role_hierarchy.roles');
381
        $roles = array_keys($roleHierarchy);
382
        $theRoles = array();
383
384
        foreach ($roles as $role) {
385
            $theRoles[$role] = $role;
386
        }
387
        return $theRoles;
388
    }
389
390
    /**
391
     * Add roles to form
392
     *
393
     * @param \Symfony\Component\Form\Form  $form  The form in which to insert the roles
394
     * @param \AppBundle\Entity\Group       $group The entity to deal
395
     * @return \Symfony\Component\Form\Form The form
396
     */
397
    private function addRoles($form, $group)
398
    {
399
        $form->add('roles', ChoiceType::class, array(
400
            'choices' => $this->getExistingRoles(),
401
            'choices_as_values' => true,
402
            'data' => $group->getRoles(),
403
            'label' => 'Roles',
404
            'expanded' => true,
405
            'multiple' => true,
406
            'mapped' => true,
407
        ));
408
409
        return $form;
410
    }
411
}
412