File size: 1,755 Bytes
d2897cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php

namespace Mautic\UserBundle\Entity;

use Doctrine\ORM\Query;
use Mautic\CoreBundle\Cache\ResultCacheHelper;
use Mautic\CoreBundle\Cache\ResultCacheOptions;
use Mautic\CoreBundle\Entity\CommonRepository;

/**
 * @extends CommonRepository<Permission>
 */
class PermissionRepository extends CommonRepository
{
    /**
     * Delete all permissions for a specific role.
     */
    public function purgeRolePermissions(Role $role): void
    {
        $query = $this
            ->createQueryBuilder('p')
            ->delete(Permission::class, 'p')
            ->where('p.role = :role')
            ->setParameter('role', $role)
            ->getQuery();
        $query->execute();
    }

    /**
     * Retrieves array of permissions for a set role.  If $forForm, then the array will contain.
     *
     * @param bool $forForm
     */
    public function getPermissionsByRole(Role $role, $forForm = false): array
    {
        $query = $this
            ->createQueryBuilder('p')
            ->where('p.role = :role')
            ->orderBy('p.bundle')
            ->setParameter(':role', $role)
            ->getQuery();
        ResultCacheHelper::enableOrmQueryCache($query, new ResultCacheOptions(Permission::CACHE_NAMESPACE));
        $results = $query->getResult(Query::HYDRATE_ARRAY);

        // rearrange the array to meet needs
        $permissions = [];
        foreach ($results as $r) {
            if ($forForm) {
                $permissions[$r['bundle']][$r['id']] = [
                    'name'    => $r['name'],
                    'bitwise' => $r['bitwise'],
                ];
            } else {
                $permissions[$r['bundle']][$r['name']] = $r['bitwise'];
            }
        }

        return $permissions;
    }
}