Completed
Push — master ( b7c24f...5fe0cf )
by Laurent
03:42
created

AbstractController::getEntity()   D

Complexity

Conditions 10
Paths 10

Size

Total Lines 33
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 33
rs 4.8196
cc 10
eloc 29
nc 10
nop 2

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Common\Persistence\ObjectManager;
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 && is_array($entities) === false && $entities !== 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
     * Finds and displays an item entity.
55
     *
56
     * @param Object $entity     Entity
57
     * @param string $entityName Name of Entity
58
     * @return array
59
     */
60
    public function abstractShowAction($entity, $entityName)
61
    {
62
        $deleteForm = $this->createDeleteForm($entity->getId(), $entityName.'_delete');
63
64
        return array(
65
            $entityName => $entity,
66
            'delete_form' => $deleteForm->createView(),
67
        );
68
    }
69
70
    /**
71
     * Displays a form to create a new item entity.
72
     *
73
     * @param string      $entity     Entity
74
     * @param string      $entityPath Path of Entity
75
     * @param string      $typePath   Path of FormType
76
     * @return array
77
     */
78
    public function abstractNewAction($entity, $entityPath, $typePath)
79
    {
80
        $etm = $this->getDoctrine()->getManager();
81
        $ctEntity = count($etm->getRepository('AppBundle:'.$entity)->findAll());
82
        
83
        if ($entity === 'Company' || $entity === 'Settings' && $ctEntity >= 1) {
84
            $return = $this->redirectToRoute('_home');
85
            $this->addFlash('danger', 'gestock.settings.'.strtolower($entity).'.add2');
86
        }
87
88
        $entityNew = $etm->getClassMetadata($entityPath)->newInstance();
89
        $form = $this->createForm($typePath, $entityNew, array(
90
            'action' => $this->generateUrl(strtolower($entity).'_create'),
91
        ));
92
93
        if ($entity === 'Group') {
94
            $this->addRoles($form, $entityNew);
95
        }
96
        $return = array(strtolower($entity) => $entityNew, 'form'   => $form->createView(),);
97
98
        return $return;
99
    }
100
101
    /**
102
     * Creates a new item entity.
103
     *
104
     * @param Request $request   Request in progress
105
     * @param string $entity     Entity <i>First letter Upper</i>
106
     * @param string $entityPath Path of Entity
107
     * @param string $typePath   Path of FormType
108
     * @return array
109
     */
110
    public function abstractCreateAction(Request $request, $entity, $entityPath, $typePath)
111
    {
112
        $param = array();
113
        $etm = $this->getDoctrine()->getManager();
114
        $entityNew = $etm->getClassMetadata($entityPath)->newInstance();
115
        $form = $this->createForm($typePath, $entityNew, array(
116
            'action' => $this->generateUrl(strtolower($entity).'_create'),
117
        ));
118
        if ($entity === 'Group') {
119
            $this->addRoles($form, $entityNew);
120
        }
121
        $form->handleRequest($request);
122
        $return = [$entity => $entityNew, 'form' => $form->createView(),];
123
124
        if ($form->isValid()) {
125
            $etm = $this->getDoctrine()->getManager();
126
            $etm->persist($entityNew);
127
            $etm->flush();
128
129
            $param = $this->get('app.helper.controller')->testReturnParam($entityNew, strtolower($entity));
130
            $route = $form->get('addmore')->isClicked() ? strtolower($entity).'_new' : strtolower($entity).'_show';
131
132
            $return = $this->redirectToRoute($route, $param);
133
        }
134
135
        return $return;
136
    }
137
138
    /**
139
     * Displays a form to edit an existing item entity.
140
     *
141
     * @param Object $entity     Entity
142
     * @param string $entityName Name of Entity
143
     * @param string $typePath   Path of FormType
144
     * @return array
145
     */
146
    public function abstractEditAction($entity, $entityName, $typePath)
