Completed
Push — master ( 647efd...c7681f )
by Jeroen
38:40 queued 32:44
created

AclNativeHelper   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 137
Duplicated Lines 29.2 %

Coupling/Cohesion

Components 1
Dependencies 9

Test Coverage

Coverage 92.73%

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 9
dl 40
loc 137
ccs 51
cts 55
cp 0.9273
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 7 7 1
C apply() 33 83 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 = array();
90 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...
91 2
            $user = $token->getUser();
92 2
            if (method_exists($this->roleHierarchy, 'getReachableRoleNames')) {
93 2
                $userRoles = $this->roleHierarchy->getReachableRoleNames($token->getRoleNames());
94
            } else {
95
                // Symfony 3.4 compatibility
96
                $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...
97
            }
98
        }
99
100
        // Security context does not provide anonymous role automatically.
101 2
        $uR = array('"IS_AUTHENTICATED_ANONYMOUSLY"');
102
103 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...
104
            // The reason we ignore this is because by default FOSUserBundle adds ROLE_USER for every user
105 2
            if (is_string($role)) {
106 2
                if ($role !== 'ROLE_USER') {
107 2
                    $uR[] = '"' . $role . '"';
108
                }
109
            } else {
110
                // Symfony 3.4 compatibility
111
                if ($role->getRole() !== 'ROLE_USER') {
112
                    $uR[] = '"' . $role->getRole() . '"';
113
                }
114
            }
115
        }
116 2
        $uR = array_unique($uR);
117 2
        $inString = implode(' OR s.identifier = ', $uR);
118
119 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...
120 1
            $inString .= ' OR s.identifier = "' . str_replace(
121 1
                '\\',
122 1
                '\\\\',
123 1
                \get_class($user)
0 ignored issues
show
Bug introduced by
The variable $user 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...
124 1
            ) . '-' . $user->getUserName() . '"';
125
        }
126
127
        $joinTableQuery = <<<SELECTQUERY
128 2
SELECT DISTINCT o.object_identifier as id FROM {$databasePrefix}acl_object_identities as o
129 2
INNER JOIN {$databasePrefix}acl_classes c ON c.id = o.class_id
130 2
LEFT JOIN {$databasePrefix}acl_entries e ON (
131
    e.class_id = o.class_id AND (e.object_identity_id = o.id
132 2
    OR {$aclConnection->getDatabasePlatform()->getIsNullExpression('e.object_identity_id')})
133
)
134 2
LEFT JOIN {$databasePrefix}acl_security_identities s ON (
135
s.id = e.security_identity_id
136
)
137 2
WHERE c.class_type = {$rootEntity}
138 2
AND (s.identifier = {$inString})
139 2
AND e.mask & {$mask} > 0
140
SELECTQUERY;
141
142 2
        $query->join($linkAlias, '(' . $joinTableQuery . ')', 'perms_', 'perms_.id = ' . $linkAlias . '.' . $linkField);
143
144 2
        return $query;
145
    }
146
147
    /**
148
     * @return null|TokenStorageInterface
149
     */
150 1
    public function getTokenStorage()
151
    {
152 1
        return $this->tokenStorage;
153
    }
154
}
155