Test Failed
Pull Request — master (#24)
by Sergei
01:58
created

CurrentUser::isGuest()   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 0
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 Authenticator $authenticator;
16
17
    public function __construct(Authenticator $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
     * @see getIdentity()
41
     */
42
    public function isGuest(): bool
43
    {
44
        return $this->getIdentity() instanceof GuestIdentity;
45
    }
46
47
    /**
48
     * Returns a value that uniquely represents the user.
49
     *
50
     * @throws Throwable
51
     *
52
     * @return string the unique identifier for the user. If `null`, it means the user is a guest.
53
     *
54
     * @see getIdentity()
55
     */
56
    public function getId(): ?string
57
    {
58
        return $this->authenticator->getIdentity()->getId();
59
    }
60
61
    /**
62
     * Checks if the user can perform the operation as specified by the given permission.
63
     *
64
     * Note that you must provide access checker via {{@see CurrentUser::setAccessChecker()}} in order to use this method.
65
     * Otherwise it will always return false.
66
     *
67
     * @param string $permissionName the name of the permission (e.g. "edit post") that needs access check.
68
     * @param array $params name-value pairs that would be passed to the rules associated
69
     * with the roles and permissions assigned to the user.
70
     *
71
     * @throws Throwable
72
     *
73
     * @return bool whether the user can perform the operation as specified by the given permission.
74
     */
75
    public function can(string $permissionName, array $params = []): bool
76
    {
77
        if ($this->accessChecker === null) {
78
            return false;
79
        }
80
81
        return $this->accessChecker->userHasPermission($this->getId(), $permissionName, $params);
82
    }
83
}
84