Completed
Push — master ( 1063d7...a7489f )
by Laurent
03:16
created

AbstractController::abstractUpdateAction()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

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