Completed
Push — Recipes ( 432d36...7b4b65 )
by Laurent
04:19
created

AbstractController::getEntity()   C

Complexity

Conditions 11
Paths 12

Size

Total Lines 34
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

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