Completed
Push — master ( 099705...21cdad )
by Laurent
03:04
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 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));
0 ignored issues
show
Bug introduced by
It seems like $entities defined by $this->getEntity($entityName, $etm) on line 42 can also be of type array or null; however, AppBundle\Controller\Abs...::addQueryBuilderSort() does only seem to accept object<Doctrine\ORM\QueryBuilder>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
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 array|QueryBuilder|null Entity elements
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->get('app.helper.controller')->testReturnParam($entityNew, strtolower($entity));
164
            $route = $form->get('addmore')->isClicked() ? strtolower($entity).'_new' : strtolower($entity).'_show';
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->get('app.helper.controller')->testReturnParam($entityNew, strtolower($entity));
0 ignored issues
show
Bug introduced by
The variable $entityNew does not exist. Did you mean $entity?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
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->get('app.helper.controller')->testReturnParam($entityNew, strtolower($entity));
0 ignored issues
show
Bug introduced by
The variable $entityNew does not exist. Did you mean $entity?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
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
    /**
282
     * AddQueryBuilderSort for the SortAction in views.
283
     *
284
     * @param QueryBuilder $qbd
285
     * @param string       $name
286
     */
287
    protected function addQueryBuilderSort(QueryBuilder $qbd, $name)
288
    {
289
        $alias = '';
290
        if (is_array($order = $this->get('app.helper.controller')->getOrder($name))) {
291
            if ($name !== $order['entity']) {
292
                $rootAlias = current($qbd->getDQLPart('from'))->getAlias();
293
                $join = current($qbd->getDQLPart('join'));
294
                foreach ($join as $item) {
295
                    if ($item->getJoin() === $rootAlias.'.'.$order['entity']) {
296
                        $alias = $item->getAlias();
297
                    }
298
                }
299
            } else {
300
                $alias = current($qbd->getDQLPart('from'))->getAlias();
301
            }
302
            $qbd->orderBy($alias . '.' . $order['field'], $order['type']);
303
        }
304
    }
305
306
    /**
307
     * Create Delete form.
308
     *
309
     * @param int    $id
310
     * @param string $route
311
     *
312
     * @return \Symfony\Component\Form\Form
313
     */
314
    protected function createDeleteForm($id, $route)
315
    {
316
        return $this->createFormBuilder(null, array('attr' => array('id' => 'delete')))
317
            ->setAction($this->generateUrl($route, array('id' => $id)))
318
            ->setMethod('DELETE')
319
            ->getForm()
320
        ;
321
    }
322
323
    /**
324
     * Array of file (`pdf`) layout.
325
     *
326
     * @param string $date File date
327
     * @param string $title File title
328
     * @return array<string,integer|string|boolean>
329
     */
330
    protected function getArray($date, $title)
331
    {
332
        $array = array(
333
            'margin-top' => 15,
334
            'header-spacing' => 5,
335
            'header-font-size' => 8,
336
            'header-left' => 'G.L.S.R.',
337
            'header-center' => $title,
338
            'header-right' => $date,
339
            'header-line' => true,
340
            'margin-bottom' => 15,
341
            'footer-spacing' => 5,
342
            'footer-font-size' => 8,
343
            'footer-left' => 'GLSR &copy 2014 and beyond.',
344
            'footer-right' => 'Page [page]/[toPage]',
345
            'footer-line' => true,
346
        );
347
        return $array;
348
    }
349
350
    /**
351
     * Get the existing roles
352
     *
353
     * @return array Array of roles
354
     */
355
    private function getExistingRoles()
356
    {
357
        $roleHierarchy = $this->container->getParameter('security.role_hierarchy.roles');
358
        $roles = array_keys($roleHierarchy);
359
        $theRoles = array();
360
361
        foreach ($roles as $role) {
362
            $theRoles[$role] = $role;
363
        }
364
        return $theRoles;
365
    }
366
367
    /**
368
     * Add roles to form
369
     *
370
     * @param \Symfony\Component\Form\Form  $form  The form in which to insert the roles
371
     * @param \AppBundle\Entity\Group       $group The entity to deal
372
     * @return \Symfony\Component\Form\Form The form
373
     */
374
    public function addRolesAction($form, $group)
375
    {
376
        $form->add('roles', ChoiceType::class, array(
377
            'choices' => $this->getExistingRoles(),
378
            'choices_as_values' => true,
379
            'data' => $group->getRoles(),
380
            'label' => 'Roles',
381
            'expanded' => true,
382
            'multiple' => true,
383
            'mapped' => true,
384
        ));
385
386
        return $form;
387
    }
388
}
389