Completed
Push — Recipes ( 630f49...c8afb0 )
by Laurent
12:15 queued 03:48
created

AbstractAppController::getEntity()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.7
c 0
b 0
f 0
cc 4
nc 3
nop 2
1
<?php
2
/**
3
 * AbstractController Controller common methods.
4
 *
5
 * PHP Version 7
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
 * @see      https://github.com/Dev-Int/glsr
14
 */
15
16
namespace App\Controller;
17
18
use Symfony\Component\HttpFoundation\Request;
19
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
20
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
21
use Doctrine\Common\Persistence\ObjectManager;
22
use Doctrine\ORM\QueryBuilder;
23
24
/**
25
 * Abstract controller.
26
 *
27
 * @category Controller
28
 */
29
abstract class AbstractAppController extends AbstractController
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
     *
38
     * @return array
39
     */
40
    public function abstractIndexAction($entityName, $prefixRoute, Request $request = null)
41
    {
42
        $etm = $this->getDoctrine()->getManager();
43
        $paginator = '';
44
        $entities = $this->getEntity($entityName, $etm);
45
        $qbd = $etm->createQueryBuilder();
46
        $qbd->select('count(entity.id)');
47
        $qbd->from('App:'.$entityName, 'entity');
48
        $ctEntity = $qbd->getQuery()->getSingleScalarResult();
49
50
        if (null !== $request && false === is_array($entities) && null !== $entities) {
51
            $item = $this->container->getParameter('knp_paginator.page_range');
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Psr\Container\ContainerInterface as the method getParameter() does only exist in the following implementations of said interface: Container14\ProjectServiceContainer, ProjectServiceContainer, Symfony\Component\Depend...urationContainerBuilder, Symfony\Component\DependencyInjection\Container, Symfony\Component\Depend...ection\ContainerBuilder, Symfony\Component\Depend...\NoConstructorContainer, Symfony\Component\Depend...tainers\CustomContainer, Symfony\Component\Depend...ProjectServiceContainer, Symfony\Component\Depend...ProjectServiceContainer, Symfony_DI_PhpDumper_Test_Almost_Circular_Private, Symfony_DI_PhpDumper_Test_Almost_Circular_Public, Symfony_DI_PhpDumper_Test_Base64Parameters, Symfony_DI_PhpDumper_Test_Deep_Graph, Symfony_DI_PhpDumper_Test_EnvParameters, Symfony_DI_PhpDumper_Test_Inline_Self_Ref, Symfony_DI_PhpDumper_Test_Legacy_Privates, Symfony_DI_PhpDumper_Test_Rot13Parameters, Symfony_DI_PhpDumper_Test_Uninitialized_Reference.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
52
            $this->addQueryBuilderSort($entities, $prefixRoute);
53
            $paginator = $this->get('knp_paginator')->paginate($entities, $request->query->get('page', 1), $item);
54
        }
55
56
        return ['entities' => $entities, 'ctEntity' => $ctEntity, 'paginator' => $paginator];
57
    }
58
59
    /**
60
     * Finds and displays an item entity.
61
     *
62
     * @param object $entity      Entity
63
     * @param string $prefixRoute prefix_route
64
     *
65
     * @return array
66
     */
67
    public function abstractShowAction($entity, $prefixRoute)
68
    {
69
        $deleteForm = $this->createDeleteForm($entity->getId(), $prefixRoute.'_delete');
70
71
        return [$prefixRoute => $entity, 'delete_form' => $deleteForm->createView()];
72
    }
73
74
    /**
75
     * Displays a form to create a new item entity.
76
     *
77
     * @param string $entityName  Name of Entity
78
     * @param string $entityPath  Path of Entity
79
     * @param string $typePath    Path of FormType
80
     * @param string $prefixRoute Prefix of Route
81
     *
82
     * @return array
83
     */
84
    public function abstractNewAction($entityName, $entityPath, $typePath, $prefixRoute)
