Completed
Pull Request — 5.6 (#2830)
by Jeroen
14:14
created

AclNativeHelper   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 138
Duplicated Lines 28.99 %

Coupling/Cohesion

Components 1
Dependencies 9

Test Coverage

Coverage 92.86%

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 9
dl 40
loc 138
ccs 52
cts 56
cp 0.9286
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 7 7 1
C apply() 33 84 11
A getTokenStorage() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Kunstmaan\AdminBundle\Helper\Security\Acl;
4
5
use Doctrine\DBAL\Query\QueryBuilder;
6
use Doctrine\ORM\EntityManager;
7
use Kunstmaan\AdminBundle\Helper\Security\Acl\Permission\MaskBuilder;
8
use Kunstmaan\AdminBundle\Helper\Security\Acl\Permission\PermissionDefinition;
9
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
10
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
11
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
12
13
/**
14
 * AclHelper is a helper class to help setting the permissions when querying using native queries
15
 *
16
 * @see https://gist.github.com/1363377
17
 */
18
class AclNativeHelper
19
{
20
    /**
21
     * @var EntityManager
22
     */
23
    private $em = null;
24
25
    /**
26
     * @var TokenStorageInterface
27
     */
28
    private $tokenStorage = null;
29
30
    /**
31
     * @var RoleHierarchyInterface
32
     */
33
    private $roleHierarchy = null;
34
35
    /**
36
     * @var bool
37
     */
38
    private $permissionsEnabled;
39
40
    /**
41
     * Constructor.
42
     *
43
     * @param EntityManager          $em           The entity manager
44
     * @param TokenStorageInterface  $tokenStorage The security context
45
     * @param RoleHierarchyInterface $rh           The role hierarchies
46
     */
47 3 View Code Duplication
    public function __construct(EntityManager $em, TokenStorageInterface $tokenStorage, RoleHierarchyInterface $rh, $permissionsEnabled = true)
0 ignored issues
show
Bug introduced by
You have injected the EntityManager via parameter $em. This is generally not recommended as it might get closed and become unusable. Instead, it is recommended to inject the ManagerRegistry and retrieve the EntityManager via getManager() each time you need it.

The EntityManager might become unusable for example if a transaction is rolled back and it gets closed. Let’s assume that somewhere in your application, or in a third-party library, there is code such as the following:

function someFunction(ManagerRegistry $registry) {
    $em = $registry->getManager();
    $em->getConnection()->beginTransaction();
    try {
        // Do something.
        $em->getConnection()->commit();
    } catch (\Exception $ex) {
        $em->getConnection()->rollback();
        $em->close();

        throw $ex;
    }
}

If that code throws an exception and the EntityManager is closed. Any other code which depends on the same instance of the EntityManager during this request will fail.

On the other hand, if you instead inject the ManagerRegistry, the getManager() method guarantees that you will always get a usable manager instance.

Loading history...
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
48
    {
49 3
        $this->em = $em;
50 3
        $this->tokenStorage = $tokenStorage;
51 3
        $this->roleHierarchy = $rh;
52 3
        $this->permissionsEnabled = $permissionsEnabled;
53 3
    }
54
55
    /**
56
     * Apply the ACL constraints to the specified query builder, using the permission definition
57
     *
58
     * @param QueryBuilder         $queryBuilder  The query builder
59
     * @param PermissionDefinition $permissionDef The permission definition
60
     *
61
     * @return QueryBuilder
62
     */
63 2
    public function apply(QueryBuilder $queryBuilder, PermissionDefinition $permissionDef)
64
    {
65 2
        if (!$this->permissionsEnabled) {
66
            return $queryBuilder;
67
        }
68
69 2
        $aclConnection = $this->em->getConnection();
70
71 2
        $databasePrefix = is_file($aclConnection->getDatabase()) ? '' : $aclConnection->getDatabase() . '.';
72 2
        $rootEntity = $permissionDef->getEntity();
73 2
        $linkAlias = $permissionDef->getAlias();
74
        // Only tables with a single ID PK are currently supported
75 2
        $linkField = $this->em->getClassMetadata($rootEntity)->getSingleIdentifierColumnName();
76
77 2
        $rootEntity = '"' . str_replace('\\', '\\\\', $rootEntity) . '"';
78 2
        $query = $queryBuilder;
79
80 2
        $builder = new MaskBuilder();
81 2 View Code Duplication
        foreach ($permissionDef->getPermissions() as $permission) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
82 2
            $mask = \constant(\get_class($builder) . '::MASK_' . strtoupper($permission));
83 2
            $builder->add($mask);
84
        }
85 2
        $mask = $builder->get();
86
87
        /* @var $token TokenInterface */
88 2
        $token = $this->tokenStorage->getToken();
89 2
        $userRoles = [];
90 2
        $user = null;
91 2 View Code Duplication
        if (!\is_null($token)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
92 2
            $user = $token->getUser();
93 2
            if (method_exists($this->roleHierarchy, 'getReachableRoleNames')) {
94 2
                $userRoles = $this->roleHierarchy->getReachableRoleNames($token->getRoleNames());
95
            } else {
96
                // Symfony 3.4 compatibility
97
                $userRoles = $this->roleHierarchy->getReachableRoles($token->getRoles());
0 ignored issues
show
Deprecated Code introduced by
The method Symfony\Component\Securi...enInterface::getRoles() has been deprecated with message: since Symfony 4.3, use the getRoleNames() method instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
98
            }
99
        }
100
101
        // Security context does not provide anonymous role automatically.
102 2
        $uR = ['"IS_AUTHENTICATED_ANONYMOUSLY"'];
103
104 2 View Code Duplication
        foreach ($userRoles as $role) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
105
            // The reason we ignore this is because by default FOSUserBundle adds ROLE_USER for every user
106 2
            if (is_string($role)) {
107 2
                if ($role !== 'ROLE_USER') {
108 2
                    $uR[] = '"' . $role . '"';
109
                }
110
            } else {
111
                // Symfony 3.4 compatibility
112
                if ($role->getRole() !== 'ROLE_USER') {
113
                    $uR[] = '"' . $role->getRole() . '"';
114
                }
115
            }
116
        }
117 2
        $uR = array_unique($uR);
118 2
        $inString = implode(' OR s.identifier = ', $uR);
119
120 2 View Code Duplication
        if (\is_object($user)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
121 1
            $inString .= ' OR s.identifier = "' . str_replace(
122 1
                '\\',
123 1
                '\\\\',
124 1
                \get_class($user)
125 1
            ) . '-' . $user->getUserName() . '"';
0 ignored issues
show
Bug introduced by
The method getUserName does only exist in Symfony\Component\Security\Core\User\UserInterface, but not in Stringable.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
126
        }
127
128
        $joinTableQuery = <<<SELECTQUERY
129 2
SELECT DISTINCT o.object_identifier as id FROM {$databasePrefix}acl_object_identities as o
130 2
INNER JOIN {$databasePrefix}acl_classes c ON c.id = o.class_id
131 2
LEFT JOIN {$databasePrefix}acl_entries e ON (
132
    e.class_id = o.class_id AND (e.object_identity_id = o.id
133 2
    OR {$aclConnection->getDatabasePlatform()->getIsNullExpression('e.object_identity_id')})
134
)
135 2
LEFT JOIN {$databasePrefix}acl_security_identities s ON (
136
s.id = e.security_identity_id
137
)
138 2
WHERE c.class_type = {$rootEntity}
139 2
AND (s.identifier = {$inString})
140 2
AND e.mask & {$mask} > 0
141
SELECTQUERY;
142
143 2
        $query->join($linkAlias, '(' . $joinTableQuery . ')', 'perms_', 'perms_.id = ' . $linkAlias . '.' . $linkField);
144
145 2
        return $query;
146
    }
147
148
    /**
149
     * @return TokenStorageInterface|null
150
     */
151 1
    public function getTokenStorage()
152
    {
153 1
        return $this->tokenStorage;
154
    }
155
}
156