Passed
Push — master ( af16b4...bf34ca )
by Arnold
03:18
created

StateTrait::user()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

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