147
    {
148
        $param = $this->get('app.helper.controller')->testReturnParam($entity, $entityName);
149
        $editForm = $this->createForm($typePath, $entity, array(
150
            'action' => $this->generateUrl($entityName.'_update', $param),
151
            'method' => 'PUT',
152
        ));
153
        if ($entityName === 'group') {
154
            $this->addRoles($editForm, $entity);
155
        }
156
        $deleteForm = $this->createDeleteForm($entity->getId(), $entityName.'_delete');
157
158
        return array(
159
            $entityName => $entity,
160
            'edit_form'   => $editForm->createView(),
161
            'delete_form' => $deleteForm->createView(),
162
        );
163
    }
164
165
    /**
166
     * Edits an existing item entity.
167
     *
168
     * @param Object $entity     Entity
169
     * @param Request $request   Request in progress
170
     * @param string $entityName Name of Entity
171
     * @param string $typePath   Path of FormType
172
     * @return array
173
     */
174
    public function abstractUpdateAction($entity, Request $request, $entityName, $typePath)
175
    {
176
        $param = $this->get('app.helper.controller')->testReturnParam($entity, $entityName);
177
        $editForm = $this->createForm($typePath, $entity, array(
178
            'action' => $this->generateUrl($entityName.'_update', $param),
179
            'method' => 'PUT',
180
        ));
181
        if ($entityName === 'group') {
182
            $this->addRoles($editForm, $entity);
183
        }
184
        $editForm->handleRequest($request);
185
        $deleteForm = $this->createDeleteForm($entity->getId(), $entityName.'_delete');
186
187
        $return = array(
188
            $entityName => $entity,
189
            'edit_form'   => $editForm->createView(),
190
            'delete_form' => $deleteForm->createView(),);
191
192
        if ($editForm->isValid()) {
193
            $this->getDoctrine()->getManager()->flush();
194
            $this->addFlash('info', 'gestock.edit.ok');
195
196
            $return = $this->redirectToRoute($entityName.'_edit', $param);
197
        }
198
199
        return $return;
200
    }
201
202
    /**
203
     * Deletes an item entity.
204
     *
205
     * @param Object $entity     Entity
206
     * @param Request $request   Request in progress
207
     * @param string $entityName Name of Entity
208
     * @return array
209
     */
210
    public function abstractDeleteAction($entity, Request $request, $entityName)
211
    {
212
        $form = $this->createDeleteForm($entity->getId(), $entityName.'_delete');
213
        if ($form->handleRequest($request)->isValid()) {
214
            $etm = $this->getDoctrine()->getManager();
215
            $etm->remove($entity);
216
            $etm->flush();
217
        }
218
    }
219
220
    /**
221
     * Deletes a item entity with Articles.
222
     *
223
     * @param Object $entity     Entity
224
     * @param Request $request   Request in progress
225
     * @param string $entityName Name of Entity
226
     * @return array
227
     */
228
    public function abstractDeleteWithArticlesAction($entity, Request $request, $entityName)
229
    {
230
        $etm = $this->getDoctrine()->getManager();
231
        $form = $this->createDeleteForm($entity->getId(), $entityName . '_delete');
232
        $entityArticles = $etm
233
            ->getRepository('AppBundle:' .  ucfirst($entityName) . 'Articles')
234
            ->findBy([$entityName => $entity->getId()]);
235
236
        if ($form->handleRequest($request)->isValid()) {
237
            foreach ($entityArticles as $article) {
238
                $etm->remove($article);
239
            }
240
            $etm->remove($entity);
241
            $etm->flush();
242
        }
243
244
        return $this->redirect($this->generateUrl($entityName));
245
    }
246
247
    /**
248
     * AddQueryBuilderSort for the SortAction in views.
249
     *
250
     * @param QueryBuilder $qbd
251
     * @param string       $name
252
     */
253
    protected function addQueryBuilderSort(QueryBuilder $qbd, $name)