85
    {
86
        $etm = $this->getDoctrine()->getManager();
87
        $ctEntity = count($etm->getRepository('App:'.$entityName)->findAll());
88
89
        // Only ONE record in these entity
90
        if ('Settings\Company' === $entityName || 'Settings\Settings' === $entityName && $ctEntity >= 1) {
91
            $return = $this->redirectToRoute('_home');
92
            $this->addFlash('danger', 'gestock.settings.'.$prefixRoute.'.add2');
93
        }
94
        if ('Settings\Company' !== $entityName || 'Settings\Settings' !== $entityName) {
95
            $entityNew = $etm->getClassMetadata($entityPath)->newInstance();
96
            $form = $this->createForm($typePath, $entityNew, ['action' => $this->generateUrl($prefixRoute.'_create')]);
97
98
            if ('Staff\Group' === $entityName) {
99
                $this->addRolesAction($form, $entityNew);
0 ignored issues
show
Compatibility introduced by
$form of type object<Symfony\Component\Form\FormInterface> is not a sub-type of object<Symfony\Component\Form\Form>. It seems like you assume a concrete implementation of the interface Symfony\Component\Form\FormInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
100
            }
101
            $return = [strtolower($entityName) => $entityNew, 'form' => $form->createView()];
102
        }
103
104
        return $return;
0 ignored issues
show
Bug introduced by
The variable $return does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
105
    }
106
107
    /**
108
     * Creates a new item entity.
109
     *
110
     * @param \Symfony\Component\HttpFoundation\Request $request     Request in progress
111
     * @param string                                    $entityName  Entity name <i>First letter Upper</i>
112
     * @param string                                    $entityPath  Path of Entity
113
     * @param string                                    $typePath    Path of FormType
114
     * @param string                                    $prefixRoute Prefix of route
115
     *
116
     * @return array
117
     */
118
    public function abstractCreateAction(Request $request, $entityName, $entityPath, $typePath, $prefixRoute)
119
    {
120
        $etm = $this->getDoctrine()->getManager();
121
        $entityNew = $etm->getClassMetadata($entityPath)->newInstance();
122
        $form = $this->createForm($typePath, $entityNew, ['action' => $this->generateUrl($prefixRoute.'_create')]);
123
        if ('Staff\Group' === $entityName) {
124
            $this->addRolesAction($form, $entityNew);
0 ignored issues
show
Compatibility introduced by
$form of type object<Symfony\Component\Form\FormInterface> is not a sub-type of object<Symfony\Component\Form\Form>. It seems like you assume a concrete implementation of the interface Symfony\Component\Form\FormInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
125
        }
126
        $form->handleRequest($request);
127
        $return = [$entityName => $entityNew, 'form' => $form->createView()];
128
129
        if ($form->isValid()) {
130
            $etm = $this->getDoctrine()->getManager();
131
            if ('Settings\Article' === $entityName) {
132
                $entityNew->setQuantity(0.000);
133
            }
134
            $etm->persist($entityNew);
135
            $etm->flush();
136
137
            $param = $this->testReturnParam($entityNew, $prefixRoute);
138
            $route = $form->get('addmore')->isClicked() ? $prefixRoute.'_new' : $prefixRoute.'_show';
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Form\FormInterface as the method isClicked() does only exist in the following implementations of said interface: Symfony\Component\Form\SubmitButton.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
139
140
            $return = $this->redirectToRoute($route, $param);
141
        }
142
143
        return $return;
144
    }
145
146
    /**
147
     * Displays a form to edit an existing item entity.
148
     *
149
     * @param object $entity      Entity
150
     * @param string $prefixRoute Prefix of Route
151
     * @param string $typePath    Path of FormType
152
     *
153
     * @return array
154
     */
155
    public function abstractEditAction($entity, $prefixRoute, $typePath)
156
    {
157
        $param = $this->testReturnParam($entity, $prefixRoute);
158
        $editForm = $this->createForm(
159
            $typePath,
160
            $entity,
161
            ['action' => $this->generateUrl($prefixRoute.'_update', $param), 'method' => 'PUT']
162
        );
163
        if ('group' === $prefixRoute) {
164
            $this->addRolesAction($editForm, $entity);
0 ignored issues
show
Compatibility introduced by
$editForm of type object<Symfony\Component\Form\FormInterface> is not a sub-type of object<Symfony\Component\Form\Form>. It seems like you assume a concrete implementation of the interface Symfony\Component\Form\FormInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
165
        }
166
        $deleteForm = $this->createDeleteForm($entity->getId(), $prefixRoute.'_delete');
167
168
        return [$prefixRoute => $entity, 'edit_form' => $editForm->createView(),
169
            'delete_form' => $deleteForm->createView(), ];
170
    }
171
172
    /**
173
     * Edits an existing item entity.
174
     *
175
     * @param object                                    $entity      Entity
176
     * @param \Symfony\Component\HttpFoundation\Request $request     Request in progress
177
     * @param string                                    $prefixRoute Prefix of Route
178
     * @param string                                    $typePath    Path of FormType
179
     *
180
     * @return array
181
     */
