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
|
|
|
|