Completed
Push — master ( be772b...99d542 )
by Tomas
16:16
created

UserManagerAbstract::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace Eziat\PermissionBundle\Model;
6
7
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
8
9
/**
10
 * @author Tomas Jakl <[email protected]>
11
 */
12
abstract class UserManagerAbstract implements UserManagerInterface
13
{
14
    /**
15
     * @var TokenStorageInterface
16
     */
17
    protected $tokenStorage;
18
19
    public function __construct(TokenStorageInterface $tokenStorage)
20
    {
21
        $this->tokenStorage = $tokenStorage;
22
    }
23
24
    /**
25
     * Gets the logged in user from any place of the code.
26
     * returns null if no user is logged in.
27
     */
28
    protected function getLoggedInUser() : ?UserPermissionInterface
29
    {
30
        $tokenUser = $this->tokenStorage->getToken()->getUser();
31
        if ($tokenUser == "anon.") {
32
            return null;
33
        } else {
34
            return $tokenUser;
35
        }
36
    }
37
38
    /**
39
     * {@inheritdoc}
40
     */
41
    public function hasPermissions(UserPermissionInterface $user, array $permissions) : bool
42
    {
43
        $userPermissions = $this->getPermissions($user);
44
45
        foreach ($permissions as $permission) {
46
            if (!in_array($permission, $userPermissions)) {
47
                return false;
48
            }
49
        }
50
51
        return true;
52
    }
53
54
    /**
55
     * {@inheritdoc}
56
     */
57
    public function hasPermission(UserPermissionInterface $user, $permission) : bool
58
    {
59
        return $this->hasPermission($user, [$permission]);
60
    }
61
62
    protected function getUserPermissions(?UserPermissionInterface $user = null) : array
63
    {
64
        $permissions = [];
65
        $user        = $user !== null ? $user : $this->getLoggedInUser();
66
67
        if ($user === null) {
68
            return $permissions;
69
        }
70
71
        foreach ($user->getPermissions() as $permission) {
72
            $permissions[] = $permission->getName();
73
        }
74
75
        return $permissions;
76
    }
77
}