254
    {
255
        $alias = '';
256
        if (is_array($order = $this->get('app.helper.controller')->getOrder($name))) {
257
            if ($name !== $order['entity']) {
258
                $rootAlias = current($qbd->getDQLPart('from'))->getAlias();
259
                $join = current($qbd->getDQLPart('join'));
260
                foreach ($join as $item) {
261
                    if ($item->getJoin() === $rootAlias.'.'.$order['entity']) {
262
                        $alias = $item->getAlias();
263
                    }
264
                }
265
            } else {
266
                $alias = current($qbd->getDQLPart('from'))->getAlias();
267
            }
268
            $qbd->orderBy($alias . '.' . $order['field'], $order['type']);
269
        }
270
    }
271
272
    /**
273
     * Create Delete form.
274
     *
275
     * @param int    $id
276
     * @param string $route
277
     *
278
     * @return \Symfony\Component\Form\Form
279
     */
280
    protected function createDeleteForm($id, $route)
281
    {
282
        return $this->createFormBuilder(null, array('attr' => array('id' => 'delete')))
283
            ->setAction($this->generateUrl($route, array('id' => $id)))
284
            ->setMethod('DELETE')
285
            ->getForm()
286
        ;
287
    }
288
289
    /**
290
     * Get the existing roles
291
     *
292
     * @return array Array of roles
293
     */
294
    private function getExistingRoles()
295
    {
296
        $roleHierarchy = $this->container->getParameter('security.role_hierarchy.roles');
297
        $roles = array_keys($roleHierarchy);
298
        $theRoles = array();
299
300
        foreach ($roles as $role) {
301
            $theRoles[$role] = $role;
302
        }
303
        return $theRoles;
304
    }
305
306
    /**
307
     * Add roles to form
308
     *
309
     * @param \Symfony\Component\Form\Form  $form  The form in which to insert the roles
310
     * @param \AppBundle\Entity\Group       $group The entity to deal
311
     * @return \Symfony\Component\Form\Form The form
312
     */
313
    private function addRoles($form, $group)
314
    {
315
        $form->add('roles', ChoiceType::class, array(
316
            'choices' => $this->getExistingRoles(),
317
            'choices_as_values' => true,
318
            'data' => $group->getRoles(),
319
            'label' => 'Roles',
320
            'expanded' => true,
321
            'multiple' => true,
322
            'mapped' => true,
323
        ));
324
325
        return $form;
326
    }
327
328
    /**
329
     * Get the entity.
330
     *
331
     * @param string                                     $entityName Name of Entity
332
     * @param \Doctrine\Common\Persistence\ObjectManager $etm        ObjectManager instances
333
     * @return array|\Doctrine\ORM\QueryBuilder|null Entity elements
334
     */
335
    private function getEntity($entityName, ObjectManager $etm)
336
    {
337
        $roles = ['ROLE_ADMIN', 'ROLE_SUPER_ADMIN'];
338
        switch ($entityName) {
339
            case 'Article':
340
            case 'Supplier':
341
                if ($this->getUser() !== null &&
342
                    in_array($this->getUser()->getRoles()[0], $roles)) {
343
                    $entities = $etm->getRepository('AppBundle:'.$entityName)->getAllItems();
344
                } else {
345
                    $entities = $etm->getRepository('AppBundle:'.$entityName)->getItems();
346
                }
347
                break;
348
            case 'User':
349
                $entities = $etm->getRepository('AppBundle:'.$entityName)->getUsers();
350
                break;
351
            case 'FamilyLog':
352
                $entities = $etm->getRepository('AppBundle:'.$entityName)->childrenHierarchy();
353
                break;
354
            case 'UnitStorage':
355
                $entities = $etm->getRepository('AppBundle:'.$entityName)->createQueryBuilder('u');
356
                break;
357
            case 'Orders':
358
                $entities = $etm->getRepository('AppBundle:'.$entityName)->findOrders();
359
                break;
360
            case 'Inventory':
361
                $entities = $etm->getRepository('AppBundle:'.$entityName)->getInventory();
362
                break;
363
            default:
364
                $entities = $etm->getRepository('AppBundle:'.$entityName)->findAll();
365
        }
366
        return $entities;
367
    }
368
}
369