Completed
Push — master ( 5e4f38...1af8b6 )
by Laurent
08:07 queued 04:24
created

AbstractController::testReturnParam()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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