Completed
Push — master ( 630db2...59081b )
by Laurent
03:27
created

AbstractController::getEntity()   C

Complexity

Conditions 8
Paths 8

Size

Total Lines 26
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 26
rs 5.3846
cc 8
eloc 22
nc 8
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 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
            case 'Article':
65
            case 'Supplier':
66
                if ($this->getUser() !== null && in_array($this->getUser()->getRoles()[0], $roles)) {
67
                    $entities = $etm->getRepository('AppBundle:'.$entityName)->getAllItems();
68
                } else {
69
                    $entities = $etm->getRepository('AppBundle:'.$entityName)->getItems();
70
                }
71
                break;
72
            case 'User':
73
                $entities = $etm->getRepository('AppBundle:'.$entityName)->getUsers();
74
                break;
75
            case 'FamilyLog':
76
                $entities = $etm->getRepository('AppBundle:'.$entityName)->childrenHierarchy();
77
                break;
78
            case 'UnitStorage':
79
                $entities = $etm->getRepository('AppBundle:'.$entityName)->createQueryBuilder('u');
80
                break;
81
            default:
82
                $entities = $etm->getRepository('AppBundle:'.$entityName)->findAll();
83
        }
84
        return $entities;
85
    }
86
87
    /**
88
     * Finds and displays an item entity.
89
     *
90
     * @param Object $entity     Entity
91
     * @param string $entityName Name of Entity
92
     * @return array
93
     */
94
    public function abstractShowAction($entity, $entityName)
95
    {
96
        $deleteForm = $this->createDeleteForm($entity->getId(), $entityName.'_delete');
97
98
        return array(
99
            $entityName => $entity,
100
            'delete_form' => $deleteForm->createView(),
101
        );
102
    }
103
104
    /**
105
     * Displays a form to create a new item entity.
106
     *
107
     * @param string      $entity     Entity
108
     * @param string      $entityPath Path of Entity
109
     * @param string      $typePath   Path of FormType
110
     * @return array
111
     */
112
    public function abstractNewAction($entity, $entityPath, $typePath)
113
    {
114
        $etm = $this->getDoctrine()->getManager();
115
        $ctEntity = count($etm->getRepository('AppBundle:'.$entity)->findAll());
116
        
117
        if ($entity === 'Company' || $entity === 'Settings' && $ctEntity >= 1) {
118
            $return = $this->redirectToRoute('_home');
119
            $this->addFlash('danger', 'gestock.settings.'.strtolower($entity).'.add2');
120
        }
121
122
        $entityNew = $etm->getClassMetadata($entityPath)->newInstance();
123
        $form = $this->createForm($typePath, $entityNew, array(
124
            'action' => $this->generateUrl(strtolower($entity).'_create'),
125
        ));
126
127
        if ($entity === 'Group') {
128
            $this->addRolesAction($form, $entityNew);
129
        }
130
        $return = array(strtolower($entity) => $entityNew, 'form'   => $form->createView(),);
131
132
        return $return;
133
    }
134
135
    /**
136
     * Creates a new item entity.
137
     *
138
     * @param Request $request   Request in progress
139
     * @param string $entity     Entity <i>First letter Upper</i>
140
     * @param string $entityPath Path of Entity
141
     * @param string $typePath   Path of FormType
142
     * @return array
143
     */
144
    public function abstractCreateAction(Request $request, $entity, $entityPath, $typePath)
145
    {
146
        $param = array();
147
        $etm = $this->getDoctrine()->getManager();
148
        $entityNew = $etm->getClassMetadata($entityPath)->newInstance();
149
        $form = $this->createForm($typePath, $entityNew, array(
150
            'action' => $this->generateUrl(strtolower($entity).'_create'),
151
        ));
152
        if ($entity === 'Group') {
153
            $this->addRolesAction($form, $entityNew);
154
        }
155
        $form->handleRequest($request);
156
        $return = [$entity => $entityNew, 'form' => $form->createView(),];
157
158
        if ($form->isValid()) {
159
            $etm = $this->getDoctrine()->getManager();
160
            $etm->persist($entityNew);
161
            $etm->flush();
162
163
            $param = $this->testReturnParam($entityNew, strtolower($entity));
164
            $route = $form->get('addmore')->isClicked() ? strtolower($entity).'_new' : strtolower($entity).'_show';
1 ignored issue
show
Bug introduced by
The method isClicked() does not seem to exist on object<Symfony\Component\Form\Form>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
165
166
            $return = $this->redirectToRoute($route, $param);
167
        }
168
169
        return $return;
170
    }
