Completed
Push — master ( 6c1856...1699d4 )
by Arnold
03:39
created

StateTrait::isLoggedOut()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Jasny\Auth\Authz;
6
7
use Jasny\Auth\AuthException;
8
use Jasny\Auth\AuthzInterface as Authz;
9
use Jasny\Auth\ContextInterface as Context;
10
use Jasny\Auth\User\PartiallyLoggedIn;
11
use Jasny\Auth\UserInterface as User;
12
use Jasny\Immutable;
13
14
/**
15
 * Trait for keeping state (user and context) in authz service.
16
 */
17
trait StateTrait
18
{
19
    use Immutable\With;
20
21
    /**
22
     * Current authenticated user
23
     */
24
    protected ?User $user = null;
25
26
    /**
27
     * The authorization context. This could be an organization, where a user has specific roles per organization
28
     * rather than roles globally.
29
     */
30
    protected ?Context $context = null;
31
32
    /**
33
     * Get a copy of the service for the given user.
34
     *
35
     * @param User|null $user
36
     * @return static&Authz
37
     */
38 26
    public function forUser(?User $user): Authz
39
    {
40 26
        return $this->withProperty('user', $user);
41
    }
42
43
    /**
44
     * Get a copy of the service for the given context.
45
     * Returns $this if authz hasn't changed.
46
     *
47
     * @param Context|null $context
48
     * @return static&Authz
49
     */
50 1
    public function inContextOf(?Context $context): Authz
51
    {
52 1
        return $this->withProperty('context', $context);
53
    }
54
55
    /**
56
     * Get current authenticated user.
57
     *
58
     * @throws AuthException if no user is logged in.
59
     */
60 3
    final public function user(): User
61
    {
62 3
        if ($this->user === null) {
63 1
            throw new AuthException("The user is not logged in");
64
        }
65
66 2
        return $this->user;
67
    }
68
69
    /**
70
     * Get the current context.
71
     */
72 1
    final public function context(): ?Context
73
    {
74 1
        return $this->context;
75
    }
76
77
    /**
78
     * Check if the current user is logged in.
79
     */
80 3
    public function isLoggedIn(): bool
81
    {
82 3
        return $this->user !== null && !$this->isPartiallyLoggedIn();
83
    }
84
85
    /**
86
     * Check if the current user is partially logged in.
87
     * Typically this means MFA verification is required.
88
     */
89 3
    public function isPartiallyLoggedIn(): bool
90
    {
91 3
        return $this->user instanceof PartiallyLoggedIn;
92
    }
93
94
    /**
95
     * Check if current user is not logged in or partially logged in.
96
     */
97 3
    public function isLoggedOut(): bool
98
    {
99 3
        return $this->user === null;
100
    }
101
}
102