Completed
Push — bugfix/enforce_raa ( 216a2a...11abae )
by
unknown
02:20
created

AuthorizationRepository::getInstitutionsForRole()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 34
rs 9.376
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
3
/**
4
 * Copyright 2014 SURFnet bv
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 *     http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18
19
namespace Surfnet\StepupMiddleware\ApiBundle\Identity\Repository;
20
21
use Doctrine\ORM\EntityManager;
22
use Doctrine\ORM\Query\Expr\Join;
23
use Surfnet\Stepup\Configuration\Value\InstitutionRole;
24
use Surfnet\Stepup\Identity\Collection\InstitutionCollection;
25
use Surfnet\Stepup\Identity\Value\IdentityId;
26
use Surfnet\Stepup\Identity\Value\Institution;
27
use Surfnet\StepupMiddleware\ApiBundle\Configuration\Entity\InstitutionAuthorization;
28
use Surfnet\StepupMiddleware\ApiBundle\Identity\Entity\RaListing;
29
use Surfnet\StepupMiddleware\ApiBundle\Identity\Value\AuthorityRole;
30
31
class AuthorizationRepository
32
{
33
    /**
34
     * @var EntityManager
35
     */
36
    private $entityManager;
37
38
    public function __construct(EntityManager $entityManager)
0 ignored issues
show
Bug introduced by
You have injected the EntityManager via parameter $entityManager. 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...
39
    {
40
        $this->entityManager = $entityManager;
41
    }
42
43
    /**
44
     * Return all institutions were the actor has the specified role for
45
     * The returned institutions are used to filter query results on
46
     *
47
     * @param InstitutionRole $role
48
     * @param IdentityId $actorId
49
     * @return InstitutionCollection
50
     */
51
    public function getInstitutionsForRole(InstitutionRole $role, IdentityId $actorId)
52
    {
53
        $qb = $this->entityManager->createQueryBuilder()
54
            ->select("a.institution")
55
            ->from(RaListing::class, 'i')
56
            ->innerJoin(RaListing::class, 'r', Join::WITH, "i.institution = r.raInstitution")
57
            ->innerJoin(
58
                InstitutionAuthorization::class,
59
                'a',
60
                Join::WITH,
61
                "i.institution = a.institutionRelation AND a.institutionRole IN (:authorizationRoles)"
62
            )
63
            ->where("r.identityId = :identityId AND r.role IN(:roles)")
64
            ->groupBy("a.institution");
65
66
        $qb->setParameter('identityId', (string)$actorId);
67
        $qb->setParameter(
68
            'authorizationRoles',
69
            $this->getAllowedInstitutionRoles($role)
70
        );
71
        $qb->setParameter(
72
            'roles',
73
            $this->getAllowedIdentityRoles($role)
74
        );
75
76
        $institutions = $qb->getQuery()->getArrayResult();
77
78
        $result = new InstitutionCollection();
79
        foreach ($institutions as $institution) {
80
            $result->add(new Institution((string)$institution['institution']));
81
        }
82
83
        return $result;
84
    }
85
86
    /**
87
     * This is the mapping to look up allowed institution roles
88
     * - if the institution role is RA we should look if the configured institution has RA role
89
     * - if the institution role is RAA we should look if the configured institution has RAA role
90
     *
91
     * @param InstitutionRole $role
92
     * @return array
93
     */
94 View Code Duplication
    private function getAllowedInstitutionRoles(InstitutionRole $role)
0 ignored issues
show
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...
95
    {
96
        switch (true) {
97
            case $role->equals(InstitutionRole::useRa()):
98
                return [InstitutionRole::ROLE_USE_RA];
99
            case $role->equals(InstitutionRole::useRaa()):
100
                return [InstitutionRole::ROLE_USE_RAA];
101
            default:
102
                return [];
103
        }
104
    }
105
106
    /**
107
     * This is the mapping to look up allowed identity roles for a specific institution role
108
     * - if the institution role is RA we should look if the identity has a RA or RAA role
109
     * - if the institution role is RAA we should look if the identity has a RAA role
110
     *
111
     * @param InstitutionRole $role
112
     * @return array
113
     */
114 View Code Duplication
    private function getAllowedIdentityRoles(InstitutionRole $role)
0 ignored issues
show
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...
115
    {
116
        switch (true) {
117
            case $role->equals(InstitutionRole::useRa()):
118
                return [AuthorityRole::ROLE_RA, AuthorityRole::ROLE_RAA];
119
            case $role->equals(InstitutionRole::useRaa()):
120
                return [AuthorityRole::ROLE_RAA];
121
            default:
122
                return [];
123
        }
124
    }
125
}
126