Passed
Push — main ( a27a58...542219 )
by Peter
04:05
created

AccessToken   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Test Coverage

Coverage 60%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
c 1
b 0
f 0
dl 0
loc 53
ccs 12
cts 20
cp 0.6
rs 10
wmc 9

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getHttpClient() 0 7 1
A getExpiresAt() 0 3 1
A getExpiresIn() 0 3 1
A __construct() 0 8 3
A getAccessToken() 0 3 1
A resolveCustomAuth() 0 7 2
1
<?php
2
3
namespace Pelmered\LaravelHttpOAuthHelper;
4
5
use Carbon\Carbon;
6
use Closure;
7
use Illuminate\Http\Client\PendingRequest;
8
use InvalidArgumentException;
9
10
final class AccessToken
11
{
12
    public const TYPE_BEARER = 'Bearer';
13
14
    public const TYPE_QUERY = 'query';
15
16
    public const TYPE_CUSTOM = 'custom';
17
18
    protected string $tokenName = 'token';
19
20 12
    public function __construct(
21
        protected string $accessToken,
22
        protected Carbon $expiresAt,
23
        protected string $tokenType = self::TYPE_BEARER,
24
        protected ?Closure $customCallback = null
25
    ) {
26 12
        if ($tokenType === self::TYPE_CUSTOM && is_null($customCallback)) {
27
            throw new InvalidArgumentException('customCallback must be set when using AUTH_TYPE_CUSTOM');
28
        }
29
    }
30
31 7
    public function getAccessToken(): string
32
    {
33 7
        return $this->accessToken;
34
    }
35
36
    public function getExpiresAt(): Carbon
37
    {
38
        return $this->expiresAt;
39
    }
40
41 6
    public function getExpiresIn(): int
42
    {
43 6
        return (int) round(Carbon::now()->diffInSeconds($this->expiresAt));
44
    }
45
46 4
    public function getHttpClient(PendingRequest $httpClient): PendingRequest
47
    {
48 4
        return match ($this->tokenType) {
49 3
            self::TYPE_BEARER => $httpClient->withToken($this->accessToken),
50 1
            self::TYPE_QUERY  => $httpClient->withQueryParameters([$this->tokenName => $this->accessToken]),
51
            self::TYPE_CUSTOM => $this->resolveCustomAuth($httpClient),
52 4
            default           => throw new InvalidArgumentException('Invalid auth type')
53 4
        };
54
    }
55
56
    protected function resolveCustomAuth(PendingRequest $httpClient): PendingRequest
57
    {
58
        if (! is_callable($this->customCallback)) {
59
            throw new InvalidArgumentException('customCallback must be callable');
60
        }
61
62
        return ($this->customCallback)($httpClient);
63
    }
64
}
65