1: <?php declare(strict_types=1);
2:
3: namespace Salient\Http\OAuth2;
4:
5: use Salient\Contract\Core\Immutable;
6: use Salient\Contract\Core\Readable;
7: use Salient\Contract\Http\AccessTokenInterface;
8: use Salient\Core\Concern\ReadsProtectedProperties;
9: use Salient\Utility\Date;
10: use DateTimeImmutable;
11: use DateTimeInterface;
12: use InvalidArgumentException;
13:
14: /**
15: * A token issued by an authorization provider for access to protected resources
16: *
17: * @property-read string $Token
18: * @property-read string $Type
19: * @property-read DateTimeImmutable|null $Expires
20: * @property-read string[] $Scopes
21: * @property-read array<string,mixed> $Claims
22: */
23: final class AccessToken implements AccessTokenInterface, Immutable, Readable
24: {
25: use ReadsProtectedProperties;
26:
27: protected string $Token;
28: protected string $Type;
29: protected ?DateTimeImmutable $Expires;
30: /** @var string[] */
31: protected array $Scopes;
32: /** @var array<string,mixed> */
33: protected array $Claims;
34:
35: /**
36: * Creates a new AccessToken object
37: *
38: * @param DateTimeInterface|int|null $expires `null` if the access token's
39: * lifetime is unknown, otherwise a {@see DateTimeInterface} or Unix
40: * timestamp representing its expiration time.
41: * @param string[]|null $scopes
42: * @param array<string,mixed>|null $claims
43: */
44: public function __construct(
45: string $token,
46: string $type,
47: $expires,
48: ?array $scopes = null,
49: ?array $claims = null
50: ) {
51: if (is_int($expires) && $expires < 0) {
52: throw new InvalidArgumentException(sprintf(
53: 'Invalid $expires: %d',
54: $expires
55: ));
56: }
57:
58: $this->Token = $token;
59: $this->Type = $type;
60: $this->Expires = $expires instanceof DateTimeInterface
61: ? Date::immutable($expires)
62: : ($expires === null
63: ? null
64: : new DateTimeImmutable("@$expires"));
65: $this->Scopes = $scopes ?: [];
66: $this->Claims = $claims ?: [];
67: }
68:
69: /**
70: * @inheritDoc
71: */
72: public function getToken(): string
73: {
74: return $this->Token;
75: }
76:
77: /**
78: * @inheritDoc
79: */
80: public function getTokenType(): string
81: {
82: return $this->Type;
83: }
84: }
85: