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
|
13 |
|
public function __construct( |
19
|
|
|
protected string $accessToken, |
20
|
|
|
protected Carbon $expiresAt, |
21
|
|
|
protected string $tokenType = self::TYPE_BEARER, |
22
|
|
|
protected string $tokenName = 'token', |
23
|
|
|
protected ?Closure $customCallback = null, |
24
|
|
|
) { |
25
|
13 |
|
if ($tokenType === self::TYPE_CUSTOM && is_null($customCallback)) { |
26
|
|
|
throw new InvalidArgumentException('customCallback must be set when using AUTH_TYPE_CUSTOM'); |
27
|
|
|
} |
28
|
|
|
} |
29
|
|
|
|
30
|
8 |
|
public function getAccessToken(): string |
31
|
|
|
{ |
32
|
8 |
|
return $this->accessToken; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
public function getExpiresAt(): Carbon |
36
|
|
|
{ |
37
|
|
|
return $this->expiresAt; |
38
|
|
|
} |
39
|
|
|
|
40
|
7 |
|
public function getExpiresIn(): int |
41
|
|
|
{ |
42
|
7 |
|
return (int) round(Carbon::now()->diffInSeconds($this->expiresAt)); |
43
|
|
|
} |
44
|
|
|
|
45
|
1 |
|
public function getTokenType(): string |
46
|
|
|
{ |
47
|
1 |
|
return $this->tokenType; |
48
|
|
|
} |
49
|
|
|
|
50
|
1 |
|
public function getTokenName(): string |
51
|
|
|
{ |
52
|
1 |
|
return $this->tokenName; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
public function getCustomCallback(): ?Closure |
56
|
|
|
{ |
57
|
|
|
return $this->customCallback; |
58
|
|
|
} |
59
|
|
|
|
60
|
5 |
|
public function getHttpClient(PendingRequest $httpClient): PendingRequest |
61
|
|
|
{ |
62
|
5 |
|
return match ($this->tokenType) { |
63
|
4 |
|
self::TYPE_BEARER => $httpClient->withToken($this->accessToken), |
64
|
1 |
|
self::TYPE_QUERY => $httpClient->withQueryParameters([$this->tokenName => $this->accessToken]), |
65
|
|
|
self::TYPE_CUSTOM => $this->resolveCustomAuth($httpClient), |
66
|
5 |
|
default => throw new InvalidArgumentException('Invalid auth type') |
67
|
5 |
|
}; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
protected function resolveCustomAuth(PendingRequest $httpClient): PendingRequest |
71
|
|
|
{ |
72
|
|
|
if (! is_callable($this->customCallback)) { |
73
|
|
|
throw new InvalidArgumentException('customCallback must be callable'); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
return ($this->customCallback)($httpClient); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|