Completed
Push — master ( 07ded0...750096 )
by Laurent
03:19
created

abstractDeleteWithArticlesAction()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 18
rs 9.4285
cc 3
eloc 12
nc 2
nop 3
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\ORM\QueryBuilder;
20
21
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
22
23
/**
24
 * Abstract controller.
25
 *
26
 * @category Controller
27
 */
28
abstract class AbstractController extends Controller
29
{
30
    /**
31
     * Lists all items entity.
32
     *
33
     * @param string $entityName Name of Entity
34
     * @param \Symfony\Component\HttpFoundation\Request $request Sort request
35
     * @return array
36
     */
37
    public function abstractIndexAction($entityName, Request $request = null)
38
    {
39
        $etm = $this->getDoctrine()->getManager();
40
        $paginator = '';
41
        $entities = $this->get('app.helper.controller')->getEntity($entityName, $etm);
42
        
43
        if ($request !== null && is_array($entities) === false && $entities !== null) {
44
            $item = $this->container->getParameter('knp_paginator.page_range');
45
            $this->addQueryBuilderSort($entities, strtolower($entityName));
46
            $paginator = $this->get('knp_paginator')->paginate($entities, $request->query->get('page', 1), $item);
47
        }
48
49
        return array('entities'  => $entities, 'ctEntity' => count($entities), 'paginator' => $paginator,);
50
    }
51
52
    /**
53
     * Finds and displays an item entity.
54
     *
55
     * @param Object $entity     Entity
56
     * @param string $entityName Name of Entity
57
     * @return array
58
     */
59
    public function abstractShowAction($entity, $entityName)
60
    {
61
        $deleteForm = $this->createDeleteForm($entity->getId(), $entityName.'_delete');
62
63
        return array(
64
            $entityName => $entity,
65
            'delete_form' => $deleteForm->createView(),
66
        );
67
    }
68
69
    /**
70
     * Displays a form to create a new item entity.
71
     *
72
     * @param string      $entity     Entity
73
     * @param string      $entityPath Path of Entity
74
     * @param string      $typePath   Path of FormType
75
     * @return array
76
     */
77
    public function abstractNewAction($entity, $entityPath, $typePath)
78
    {
79
        $etm = $this->getDoctrine()->getManager();
80
        $ctEntity = count($etm->getRepository('AppBundle:'.$entity)->findAll());
81
        
82
        if ($entity === 'Company' || $entity === 'Settings' && $ctEntity >= 1) {
83
            $return = $this->redirectToRoute('_home');
84
            $this->addFlash('danger', 'gestock.settings.'.strtolower($entity).'.add2');
85
        }
86
87
        $entityNew = $etm->getClassMetadata($entityPath)->newInstance();
88
        $form = $this->createForm($typePath, $entityNew, array(
89
            'action' => $this->generateUrl(strtolower($entity).'_create'),
90
        ));
91
92
        if ($entity === 'Group') {
93
            $this->addRolesAction($form, $entityNew);
94
        }
95
        $return = array(strtolower($entity) => $entityNew, 'form'   => $form->createView(),);
96
97
        return $return;
98
    }
99
100
    /**
101
     * Creates a new item entity.
102
     *
103
     * @param Request $request   Request in progress
104
     * @param string $entity     Entity <i>First letter Upper</i>
105
     * @param string $entityPath Path of Entity
106
     * @param string $typePath   Path of FormType
107
     * @return array
108
     */
109
    public function abstractCreateAction(Request $request, $entity, $entityPath, $typePath)
110
    {
111
        $param = array();
112
        $etm = $this->getDoctrine()->getManager();
113
        $entityNew = $etm->getClassMetadata($entityPath)->newInstance();
114
        $form = $this->createForm($typePath, $entityNew, array(
115
            'action' => $this->generateUrl(strtolower($entity).'_create'),
116
        ));
117
        if ($entity === 'Group') {
118
            $this->addRolesAction($form, $entityNew);
119
        }
120
        $form->handleRequest($request);
121
        $return = [$entity => $entityNew, 'form' => $form->createView(),];
122
123
        if ($form->isValid()) {
124
            $etm = $this->getDoctrine()->getManager();
125
            $etm->persist($entityNew);
126
            $etm->flush();
127
128
            $param = $this->get('app.helper.controller')->testReturnParam($entityNew, strtolower($entity));
129
            $route = $form->get('addmore')->isClicked() ? strtolower($entity).'_new' : strtolower($entity).'_show';
130
131
            $return = $this->redirectToRoute($route, $param);
132
        }
133
134
        return $return;
135
    }
136
137
    /**
138
     * Displays a form to edit an existing item entity.
139
     *
140
     * @param Object $entity     Entity
141
     * @param string $entityName Name of Entity
142
     * @param string $typePath   Path of FormType
143
     * @return array
144
     */
145
    public function abstractEditAction($entity, $entityName, $typePath)
146
    {
147
        $param = $this->get('app.helper.controller')->testReturnParam($entity, $entityName);
148
        $editForm = $this->createForm($typePath, $entity, array(
149
            'action' => $this->generateUrl($entityName.'_update', $param),
150
            'method' => 'PUT',
151
        ));
152
        if ($entityName === 'group') {
153
            $this->addRolesAction($editForm, $entity);
154
        }
155
        $deleteForm = $this->createDeleteForm($entity->getId(), $entityName.'_delete');
156
157
        return array(
158
            $entityName => $entity,
159
            'edit_form'   => $editForm->createView(),
160
            'delete_form' => $deleteForm->createView(),
161
        );
162
    }
163
164
    /**
165
     * Edits an existing item entity.
166
     *
167
     * @param Object $entity     Entity
168
     * @param Request $request   Request in progress
169
     * @param string $entityName Name of Entity
170
     * @param string $typePath   Path of FormType
171
     * @return array
172
     */
173
    public function abstractUpdateAction($entity, Request $request, $entityName, $typePath)
174
    {
175
        $param = $this->get('app.helper.controller')->testReturnParam($entity, $entityName);
176
        $editForm = $this->createForm($typePath, $entity, array(
177
            'action' => $this->generateUrl($entityName.'_update', $param),
178
            'method' => 'PUT',
179
        ));
180
        if ($entityName === 'group') {
181
            $this->addRolesAction($editForm, $entity);
182
        }
183
        $editForm->handleRequest($request);
184
        $deleteForm = $this->createDeleteForm($entity->getId(), $entityName.'_delete');
185
186
        $return = array(
187
            $entityName => $entity,
188
            'edit_form'   => $editForm->createView(),
189
            'delete_form' => $deleteForm->createView(),);
190
191
        if ($editForm->isValid()) {
192
            $this->getDoctrine()->getManager()->flush();
193
            $this->addFlash('info', 'gestock.edit.ok');
194
195
            $return = $this->redirectToRoute($entityName.'_edit', $param);
196
        }
197
198
        return $return;
199
    }
200
201
    /**
202
     * Deletes an item entity.
203
     *
204
     * @param Object $entity     Entity
205
     * @param Request $request   Request in progress
206
     * @param string $entityName Name of Entity
207
     * @return array
208
     */
209
    public function abstractDeleteAction($entity, Request $request, $entityName)
210
    {
211
        $form = $this->createDeleteForm($entity->getId(), $entityName.'_delete');
212
        if ($form->handleRequest($request)->isValid()) {
213
            $etm = $this->getDoctrine()->getManager();
214
            $etm->remove($entity);
215
            $etm->flush();
216
        }
217
    }
218
219
    /**
220
     * Deletes a item entity with Articles.
221
     *
222
     * @param Object $entity     Entity
223
     * @param Request $request   Request in progress
224
     * @param string $entityName Name of Entity
225
     * @return array
226
     */
227
    public function abstractDeleteWithArticlesAction($entity, Request $request, $entityName)
228
    {
229
        $etm = $this->getDoctrine()->getManager();
230
        $form = $this->createDeleteForm($entity->getId(), $entityName . '_delete');
231
        $entityArticles = $etm
232
            ->getRepository('AppBundle:' .  ucfirst($entityName) . 'Articles')
233
            ->findBy([$entityName => $entity->getId()]);
234
235
        if ($form->handleRequest($request)->isValid()) {
236
            foreach ($entityArticles as $article) {
237
                $etm->remove($article);
238
            }
239
            $etm->remove($entity);
240
            $etm->flush();
241
        }
242
243
        return $this->redirect($this->generateUrl($entityName));
244
    }
245
246
    /**
247
     * AddQueryBuilderSort for the SortAction in views.
248
     *
249
     * @param QueryBuilder $qbd
250
     * @param string       $name
251
     */
252
    protected function addQueryBuilderSort(QueryBuilder $qbd, $name)
253
    {
254
        $alias = '';
255
        if (is_array($order = $this->get('app.helper.controller')->getOrder($name))) {
256
            if ($name !== $order['entity']) {
257
                $rootAlias = current($qbd->getDQLPart('from'))->getAlias();
258
                $join = current($qbd->getDQLPart('join'));
259
                foreach ($join as $item) {
260
                    if ($item->getJoin() === $rootAlias.'.'.$order['entity']) {
261
                        $alias = $item->getAlias();
262
                    }
263
                }
264
            } else {
265
                $alias = current($qbd->getDQLPart('from'))->getAlias();
266
            }
267
            $qbd->orderBy($alias . '.' . $order['field'], $order['type']);
268
        }
269
    }
270
271
    /**
272
     * Create Delete form.
273
     *
274
     * @param int    $id
275
     * @param string $route
276
     *
277
     * @return \Symfony\Component\Form\Form
278
     */
279
    protected function createDeleteForm($id, $route)
280
    {
281
        return $this->createFormBuilder(null, array('attr' => array('id' => 'delete')))
282
            ->setAction($this->generateUrl($route, array('id' => $id)))
283
            ->setMethod('DELETE')
284
            ->getForm()
285
        ;
286
    }
287
288
    /**
289
     * Get the existing roles
290
     *
291
     * @return array Array of roles
292
     */
293
    private function getExistingRoles()
294
    {
295
        $roleHierarchy = $this->container->getParameter('security.role_hierarchy.roles');
296
        $roles = array_keys($roleHierarchy);
297
        $theRoles = array();
298
299
        foreach ($roles as $role) {
300
            $theRoles[$role] = $role;
301
        }
302
        return $theRoles;
303
    }
304
305
    /**
306
     * Add roles to form
307
     *
308
     * @param \Symfony\Component\Form\Form  $form  The form in which to insert the roles
309
     * @param \AppBundle\Entity\Group       $group The entity to deal
310
     * @return \Symfony\Component\Form\Form The form
311
     */
312
    public function addRolesAction($form, $group)
313
    {
314
        $form->add('roles', ChoiceType::class, array(
315
            'choices' => $this->getExistingRoles(),
316
            'choices_as_values' => true,
317
            'data' => $group->getRoles(),
318
            'label' => 'Roles',
319
            'expanded' => true,
320
            'multiple' => true,
321
            'mapped' => true,
322
        ));
323
324
        return $form;
325
    }
326
}
327