Token::allowedScope()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Spinen\Halo\Api;
4
5
use Carbon\Carbon;
6
7
class Token
8
{
9
    // TODO: Is this a good length?
10
    public const EXPIRE_BUFFER = 5;
11
12
    public Carbon $expires_at;
13
14
    // TODO: Should scope be an array? An enum?
15
    // 'all',
16
    // 'email',
17
    // 'offline_access',
18
    // 'openid',
19
    // 'profile',
20
    // 'roles',
21
22 55
    public function __construct(
23
        public ?string $access_token = null,
24
        protected int $expires_in = 3600,
25
        public ?string $id_token = null,
26
        public ?string $refresh_token = null,
27
        public string $scope = 'all',
28
        public string $token_type = 'Bearer',
29
        public ?string $grant_type = null,
30
    ) {
31 55
        $this->expires_at = Carbon::now()->addSeconds($expires_in);
32
    }
33
34 12
    public function __toString(): string
35
    {
36 12
        return $this->token_type.' '.$this->access_token;
37
    }
38
39
    /**
40
     * Check to see if the scope is in the list of scopes for the token
41
     */
42 3
    public function allowedScope(string $scope): bool
43
    {
44 3
        return in_array(
45 3
            haystack: explode(separator: ' ', string: $this->scope ?? ''),
46 3
            needle: $scope,
47 3
        );
48
    }
49
50
    /**
51
     * If there is a token, has it expired
52
     */
53 26
    public function isExpired(): bool
54
    {
55 26
        return is_null($this->access_token)
56 1
            ? false
57 26
            : $this->validFor() <= self::EXPIRE_BUFFER;
58
    }
59
60
    /**
61
     * If there is a token & it has not expired & if provided a scope,
62
     * check to see if it is allowed scope
63
     */
64 27
    public function isValid(?string $scope = null): bool
65
    {
66 27
        return ! is_null($this->access_token) &&
67 27
            ! $this->isExpired() &&
68 27
            ($scope ? $this->allowedScope($scope) : true);
69
    }
70
71
    /**
72
     * If there is a refresh token & the token expires within the BUFFER
73
     */
74 8
    public function needsRefreshing(): bool
75
    {
76 8
        return is_null($this->refresh_token)
77 2
            ? false
78 8
            : $this->validFor() <= self::EXPIRE_BUFFER;
79
    }
80
81
    /**
82
     * If there is a token, how many seconds is left before expires
83
     */
84 28
    public function validFor(): int
85
    {
86 28
        return is_null($this->access_token) || Carbon::now()->gte($this->expires_at)
87 4
            ? 0
88 28
            : (int) floor(abs(Carbon::now()->diffInSeconds($this->expires_at)));
89
    }
90
}
91