182
    public function abstractUpdateAction($entity, Request $request, $prefixRoute, $typePath)
183
    {
184
        $param = $this->testReturnParam($entity, $prefixRoute);
185
        $editForm = $this->createForm(
186
            $typePath,
187
            $entity,
188
            ['action' => $this->generateUrl($prefixRoute.'_update', $param), 'method' => 'PUT']
189
        );
190
        if ('group' === $prefixRoute) {
191
            $this->addRolesAction($editForm, $entity);
0 ignored issues
show
Compatibility introduced by
$editForm of type object<Symfony\Component\Form\FormInterface> is not a sub-type of object<Symfony\Component\Form\Form>. It seems like you assume a concrete implementation of the interface Symfony\Component\Form\FormInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
192
        }
193
        $editForm->handleRequest($request);
194
        $deleteForm = $this->createDeleteForm($entity->getId(), $prefixRoute.'_delete');
195
196
        $return = [$prefixRoute => $entity, 'edit_form' => $editForm->createView(),
197
            'delete_form' => $deleteForm->createView(), ];
198
199
        if ($editForm->isValid()) {
200
            $this->getDoctrine()->getManager()->flush();
201
            $this->addFlash('info', 'gestock.edit.ok');
202
203
            $return = $this->redirectToRoute($prefixRoute.'_edit', $param);
204
        }
205
206
        return $return;
207
    }
208
209
    /**
210
     * Deletes an item entity.
211
     *
212
     * @param object                                    $entity      Entity
213
     * @param \Symfony\Component\HttpFoundation\Request $request     Request in progress
214
     * @param string                                    $prefixRoute Prefix of Route
215
     *
216
     * @return array
217
     */
218
    public function abstractDeleteAction($entity, Request $request, $prefixRoute)
219
    {
220
        $form = $this->createDeleteForm($entity->getId(), $prefixRoute.'_delete');
221
        if ($form->handleRequest($request)->isValid()) {
222
            $etm = $this->getDoctrine()->getManager();
223
            $etm->remove($entity);
224
            $etm->flush();
225
        }
226
    }
227
228
    /**
229
     * Deletes a item entity with Articles.
230
     *
231
     * @param object                                    $entity      Entity
232
     * @param \Symfony\Component\HttpFoundation\Request $request     Request in progress
233
     * @param string                                    $entityName  Name of Entity
234
     * @param string                                    $prefixRoute Prefix of Route
235
     *
236
     * @return array
237
     */
238
    public function abstractDeleteWithArticlesAction($entity, Request $request, $entityName, $prefixRoute)
239
    {
240
        $etm = $this->getDoctrine()->getManager();
241
        $form = $this->createDeleteForm($entity->getId(), $prefixRoute.'_delete');
242
        $entityArticles = $etm
243
            ->getRepository('App:'.$entityName.'Articles')
244
            ->findBy([$prefixRoute => $entity->getId()]);
245
246
        if ($form->handleRequest($request)->isValid()) {
247
            foreach ($entityArticles as $article) {
248
                $etm->remove($article);
249
            }
250
            $etm->remove($entity);
251
            $etm->flush();
252
        }
253
254
        return $this->redirect($this->generateUrl($prefixRoute));
255
    }
256
257
    /**
258
     * AddQueryBuilderSort for the SortAction in views.
259
     *
260
     * @param QueryBuilder $qbd  QueryBuilder
261
     * @param string       $name Order name
262
     */
263
    protected function addQueryBuilderSort(QueryBuilder $qbd, $name)
264
    {
265
        $alias = '';
266
        if (is_array($order = $this->get('app.helper.controller')->getOrder($name))) {
267
            if ($name !== $order['entity']) {
268
                $rootAlias = current($qbd->getDQLPart('from'))->getAlias();
269
                $join = current($qbd->getDQLPart('join'));
270
                foreach ($join as $item) {
271
                    if ($item->getJoin() === $rootAlias.'.'.$order['entity']) {
272
                        $alias = $item->getAlias();
273
                    }
274
                }
275
            }
276
            if ($name === $order['entity']) {
277
                $alias = current($qbd->getDQLPart('from'))->getAlias();
278
            }
279
            $qbd->orderBy($alias.'.'.$order['field'], $order['type']);
280
        }
281
    }
282
283
    /**
284
     * Create Delete form.
285
     *
286
     * @param int    $id    Id to delete
287
     * @param string $route Route to redirect
288
     *
289
     * @return \Symfony\Component\Form\Form
290
     */
291
    protected function createDeleteForm($id, $route)
