Completed
Push — master ( 265a2d...f9e310 )
by jerome
02:58
created

UserGroupResolver   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 4
Bugs 0 Features 0
Metric Value
wmc 9
c 4
b 0
f 0
lcom 1
cbo 2
dl 0
loc 58
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
B getAccessibleGroups() 0 27 6
A getAccessibleGroupsId() 0 6 1
A isGranted() 0 4 1
1
<?php
2
3
/**
4
 * This file is part of Dedipanel project
5
 *
6
 * (c) 2010-2015 Dedipanel <http://www.dedicated-panel.net>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace DP\Core\UserBundle\Service;
13
14
use DP\Core\UserBundle\Entity\User;
15
use Symfony\Component\Security\Core\SecurityContextInterface;
16
use DP\Core\UserBundle\Entity\GroupRepository;
17
18
class UserGroupResolver
19
{
20
    /**
21
     * @var GroupRepository
22
     */
23
    protected $groupRepo;
24
25
    /**
26
     * @var SecurityContextInterface
27
     */
28
    protected $context;
29
    
30
    public function __construct(GroupRepository $groupRepo, SecurityContextInterface $context)
31
    {
32
        $this->groupRepo = $groupRepo;
33
        $this->context   = $context;
34
    }
35
    
36
    public function getAccessibleGroups()
37
    {
38
        $groups = [];
39
        $user   = $this->context->getToken()->getUser();
40
41
        if ($this->isGranted(User::ROLE_SUPER_ADMIN)) {
42
            $groups = $this
43
                ->groupRepo
44
                ->getChildren(null)
45
            ;
46
        }
47
        elseif ($this->isGranted(User::ROLE_ADMIN)) {
48
            $groups = $this
49
                ->groupRepo
50
                ->getChildren($user->getGroup(), false, null, "asc", true)
51
            ;
52
        }
53
        elseif ($user->getGroup() !== null) {
54
            $groups = [$user->getGroup()];
55
        }
56
57
        if (empty($groups) && !$this->isGranted(User::ROLE_ADMIN)) {
58
            throw new \RuntimeException('Security error! This user should not have empty group access. This can lead to security breach.');
59
        }
60
61
        return $groups;
62
    }
63
    
64
    public function getAccessibleGroupsId()
65
    {
66
        return array_map(function ($group) {
67
            return $group->getId();
68
        }, $this->getAccessibleGroups());
69
    }
70
71
    private function isGranted($role)
72
    {
73
        return $this->context->isGranted($role);
74
    }
75
}
76