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