292
    {
293
        return $this->createFormBuilder(null, ['attr' => ['id' => 'delete']])
294
            ->setAction($this->generateUrl($route, ['id' => $id]))
295
            ->setMethod('DELETE')
296
            ->getForm();
297
    }
298
299
    /**
300
     * Test paramters to return.
301
     *
302
     * @param object $entity      Entity to return
303
     * @param string $prefixRoute Entity name to test
304
     *
305
     * @return array Parameters to return
306
     */
307
    protected function testReturnParam($entity, $prefixRoute)
308
    {
309
        $entityArray = ['article', 'supplier', 'familylog', 'zonestorage', 'unit', 'material'];
310
        if (in_array($prefixRoute, $entityArray, true)) {
311
            $param = ['slug' => $entity->getSlug()];
312
        }
313
        if (!in_array($prefixRoute, $entityArray, true)) {
314
            $param = ['id' => $entity->getId()];
315
        }
316
317
        return $param;
0 ignored issues
show
Bug introduced by
The variable $param does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
318
    }
319
320
    /**
321
     * Get the existing roles.
322
     *
323
     * @return array Array of roles
324
     */
325
    private function getExistingRoles()
326
    {
327
        $roleHierarchy = $this->container->getParameter('security.role_hierarchy.roles');
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Psr\Container\ContainerInterface as the method getParameter() does only exist in the following implementations of said interface: Container14\ProjectServiceContainer, ProjectServiceContainer, Symfony\Component\Depend...urationContainerBuilder, Symfony\Component\DependencyInjection\Container, Symfony\Component\Depend...ection\ContainerBuilder, Symfony\Component\Depend...\NoConstructorContainer, Symfony\Component\Depend...tainers\CustomContainer, Symfony\Component\Depend...ProjectServiceContainer, Symfony\Component\Depend...ProjectServiceContainer, Symfony_DI_PhpDumper_Test_Almost_Circular_Private, Symfony_DI_PhpDumper_Test_Almost_Circular_Public, Symfony_DI_PhpDumper_Test_Base64Parameters, Symfony_DI_PhpDumper_Test_Deep_Graph, Symfony_DI_PhpDumper_Test_EnvParameters, Symfony_DI_PhpDumper_Test_Inline_Self_Ref, Symfony_DI_PhpDumper_Test_Legacy_Privates, Symfony_DI_PhpDumper_Test_Rot13Parameters, Symfony_DI_PhpDumper_Test_Uninitialized_Reference.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
328
        $roles = array_keys($roleHierarchy);
329
        $theRoles = array();
330
331
        foreach ($roles as $role) {
332
            $theRoles[$role] = $role;
333
        }
334
335
        return $theRoles;
336
    }
337
338
    /**
339
     * Add roles to form.
340
     *
341
     * @param \Symfony\Component\Form\Form $form  The form in which to insert the roles
342
     * @param \App\Entity\Staff\Group      $group The entity to deal
343
     *
344
     * @return \Symfony\Component\Form\Form The form
345
     */
346
    public function addRolesAction($form, $group)
347
    {
348
        $form->add(
349
            'roles',
350
            ChoiceType::class,
351
            [
352
                'choices' => $this->getExistingRoles(),
353
                'choices_as_values' => true,
354
                'data' => $group->getRoles(),
355
                'label' => 'Roles',
356
                'expanded' => true,
357
                'multiple' => true,
358
                'mapped' => true,
359
            ]
360
        );
361
362
        return $form;
363
    }
364
365
    /**
366
     * Get the entity.
367
     *
368
     * @param string                                     $entityName Name of Entity
369
     * @param \Doctrine\Common\Persistence\ObjectManager $etm        ObjectManager instances
370
     *
371
     * @return array|\Doctrine\ORM\QueryBuilder|null Entity elements
372
     */
373
    private function getEntity($entityName, ObjectManager $etm)
374
    {
375
        $roles = ['ROLE_ADMIN', 'ROLE_SUPER_ADMIN'];
376
        switch ($entityName) {
377
            case 'Settings\Diverse\FamilyLog':
378
                $entities = $etm->getRepository('App:'.$entityName)->childrenHierarchy();
379
                break;
380
            default:
381
                if (null !== $this->getUser() && in_array($this->getUser()->getRoles()[0], $roles)) {
382
                    $entities = $etm->getRepository('App:'.$entityName)->getAllItems();
383
                } else {
384
                    $entities = $etm->getRepository('App:'.$entityName)->getItems();
385
                }
386
        }
387
388
        return $entities;
389
    }
390
}
391