171
172
    /**
173
     * Displays a form to edit an existing item entity.
174
     *
175
     * @param Object $entity     Entity
176
     * @param string $entityName Name of Entity
177
     * @param string $typePath   Path of FormType
178
     * @return array
179
     */
180
    public function abstractEditAction($entity, $entityName, $typePath)
181
    {
182
        $param = $this->testReturnParam($entity, $entityName);
183
        $editForm = $this->createForm($typePath, $entity, array(
184
            'action' => $this->generateUrl($entityName.'_update', $param),
185
            'method' => 'PUT',
186
        ));
187
        if ($entityName === 'group') {
188
            $this->addRolesAction($editForm, $entity);
189
        }
190
        $deleteForm = $this->createDeleteForm($entity->getId(), $entityName.'_delete');
191
192
        return array(
193
            $entityName => $entity,
194
            'edit_form'   => $editForm->createView(),
195
            'delete_form' => $deleteForm->createView(),
196
        );
197
    }
198
199
    /**
200
     * Edits an existing item entity.
201
     *
202
     * @param Object $entity     Entity
203
     * @param Request $request   Request in progress
204
     * @param string $entityName Name of Entity
205
     * @param string $typePath   Path of FormType
206
     * @return array
207
     */
208
    public function abstractUpdateAction($entity, Request $request, $entityName, $typePath)
209
    {
210
        $param = $this->testReturnParam($entity, $entityName);
211
        $editForm = $this->createForm($typePath, $entity, array(
212
            'action' => $this->generateUrl($entityName.'_update', $param),
213
            'method' => 'PUT',
214
        ));
215
        if ($entityName === 'group') {
216
            $this->addRolesAction($editForm, $entity);
217
        }
218
        $editForm->handleRequest($request);
219
        $deleteForm = $this->createDeleteForm($entity->getId(), $entityName.'_delete');
220
221
        $return = array(
222
            $entityName => $entity,
223
            'edit_form'   => $editForm->createView(),
224
            'delete_form' => $deleteForm->createView(),);
225
226
        if ($editForm->isValid()) {
227
            $this->getDoctrine()->getManager()->flush();
228
            $this->addFlash('info', 'gestock.edit.ok');
229
230
            $return = $this->redirectToRoute($entityName.'_edit', $param);
231
        }
232
233
        return $return;
234
    }
235
236
    /**
237
     * Deletes an item entity.
238
     *
239
     * @param Object $entity     Entity
240
     * @param Request $request   Request in progress
241
     * @param string $entityName Name of Entity
242
     * @return array
243
     */
244
    public function abstractDeleteAction($entity, Request $request, $entityName)
245
    {
246
        $form = $this->createDeleteForm($entity->getId(), $entityName.'_delete');
247
        if ($form->handleRequest($request)->isValid()) {
248
            $etm = $this->getDoctrine()->getManager();
249
            $etm->remove($entity);
250
            $etm->flush();
251
        }
252
    }
253
254
    /**
255
     * Deletes a item entity with Articles.
256
     *
257
     * @param Object $entity     Entity
258
     * @param Request $request   Request in progress
259
     * @param string $entityName Name of Entity
260
     * @return array
261
     */
262
    public function abstractDeleteWithArticlesAction($entity, Request $request, $entityName)
263
    {
264
        $etm = $this->getDoctrine()->getManager();
265
        $form = $this->createDeleteForm($entity->getId(), $entityName . '_delete');
266
        $entityArticles = $etm
267
            ->getRepository('AppBundle:' .  ucfirst($entityName) . 'Articles')
268
            ->findBy([$entityName => $entity->getId()]);
269
270
        if ($form->handleRequest($request)->isValid()) {
271
            foreach ($entityArticles as $article) {
272
                $etm->remove($article);
273
            }
274
            $etm->remove($entity);
275
            $etm->flush();
276
        }
277
278
        return $this->redirect($this->generateUrl($entityName));
279
    }
280
281
    private function testReturnParam($entity, $entityName)
282
    {
283
        $entityArray = ['company', 'settings', 'group', 'tva'];
284
        if (in_array($entityName, $entityArray, true)) {
285
            $param = array('id' => $entity->getId());
286
        } else {
287
            $param = array('slug' => $entity->getSlug());
288
        }
289
290
        return $param;
291
    }
