Test Failed
Pull Request — master (#24)
by Sergei
85:01 queued 83:05
created

CurrentUser::setAccessChecker()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\User;
6
7
use Throwable;
8
use Yiisoft\Access\AccessCheckerInterface;
9
use Yiisoft\Auth\IdentityInterface;
10
11
class CurrentUser
12
{
13
    private ?AccessCheckerInterface $accessChecker = null;
14
15
    private AuthenticatorInterface $authenticator;
16
17
    public function __construct(AuthenticatorInterface $authenticator)
18
    {
19
        $this->authenticator = $authenticator;
20
    }
21
22
    public function setAccessChecker(AccessCheckerInterface $accessChecker): void
23
    {
24
        $this->accessChecker = $accessChecker;
25
    }
26
27
    /**
28
     * Returns the identity object associated with the currently logged-in user.
29
     */
30
    public function getIdentity(): IdentityInterface
31
    {
32
        return $this->authenticator->getIdentity();
33
    }
34
35
    /**
36
     * Returns a value indicating whether the user is a guest (not authenticated).
37
     *
38
     * @return bool whether the current user is a guest.
39
     */
40
    public function isGuest(): bool
41
    {
42
        return $this->authenticator->getIdentity() instanceof GuestIdentity;
43
    }
44
45
    /**
46
     * Returns a value that uniquely represents the user.
47
     *
48
     * @throws Throwable
49
     *
50
     * @return string the unique identifier for the user. If `null`, it means the user is a guest.
51
     *
52
     * @see getIdentity()
53
     */
54
    public function getId(): ?string
55
    {
56
        return $this->authenticator->getIdentity()->getId();
57
    }
58
59
    /**
60
     * Checks if the user can perform the operation as specified by the given permission.
61
     *
62
     * Note that you must provide access checker via {{@see CurrentUser::setAccessChecker()}} in order
63
     * to use this method. Otherwise it will always return false.
64
     *
65
     * @param string $permissionName the name of the permission (e.g. "edit post") that needs access check.
66
     * @param array $params name-value pairs that would be passed to the rules associated
67
     * with the roles and permissions assigned to the user.
68
     *
69
     * @throws Throwable
70
     *
71
     * @return bool whether the user can perform the operation as specified by the given permission.
72
     */
73
    public function can(string $permissionName, array $params = []): bool
74
    {
75
        if ($this->accessChecker === null) {
76
            return false;
77
        }
78
79
        return $this->accessChecker->userHasPermission($this->getId(), $permissionName, $params);
80
    }
81
}
82