292
293
    /**
294
     * SetOrder for the SortAction in views.
295
     *
296
     * @param string $name   session name
297
     * @param string $entity entity name
298
     * @param string $field  field name
299
     * @param string $type   sort type ("ASC"/"DESC")
300
     */
301
    protected function setOrder($name, $entity, $field, $type = 'ASC')
302
    {
303
        $session = new Session();
304
305
        $session->set('sort.'.$name, array('entity' => $entity, 'field' => $field, 'type' => $type));
306
    }
307
308
    /**
309
     * GetOrder for the SortAction in views.
310
     *
311
     * @param string $name session name
312
     *
313
     * @return array
314
     */
315
    protected function getOrder($name)
316
    {
317
        $session = new Session();
318
319
        return $session->has('sort.' . $name) ? $session->get('sort.' . $name) : null;
320
    }
321
322
    /**
323
     * AddQueryBuilderSort for the SortAction in views.
324
     *
325
     * @param QueryBuilder $qbd
326
     * @param string       $name
327
     */
328
    protected function addQueryBuilderSort(QueryBuilder $qbd, $name)
329
    {
330
        $alias = '';
331
        if (is_array($order = $this->getOrder($name))) {
332
            if ($name !== $order['entity']) {
333
                $rootAlias = current($qbd->getDQLPart('from'))->getAlias();
334
                $join = current($qbd->getDQLPart('join'));
335
                foreach ($join as $item) {
336
                    if ($item->getJoin() === $rootAlias.'.'.$order['entity']) {
337
                        $alias = $item->getAlias();
338
                    }
339
                }
340
            } else {
341
                $alias = current($qbd->getDQLPart('from'))->getAlias();
342
            }
343
            $qbd->orderBy($alias . '.' . $order['field'], $order['type']);
344
        }
345
    }
346
347
    /**
348
     * Create Delete form.
349
     *
350
     * @param int    $id
351
     * @param string $route
352
     *
353
     * @return \Symfony\Component\Form\Form
354
     */
355
    protected function createDeleteForm($id, $route)
356
    {
357
        return $this->createFormBuilder(null, array('attr' => array('id' => 'delete')))
358
            ->setAction($this->generateUrl($route, array('id' => $id)))
359
            ->setMethod('DELETE')
360
            ->getForm()
361
        ;
362
    }
363
364
    /**
365
     * Array of file (`pdf`) layout.
366
     *
367
     * @param string $date File date
368
     * @param string $title File title
369
     * @return array<string,integer|string|boolean>
370
     */
371
    protected function getArray($date, $title)
372
    {
373
        $array = array(
374
            'margin-top' => 15,
375
            'header-spacing' => 5,
376
            'header-font-size' => 8,
377
            'header-left' => 'G.L.S.R.',
378
            'header-center' => $title,
379
            'header-right' => $date,
380
            'header-line' => true,
381
            'margin-bottom' => 15,
382
            'footer-spacing' => 5,
383
            'footer-font-size' => 8,
384
            'footer-left' => 'GLSR &copy 2014 and beyond.',
385
            'footer-right' => 'Page [page]/[toPage]',
386
            'footer-line' => true,
387
        );
388
        return $array;
389
    }
390
391
    /**
392
     * Get the existing roles
393
     *
394
     * @return array Array of roles
395
     */
396
    private function getExistingRoles()
397
    {
398
        $roleHierarchy = $this->container->getParameter('security.role_hierarchy.roles');
399
        $roles = array_keys($roleHierarchy);
400
        $theRoles = array();
401
402
        foreach ($roles as $role) {
403
            $theRoles[$role] = $role;
404
        }
405
        return $theRoles;
406
    }
407
408
    /**
409
     * Add roles to form
410
     *
411
     * @param \Symfony\Component\Form\Form  $form  The form in which to insert the roles
412
     * @param \AppBundle\Entity\Group       $group The entity to deal
413
     * @return \Symfony\Component\Form\Form The form
414
     */
415
    public function addRolesAction($form, $group)
416
    {
417
        $form->add('roles', ChoiceType::class, array(
418
            'choices' => $this->getExistingRoles(),
419
            'choices_as_values' => true,
420
            'data' => $group->getRoles(),
421
            'label' => 'Roles',
422
            'expanded' => true,
423
            'multiple' => true,
424
            'mapped' => true,
425
        ));
426
427
        return $form;
428
    }
429
}
430